1+ import cv2
2+ import numpy as np
3+ import matplotlib .pyplot as plt
4+ import sys
5+
6+ # load the image
7+ img = cv2 .imread (sys .argv [1 ])
8+ # convert BGR to RGB to be suitable for showing using matplotlib library
9+ img = cv2 .cvtColor (img , cv2 .COLOR_BGR2RGB )
10+ # make a copy of the original image
11+ cimg = img .copy ()
12+ # convert image to grayscale
13+ img = cv2 .cvtColor (img , cv2 .COLOR_BGR2GRAY )
14+ # apply a blur using the median filter
15+ img = cv2 .medianBlur (img , 5 )
16+ # finds the circles in the grayscale image using the Hough transform
17+ circles = cv2 .HoughCircles (image = img , method = cv2 .HOUGH_GRADIENT , dp = 0.9 ,
18+ minDist = 80 , param1 = 110 , param2 = 39 , maxRadius = 70 )
19+
20+ for co , i in enumerate (circles [0 , :], start = 1 ):
21+ # draw the outer circle in green
22+ cv2 .circle (cimg ,(i [0 ],i [1 ]),i [2 ],(0 ,255 ,0 ),2 )
23+ # draw the center of the circle in red
24+ cv2 .circle (cimg ,(i [0 ],i [1 ]),2 ,(0 ,0 ,255 ),3 )
25+
26+ # print the number of circles detected
27+ print ("Number of circles detected:" , co )
28+ # save the image, convert to BGR to save with proper colors
29+ # cv2.imwrite("coins_circles_detected.png", cimg)
30+ # show the image
31+ plt .imshow (cimg )
32+ plt .show ()
0 commit comments