Reputation: 33
I am doing edge detection using HoughLinesP opencv function. I wanted to get an estimation of good values for the parameters of this function using trackbars. I have the following code:
def compute_edgelets(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
global edges
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
init_thresh = 50
max_thresh = 1000
init_min_line = 10
max_min_line = 1000
init_max_line = 1
max_max_line = 100
cv2.namedWindow("Result")
cv2.createTrackbar("threshold", "Result", init_thresh, max_thresh, on_change)
cv2.createTrackbar("min", "Result", init_min_line, max_min_line, on_change)
cv2.createTrackbar("max", "Result", init_max_line, max_max_line, on_change)
while True:
cv2.imshow("Result", image)
key = cv2.waitKey(1)
if key == ord('q'):
break
cv2.destroyAllWindows()
on_change function:
def on_change(x):
threshold = cv2.getTrackbarPos("threshold", "Result")
min_line_length = cv2.getTrackbarPos("min", "Result")
max_line_gap = cv2.getTrackbarPos("max", "Result")
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold, min_line_length, max_line_gap)
for x in range(0, len(lines)):
for x1, y1, x2, y2 in lines[x]:
cv2.line(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
However, this code does not work as intented - the arguments do not seem to work correctly and after changing the values on a trackbar for a little bit I get the following TypeError:
TypeError: object of type 'NoneType' has no len()
Is there something I am doing wrong with the trackbars?
Upvotes: 2
Views: 249
Reputation: 19041
It's impossible to tell you the exact reason why this is happening (as you didn't provide all the relevant data to reproduce this exact issue), but fortunately the root issue is easy to pinpoint.
The error refers to a call to len
and the only place this is used in the sample code is getting the length of the result of cv2.HoughLinesP
. The issue is that you're trying to take a length of None
, which doesn't make sense.
In Python, when you call cv2.HoughLinesP
with a set of parameters that prohibit it from finding any lines, it will return None
instead of a sequence of line parameters you can iterate over. We can easily demonstrate a few of such situations:
Process empty image:
import numpy as np
import cv2
print cv2.HoughLinesP(None, 1, np.pi/180, 50, 10, 1)
Outputs None
Process an all-black image:
import numpy as np
import cv2
print cv2.HoughLinesP(np.zeros((100,100,1), np.uint8), 1, np.pi/180, 50, 10, 1)
Outputs None
In your example code, you do not handle such scenario, and you directly try to get the length of the result. Since you can't apply len
on None
, you get an error. Hence, you need to do some adjustments to your code ... at the least something like
if lines is None:
return
Upvotes: 2