Jack Guy
Jack Guy

Reputation: 8523

Python OpenCV HoughCircles not giving good results

I need to do quick and accurate circle detection so I figured that using OpenCV's Hough Circle would be a good choice. Unfortunately, no matter how good an image I give it and how much I adjust the parameters, it refuses to detect all of the circles in an image. Here's my input image: Original OpenCV image

I would like to detect each of those circles. First I'm running the image through a color filter to extract greys

frame = cv2.imread("new1.JPG")
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

lower_gray = np.array([0, 0, 0], dtype=np.uint8)
upper_gray = np.array([100,100,100], dtype=np.uint8)

mask = cv2.inRange(frame, lower_gray, upper_gray)
res = cv2.bitwise_and(frame,frame, mask= mask)

gray = cv2.cvtColor(res, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 1, 255, cv2.cv.CV_THRESH_BINARY)

That gives me the following threshold, which I figure is actually pretty darn good. Threshold image

Even with such a good threshold, the circle detection is mediocre at best.

circles = cv2.HoughCircles(thresh,cv2.cv.CV_HOUGH_GRADIENT,1,20,param1=50,param2=10,minRadius=2,maxRadius=15) 

Circles detected

Is there another technique I should be using? I've had pretty good results with contours, but it's slow.

Upvotes: 2

Views: 1459

Answers (1)

ljetibo
ljetibo

Reputation: 3094

You can try doing a cv2.dilate(img, kernel) to thicken the lines before you try to do houghCircles method.

Also a general approach to handling noise is to do a cv2.erode(img, kernel) to thin out the whites, which gets rid of small pixels in the image.

Further reading: http://docs.opencv.org/trunk/doc/py_tutorials/py_imgproc/py_morphological_ops/py_morphological_ops.html

Kernel is just a matrix like np.ones(), but you could try various different matrices until you get the most favorable result.

However don't ever expect computer vision to do a 100% good job, or to do it fast. If you hit high 80% you're doing well (of course depending on actual image quality, I'm not saying it's impossible to have a 100% on a image drawn in paint)....

Upvotes: 3

Related Questions