[英]How to automatically detect Circles in python
I've been trying to count coins in an images with different backgrounds(not necessarily solid). 我一直在尝试计算具有不同背景(不一定是实心)的图像中的硬币。 this is a code I found here in an answer but the problem is I don't want to have to change parameters every image.
这是我在答案中找到的代码,但是问题是我不想更改每个图像的参数。 Is there a way to do this?
有没有办法做到这一点?
def CountCoins_V2(img):
image_ori = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
lower_bound = np.array([0,0,10])
upper_bound = np.array([255,255,195])
image = img
mask = cv2.inRange(img, lower_bound, upper_bound)
#mask = cv2.adaptiveThreshold(image_ori,255,cv2.ADAPTIVE_THRESH_MEAN_C,\cv2.THRESH_BINARY_INV,33,2)
kernel = np.ones((3, 3), np.uint8)
mask = cv2.erode(mask, kernel, iterations=6)
mask = cv2.dilate(mask, kernel, iterations=3)
closing = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
contours = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[1]
contours.sort(key=lambda x:cv2.boundingRect(x)[0])
array = []
ii = 1
for c in contours:
(x,y),r = cv2.minEnclosingCircle(c)
center = (int(x),int(y))
r = int(r)
if r >= 6 and r<=10:
cv2.circle(image,center,r,(0,255,0),2)
array.append(center)
show_images([image_ori,mask])
return len(contours)
There are 2 parameters in the code: 代码中有2个参数:
lower_bound = np.array([0,0,10])
and upper_bound = np.array([255,255,195])
which threshold the image to get only the colors in the range between lower_bound
and upper_bound
. lower_bound = np.array([0,0,10])
和upper_bound = np.array([255,255,195])
,它们对图像进行阈值处理以仅获得在lower_bound
和upper_bound
之间的范围内的颜色。 But in this code, the range is too broad [0,0,10]
to [255,255,195]
, so it makes no sense. [0,0,10]
到[255,255,195]
太宽,因此没有任何意义。 You should limit this range closer to the color of the circles you want to detect. r
in (x,y),r = cv2.minEnclosingCircle(c)
, which is the radius of the circle found in the image. r
在(x,y),r = cv2.minEnclosingCircle(c)
,其是在图像中找到的圆的半径。 It is an important parameter and you need to do experiments to find the best range for all images.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.