OpenCV围绕Hough Circle指向Python

时间:2016-06-09 12:19:34

标签: python opencv crop

我正在使用OpenCV和Python在图像中找到一个圆圈。我能够使用OpenCV教程中的Hough Circle变换代码找到圆圈。我想围绕圆心的中心点裁剪一个矩形。我无法正确获得裁剪功能,并尝试了多种裁剪组合,并获得错误或图像的错误部分。有人可以澄清我应该如何输入裁剪坐标?这是我不断得到的错误:

  

错误:( - 1515)size.width> 0&&函数cv :: imshow

中的size.height> 0

谢谢!

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

circles = cv2.HoughCircles(img,cv.CV_HOUGH_GRADIENT,1,20)

circles = np.uint16(np.around(circles))


for i in circles[0,:]:
    #draw outer circle
    cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
    #draw center of circle
    cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)

    #crop ROI around circle...? 
    crop_cimg = cimg[i[0]:500,i[1]:700] #crop from x, y, w, h 


cv2.imshow('detected circles',crop_cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()

2 个答案:

答案 0 :(得分:1)

确保您处于原始图像的有效范围内。以下代码未经测试但您应该能够解决可能的错误。

还要注意坐标与行/列索引(这些是相互交换的)。对于大多数opencv方法,坐标是合适的,但裁剪实际上是nuympy上的切片操作,因此使用行/列索引。

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

circles = cv2.HoughCircles(img,cv.CV_HOUGH_GRADIENT,1,20)

circles = np.uint16(np.around(circles))

cropSize = (500, 700) # <- added: what size do you want to extract

for i in circles[0,:]:
    #draw outer circle
    cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
    #draw center of circle
    cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)

    #crop ROI around circle...?
    # make sure the bounds won't under-/overflow
    cropCoords = (max(0, i[1]-cropSize[0]//2),min(img.shape[0], i[1]+cropSize[0]//2),
                  max(0, i[0]-cropSize[1]//2),min(img.shape[1], i[0]+cropSize[1]//2)) 
    crop_cimg = cimg[cropCoords[0]:cropCoords[1],
                     cropCoords[2]:cropCoords[3]] 


cv2.imshow('detected circles',crop_cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()

答案 1 :(得分:0)

只要错误可能来自crom_cimg参数,您是否检查了以下内容:

  • 图片是否足够大,以便达到(x,y)=(499,699)像素?

  • i[0]应大于0且小于500

  • i[1]应大于0且小于700