Home > other >  How to cut out part of an image based on coordinates of a given circle
How to cut out part of an image based on coordinates of a given circle

Time:12-04

I'm trying to cut out part of an image based on some circles coordinates, my initial attempts have been to try doing this

startx = circle[0]
starty = circle[1]
radius = circle[2]
recImage = cv2.rectangle(image,(startx-radius,starty-radius), (startx radius,starty radius), (0,0,255),2)
miniImage = recImage[startx-radius:startx radius,starty-radius:starty radius]

circle[0] and circle[1] being the x and y coords of the circle centre and circle[2] being the radius. The recImage should draw the rectangle and then the miniImage should be a smaller image of that rectangle. However they don't line up. the image of squares to cut out one of the actual cut outs

I was expecting them to line up as their starting and ending values are identical but they don't. Thanks

CodePudding user response:

There is a mistake in your code. You are using the coordinates of the center of the circle to draw the rectangle and cut out the mini image. However, the coordinates of the top left corner of the rectangle should be used to draw the rectangle and cut out the mini image.

Here is the updated code:

startx = circle[0]
starty = circle[1]
radius = circle[2]

# Calculate the coordinates of the top left corner of the rectangle
x1 = startx - radius
y1 = starty - radius
x2 = startx   radius
y2 = starty   radius

# Draw the rectangle on the image
recImage = cv2.rectangle(image, (x1, y1), (x2, y2), (0, 0, 255), 2)

# Cut out the mini image from the rectangle
miniImage = recImage[y1:y2, x1:x2]

# Show the mini image
cv2.imshow('Mini Image', miniImage)
cv2.waitKey(0)
cv2.destroyAllWindows()
  • Related