How can I make convexHull work for smaller intervals?

221 views Asked by At

I'm trying to find an edge defect. I'm using the pre-made function convexHull, but it skips past the defect I'm searching for. Like this:

enter image description here

I want the convexHull function to act in smaller intervals so that it doesn't skip past possible defects on the contours. Like this:

enter image description here

Simplified, this is what my code looks like:

import cv2

image = cv2.imread("path to where you store the picture")
image2 = image.copy()

imgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 
ret, thresh = cv2.threshold(imgray, 70, 255, 0) 
im2, contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)


# This is where the problem begins - after the outermost contour of the picture is found:

cnt = contours[0]
hull = cv2.convexHull(cnt, returnPoints=False)
defects = cv2.convexityDefects(cnt, hull)
for x in range(defects.shape[0]):
    s, e, f, d = defects[x, 0]
    if 900 <= d:
        far = tuple(cnt[f][0])
        cv2.circle(image2, far, 40, [0, 0, 255], 5)
        start = tuple(cnt[s][0])
        end = tuple(cnt[e][0])
        cv2.line(image2, start, end, [0, 255, 0], 2)
    else:
        continue

My main problem is that if the geometry of the part I'm checking is convex (as with the pictures above) my code marks an incorrect error and also skips past contours where there might be edge defects.

My end game goal is to detect every possible edge defects. If you know a smarter solution than the convexHull method, feel free to tell me! :)

This is the original image

enter image description here

0

There are 0 answers