Uncategorized

python opencv circle detection – Stack Overflow


I have an image with two unfilled circles, the code fills them and I want the code to also show me the coordinates of each circles center. I’ve tried doing this, but my code doesn’t seem to work. Any help on this?

import cv2
import numpy as np

im_in = cv2.imread("circle.jpg", cv2.IMREAD_GRAYSCALE)

th, im_th = cv2.threshold(im_in, 127, 255, cv2.THRESH_BINARY)

im_floodfill = im_th.copy()


h, w = im_th.shape[:2]
mask = np.zeros((h+2, w+2), np.uint8)

cv2.floodFill(im_floodfill, mask, (0, 0), 255)

im_floodfill_inv = cv2.bitwise_not(im_floodfill)

im_out = im_th | im_floodfill_inv

contours, _ = cv2.findContours(im_out, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

for contour in contours:
    M = cv2.moments(contour)
    if M["m00"] != 0:
        cX = int(M["m10"] / M["m00"])
        cY = int(M["m01"] / M["m00"])

        cv2.drawContours(im_out, [contour], 0, 255, -1)

        cv2.putText(im_out, f'({cX}, {cY})', (cX - 30, cY - 10),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, 255, 2, cv2.LINE_AA)

cv2.imwrite("circles_filled_with_coordinates.png", im_out)

circle



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *