I try to find the minimum enclosing circles of shapes in an image. My function find_minEnclosingCircles processes an image to detect contours and then finds the minimum enclosing circle for each contour. I've noticed that to capture all relevant circles, I need to run this function twice: once on the original thresholded image and again on its bitwise not (cv2.bitwise_not) version. I'm seeking a more efficient solution. Here is the core of my current function:
def find_minEnclosingCircles(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (3, 3), 0) _, thresh_img = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) element = cv2.getStructuringElement(shape=cv2.MORPH_RECT, ksize=(5, 5)) cv2.morphologyEx(src=thresh_img, op=cv2.MORPH_CLOSE, kernel=element, dst=thresh_img) contours, _ = cv2.findContours(thresh_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) circles = [(int(x), int(y), int(radius)) for cnt in contours for (x, y), radius in [cv2.minEnclosingCircle(cnt)] if radius > 10] return circles img = cv2.imread(image_path) circles = find_minEnclosingCircles(img) + find_minEnclosingCircles(cv2.bitwise_not(img)) for circle in circles: cv2.circle(img, (circle[0],circle[1]), circle[2], (34, 25, 240), 2) cv2.imshow("img", img) cv2.waitKey() I tried using adaptiveThreshold, Canny but it didn't help. My question is: Is there a more efficient strategy or algorithmic approach that allows me to achieve the same result without having to process the image twice?
I attach an example image where is should find 3 circles:

Any suggestions for optimizing this process or alternative techniques would be greatly appreciated.
Источник: https://stackoverflow.com/questions/780 ... ise-not-wi
Мобильная версия