简体   繁体   中英

Python + OpenCV = How to crop circle?

The below is the code:

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

From the code how to crop the circle from the given example ?

Its simple .. you need to get x,y co-ordinates of top right of rectangle and find with and height. Circles can be only enclosed in squares.

# 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)]

After 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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