使用Python和OpenCV如何裁剪圆形?

4
以下是代码:
self.img = cv2.imread(image,)
circle = cv2.HoughCircles(self.img, 3,
                          dp=1.5, minDist=1000, minRadius=100, maxRadius=1000)
red = (0,0,255)
x = circle[0][0][0]
y = circle[0][0][1]
r = circle[0][0][2]
cv2.circle(self.img, (x, y), r, red, 2)



    x - X
    y - Y
    r - Radius
    For example: 521.25, 506.25, 318.919

从这段代码中如何裁剪给定示例中的圆形?

你使用的OpenCV版本是什么? - galath
OpenCV版本:3.0.0 - Stanislav Filin
如果您的图像是一个矩形网格,那么您可以使用类似于 cropped = image[30:120 , 240:335] 的代码行进行裁剪,其中数字是NumPy数组切片,定义了图像的矩形区域,从(240, 30)开始,到(335, 120)结束。如果您想要一个特定于您问题的答案,请根据 [ask] 重新编写它。 - boardrider
如果您提供一些图片,这个问题会更有用。 - Cătălina Sîrbu
2个回答

3

很简单,您需要获取矩形右上角的x、y坐标,并找到宽度和高度。圆只能被包含在正方形中。

# given x,y are circle center and r is radius
rectX = (x - r) 
rectY = (y - r)
crop_img = self.img[y:(y+2*r), x:(x+2*r)]

2
根据我的测试,您必须在最后的公式中使用rectX和rectY,而不是x和y。 - Maham
正如 @Maham 所提到的,最终公式中应使用 rectXrectY,否则它将无法工作。 - Ryan

2

在执行circles=cv2.HoughCircles(img,...)之后

if len(circles) == 1:
    x, y, r = circles[0][0]
    print x, y, r
    mask = np.zeros((w0,h0),dtype=np.uint8)
    cv2.circle(mask,(x,y),r,(255,255,255),-1,8,0)
    #cv2.imwrite(argv[2],mask)
    out = img*mask
    white = 255-mask
    cv2.imwrite(argv[2],out+white)

你从哪里得到了w0和h0? - Freddy Daniel
w0和h0是图像(和掩膜)的宽度和高度,w0 = img.shape[0]; h0 = img.shape[1]; - Alexander Lubyagin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接