How to measure coin widths using Python?

Viewed 194

I followed the tutorial shown at OpenCV site.. How could I use the same example and extend it to detect coin widths ?

enter image description here

I know how I could use HoughCircles() and FindContour() python functions but this approach is more stable in noisy backgrounds. I would like to extract the segmented coins and use circle/contour detection for width estimation. But I don't understand how I could extend this code.

import numpy as np
import cv2
from matplotlib import pyplot as plt

# https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_watershed/py_watershed.html

img_file_name = r'C:\Users\coins.jpg'

img = cv2.imread(img_file_name)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray,100,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
#cv2.imshow("thresolded",thresh)
# noise removal
kernel = np.ones((6,6),np.uint8)
opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 3)
# sure background area
sure_bg = cv2.dilate(opening,kernel,iterations=3)
#cv2.imshow("dilate",sure_bg)
# Finding sure foreground area
dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,5)
ret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0)
cv2.imshow("dist_transform",sure_fg)
# Finding unknown region
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg,sure_fg)
cv2.imshow("subtract",unknown)
# Marker labelling
ret, markers = cv2.connectedComponents(sure_fg)
# Add one to all labels so that sure background is not 0, but 1
markers = markers+1
# Now, mark the region of unknown with zero
markers[unknown==255] = 0
#markers = cv2.watershed(img,markers)
markers = cv2.watershed(img,markers)
img[markers == -1] = [0,255,0]
cv2.imshow("markers",img)
1 Answers

Here as I slightly changed your code:

import numpy as np
import cv2
import imutils
from matplotlib import pyplot as plt

img_file_name = 'coins.jpg'

img = cv2.imread(img_file_name)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray,100,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)

# noise removal
kernel = np.ones((6,6),np.uint8)
opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 3)

# sure background area
sure_bg = cv2.dilate(opening,kernel,iterations=3)

# CHANGE
dist_transform = cv2.distanceTransform(thresh,cv2.DIST_L2,5)

ret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0)

# Finding unknown region
sure_fg = np.uint8(sure_fg)

# CHANGE
unknown = cv2.subtract(thresh,sure_fg)

# Marker labelling
ret, markers = cv2.connectedComponents(sure_fg)

# Add one to all labels so that sure background is not 0, but 1
markers = markers+1

# Now, mark the region of unknown with zero
markers[unknown==255] = 0

markers = cv2.watershed(img,markers)

Here the code that you can use:

# loop over the unique markers returned by the Watershed
# algorithm
num_coins = np.amax(markers) -1    
coins_width = np.zeros(num_coins)
      
for marker in np.unique(markers):
    # if the marker is -1, we are examining the borders
    # if the marker is 1, we are examining the 'background'
    # so simply ignore them
    if marker <= 1:
        continue    
        
    # otherwise, allocate memory for the marker region and draw
    # it on the mask
    mask = np.zeros(gray.shape, dtype="uint8")
    mask[markers == marker] = 255
    
    # detect contours in the mask and grab the largest one
    cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)
    largest_cnt = max(cnts, key=cv2.contourArea)
    
    #
    # First Way
    #
    
    # calculate the center of the contour
    M = cv2.moments(largest_cnt )
    x = int(M["m10"] / M["m00"])
    y = int(M["m01"] / M["m00"])
    
    # calculate the radius of the contour from area (I suppose it's a circle)
    area = cv2.contourArea(largest_cnt)
    radius = np.sqrt(area/3.14)
    
    #
    # Second Way
    #
    
    # draw a circle enclosing the object
    # ((x, y), radius) = cv2.minEnclosingCircle(largest_cnt) 
    
    cv2.circle(img, (int(x), int(y)), int(radius), (0, 255, 0), 1)
    cv2.putText(img, "#{}".format(marker-2), (int(x) - 10, int(y)), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 1)

    coins_width[marker-2] = 2* radius

print(coins_width)

cv2.imshow("markers",img)

The code is a modified version of the code in the article: https://www.pyimagesearch.com/2015/11/02/watershed-opencv/

Related