niro
niro

Reputation: 1

How to detect these circles?

I want to detect the circles containing numbers. I tried circle detection(Hough method) but got very bad results. So I tried template matching and got a much better result. but still, there are a lot of circles missed. this my code

import cv2 
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image 
from numpy import asarray

img = cv2.imread(r'D:\RealPython\facedetectionOpenCV\dataset\dataset_qxgtuu.png')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
template = cv2.imread(r'D:\RealPython\facedetectionOpenCV\tam.PNG',0)
w, h = template.shape[::-1]

numpydata = asarray(template)
mean= np.mean(numpydata, axis=(0,1))

res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.6
loc = np.where( res >= threshold)

for pt in zip(*loc[::-1]):      
    cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (255,0,0), 2)

cv2.imshow("Detected Circle", img) 
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('res.png',img)

Here is what I get: https://ibb.co/Rcg2gPk

Upvotes: 0

Views: 449

Answers (2)

Dr Yuan Shenghai
Dr Yuan Shenghai

Reputation: 1915

Template matching is uaually worst case to go for finding objects. It can serve for some raw cost value but not the whole solution

If the circle always have the same intensity. You can use 2 threshold function to only look for this color with a canny to look for the edge.

Then there might be other noises, so use contour function to measure the gradient of the 2 threshold image so that only the circle with the correct contour distance is the correct match.

The other way would be direct contour shape matching as described here OpenCV shape matching between two similar shapes and https://www.youtube.com/watch?v=jvHT2eER7lU&ab_channel=JackyLe

enter image description here

Edit

To obtain the feature. you can try the method here

https://docs.opencv.org/master/d7/d4d/tutorial_py_thresholding.html

Combine multiple Simple Thresholding to find the circle feature.

After you get the 2 way thresholded feature You show be able to get multiple circle pattern and some other pattern with a similar color. Use the contour method to find the contour

After you obtained contour binary features.

You can try this method listed here with code

https://docs.opencv.org/master/d5/d45/tutorial_py_contours_more_functions.html

To find the matched circle shape. and rule out the false positive.

Upvotes: 1

Gem Taylor
Gem Taylor

Reputation: 5613

I suggest rethinking the problem. what if you tried to detect a grey rectangular outline of exactly WxH pixels? The H is just bigger than the digits. The width is the largest you can define in the circle?

Ignore that they are circles, but that there is a fixed size grey rectangle round the number.

Upvotes: 0

Related Questions