繁体   English   中英

OpenCV Crop Hough Circles Python无法正常工作

[英]OpenCV Crop Hough Circles Python not working

请参考以下图片的图片 您好,我正在尝试通过将OpenCV与Python一起构建模拟量表读取器。 我使用了Hough Circles来减少编码。 代码转载如下:

import cv2
import numpy as np

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

height,width = img.shape
mask = np.zeros((height,width), np.uint8)

counter = 0

circles = cv2.HoughCircles(img,cv2.cv.CV_HOUGH_GRADIENT,1,20,
                            param1=200,param2=100,minRadius=0,maxRadius=0)

circles = np.uint16(np.around(circles))
for i in circles[0,:]:
    # draw the outer circle
    cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)

    # draw the center of the circle
    cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)

    # Draw on mask
    cv2.circle(mask,(i[0],i[1]),i[2],(255,255,255),-1)
    masked_data = cv2.bitwise_and(cimg, cimg, mask=mask)    

    # Apply Threshold
    _,thresh = cv2.threshold(mask,1,255,cv2.THRESH_BINARY)

    # Find Contour
    cnt = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[0]

    #print len(contours)
    x,y,w,h = cv2.boundingRect(cnt[0])

    # Crop masked_data
    crop = masked_data[y:y+h,x:x+w]

    # Write Files
    cv2.imwrite("output/crop"+str(counter)+".jpg", crop)

    counter +=1

print counter

cv2.imshow('detected circles',cimg)
cv2.imwrite("output/circled_img.jpg", cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()

我的问题如下:

  1. 我没有单独的转盘,但是在每个图像中“ crop0.jpg”有1个,但“ crop1.jpg”有2个,“ crop3.jpg”有4个。我需要的是各个文件中的各个Circle,然后可以运行批处理模板匹配算法。

  2. 计数器的总结果为5,您可能需要注意。

在我看来,您在这里加班。 在这条线

circles = cv2.HoughCircles(img,cv2.cv.CV_HOUGH_GRADIENT,1,20, param1=200,param2=100,minRadius=0,maxRadius=0)

您实际上找到了所需的圈子,但由于某种原因,您尝试在随后的循环中再次找到它们。

您只需使用获得的坐标即可获取裁剪的图像。 由于每个圆都有一个中心和一个半径,因此可以得到一个包含圆的边界框,然后(可能)对其应用蒙版。
我猜类似的东西会起作用:

for c in circles[0, :]:
    c = c.astype(int)
    # get the actual cropped images here
    crop = img_copy[c[1]-c[2]:c[1]+c[2], c[0]-c[2]:c[0]+c[2]]
    # create a mask and add each circle in it
    mask = np.zeros(crop.shape)
    mask = cv2.circle(mask, (c[2], c[2]), c[2], (255, 255, 255), -1)
    final_im = mask * crop

只需在过滤之前添加以下内容即可获得图像的副本:

img = cv2.imread('/home/gorfanidis/misc/gauge2.jpg', 0)
img_copy = img.copy()  # <- add this to have a copy of your original image

编辑:

如果由于某种原因没有得到结果(返回类型为None )或None得到零结果(center和radius为0 ),则可以检查以下两种情况:

if circles is not None:  # checks that something actually was returned
    for c in circles[0, :]:
        c = c.astype(int)
        if not c[2]:  # just checks that radius is not zero to proceed
            continue
        ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM