你好, 我正在尝试通过将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()
我的问题如下:
我没有得到单独的转盘,但是在每个图像中“ crop0.jpg”有1个,但是“ crop1.jpg”有2个,“ crop3.jpg”有4个。然后,我可以运行批处理模板匹配算法。
总结果为5,您可能需要注意。
答案 0 :(得分:1)
在我看来,您在这里加班。在此行
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
)或得到零结果(中心和半径为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
...