So I have been trying to get the defects of a contour and its hull. After looking into a few tutorials I have come across similar code, but no matter how I implement it, the line cv2.convexityDefects
seems to kick me out of the loop, not displaying the video. The program works without the defects part and I'm not getting any errors with the defects part in but it just seems to end the code.
contours, H = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=cv2.contourArea, reverse=True)
max_area = 0
for i in range(len(contours)): # finding largest contour by area [3]
contour = contours[i]
area = cv2.contourArea(contour)
if area > max_area:
max_area = area
ci = i
if len(contours) > 0:
(x, y, w, h) = cv2.boundingRect(contours[ci])
# cv2.rectangle(resized, (x, y), (x + w, y + h), (0, 255, 0), 2)
moments = cv2.moments(contours[ci])
if moments['m00'] != 0: # this gives the centre of the moments [3]
cx = int(moments['m10'] / moments['m00']) # cx = M10/M00
cy = int(moments['m01'] / moments['m00']) # cy = M01/M00
center = (cx, cy)
cv2.circle(resized, center, 5, [0, 0, 255], 2) # draws small circle at the center moment
hull = cv2.convexHull(contours[ci])
defects = cv2.convexityDefects(contours[ci], hull)
if len(defects) > 0:
for i in range(defects.shape[0]):
s, e, f, d = defects[i, 0]
start = tuple(contours[ci][s][0])
end = tuple(contours[ci][e][0])
far = tuple(contours[ci][f][0])
cv2.line(resized, start, end, [0, 255, 0], 2)
cv2.circle(resized, far, 5, [0, 0, 255], -1)
else:
cv2.drawContours(resized, [contours[ci]], 0, (0, 255, 0), 2)
cv2.drawContours(resized, [hull], 0, (0, 0, 255), 2)
If anyone has come across a similar issue or knows where I am going wrong it would be a big help.