Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect dots coordinates - opencv findContours()

I want to detect dot (x, y) coordinates for an image with dimensions: (3000, 2000, 3). An example of such an image looks like:

input image

To process the image, I use the following code:

img = cv2.imread(path_dots_data + "01000.exr", cv2.IMREAD_ANYCOLOR |cv2.IMREAD_ANYDEPTH | cv2.IMREAD_UNCHANGED)
img = img - dark_img
img = img / img.max()
img = np.clip(a = img, a_min = 0.0, a_max = 1.0)

# Multiply by 255 before converting to uint 8 dtype-
img = img * 255.0
        
# Convert to uint8 dtype for opencv2 algos to work-
img = img.astype('uint8')

# Apply blurring to suppress high-frequency signals-
blur = cv2.medianBlur(img, 5)

# Convert from color to gray-scale-
gray = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY)

# Apply thresholding to detect white dots on black background-
thresh = cv2.threshold(gray * 5, 200, 255, cv2.THRESH_BINARY)[1]

# Apply findCountours()-
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

len(cnts)
# 41

# Add circles around detected contours-
min_area = 0.1
white_dots = []
for c in cnts:
   area = cv2.contourArea(c)
   if area > min_area:
      cv2.drawContours(img, [c], -1, (36, 255, 12), 2)
      white_dots.append(c)


# The final output looks like:
plt.figure(figsize = (12, 10))
plt.imshow(img, cmap = 'gray')
plt.show()

final image output

My question is: how can I find the (x, y) coordinates for the center of the detected contours/circles (green lines) in the second output image?

like image 644
Arun Avatar asked Mar 06 '26 18:03

Arun


1 Answers

It looks like the centroid of each contour might match the bright spot inside. See if this works:

for c in cnts:
    M = cv2.moments(c)
    cx = int(M['m10']/M['m00'])
    cy = int(M['m01']/M['m00'])
    cv2.circle(img, (cy, cx), 5, (0, 0, 255))
    

This should draw a red circle around each of the points cy,cx which should match the bright spoits

like image 61
Yakov Dan Avatar answered Mar 09 '26 11:03

Yakov Dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!