JDD
JDD

Reputation: 417

Python OpenCV crashes when doing a Hough transform from webcam

I think I've figured out the problem. I'm using a IP webcam stream, doing a canny edge and hough transform. Then showing the overlayed transform and the original image. So pretty much just looks like the normal web cam but the horizontal lines are highlighted. and I'm looking for horizontal lines in the image. It works just fine as long as there are horizontal lines in it. If I start the cam and there aren't any horizontal lines, I get the error:

 Traceback (most recent call last):
  File "/home/Desktop/hough.py", line 16, in <module>
  for line in lines[0]:
  TypeError: 'NoneType' object has no attribute '__getitem__'

Here's the whole code. I'm very new to python and opencv so I'm not sure how to fix this. I'd like it to just show the blank image when there aren't any horizontal lines so I can have a continuous stream.

Also my next task is to try and save the images into a video. Any help on that part would be greatly appreciated. thanks!

import cv2
import urllib
import math


cv2.namedWindow('edge')


while True:
    urllib.urlretrieve("http://192.168.5.1:8080/shot.jpg", 'cam.jpg')
    img = cv2.imread('cam.jpg')
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    edges = cv2.Canny(gray, 80, 120, apertureSize=3)

    lines = cv2.HoughLinesP(edges, 1, math.pi/2, 2, None, 30, 1)
    for line in lines[0]:
            pt1 = (line[0],line[1])
            pt2 = (line[2],line[3])
            cv2.line(img, pt1, pt2, (0,0,255), 3)

    cv2.imwrite("road2.jpg", img)
    cv2.imshow('edge', img)
    ch = cv2.waitKey(5)
    if ch == 27:
            break

Upvotes: 3

Views: 2341

Answers (1)

Martin Maillard
Martin Maillard

Reputation: 2811

Apparently cv2.HoughLinesP returns None when there are no lines.

On line 16, you try to access lines[0], which actually calls lines.__getitem__. As lines is of type NoneType, it doesn't have a __getitem__ method.

To solve the problem, you can for example check that lines is not None before accessing its items:

if lines:
    for line in lines[0]
        [...]

(note that it will also check that lines is not an empty list)

Upvotes: 4

Related Questions