Loanb222 Loanb222 - 1 year ago 151
Python Question

OpenCV Hough Circle Transform Not Working

I have followed OpenCV's tutorial here for circle detection on my Raspberry Pi. This is the code that I am using which is the same as the tutorial except a different image.

import cv2
import numpy as np

img = cv2.imread('watch.jpg',0)
img = cv2.medianBlur(img,5)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)

circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,20,
circles = np.uint16(np.around(circles))
for i in circles[0,:]:,(i[0],i[1]),i[2],(0,255,0),2),(i[0],i[1]),2,(0,0,255),3)


Then when I ran the script this is what I was presented with this
enter image description here

and this is the original image

enter image description here

What is causing this to happen?

Thank You in Advance!


enter image description here

Answer Source

The large amount of circles generated by Hough Circle Transform is caused by the low value of the threshold for center detection, which is param2 in cv2.HoughCircles in your case.

So try to increase the value of param2 to avoid false detections.

Also you can adjust minRadius and maxRadius values for better results.


I have just tried example from here and changed only param2 to 10, minRadius to 30 and maxRadius to 50. The result is good enough:

enter image description here

The example from the link above is written with C++, but you can compare parameters and the sequence of functions invocations to refine your own algorithm.