簡體   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