I am currently learning Python and OpenCV, and I'm attempting to locate the center of each shape in an image using contours. However, when I implement the code, I'm obtaining multiple cx and cy values for each shape. Ideally, I want only one set of cx and cy coordinates for each closed shape in the image. I suspect that the contours algorithm is also considering the lines in the image, which I want to exclude. To address this, I've attempted to filter out these lines by focusing on the white color, but I'm uncertain if this is the correct approach. Below is the code snippet I'm working with:
import osimport cv2 as cvimport numpy as npfrom IPython.display import Image as IPImage, displaydef extract_color_code(image, x, y): color = image[y, x] r, g, b = color return '#{:02x}{:02x}{:02x}'.format(b, g, r)def generate_X_Y(image_path): image = cv.imread(image_path) gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY) ret, thresh = cv.threshold(gray, 128, 255, cv.THRESH_BINARY_INV) cv.imwrite("image2.jpg", thresh) contours, hierarchies = cv.findContours(thresh, cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE) hierarchies = hierarchies[0] blank = np.zeros(thresh.shape[:2], dtype='uint8') for i, (contour, hierarchy) in enumerate(zip(contours, hierarchies)): if hierarchy[2] == -1 and hierarchy[3] != -1: # Check if it is not an inner part of a contour M = cv.moments(contour) if M['m00'] != 0: cx = int(M['m10'] / M['m00']) cy = int(M['m01'] / M['m00']) color = extract_color_code(image, cx, cy) #if str(color) == '#ffffff': cv.drawContours(image, [contour], -1, (0, 255, 0), 2) cv.circle(image, (cx, cy), 3, (0, 0, 255), -1) #cv.putText(image, "center", (cx - 20, cy - 20), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2) cv.imwrite("image.png", image) display(IPImage("image.png")) # Display the image in Colabif __name__ == '__main__': image_path = '/content/pic_24.png' # Provide the correct path in Colab generate_X_Y(image_path)
After updating the code now 90% accurate. And the cx and cy are not in the center of the many contours you can check from the below image. Also can check the blue box there is an extra points.
colab link gcolab find cx and cy each