Home > front end >  To cut a piece from a circle, I have to do the math manually first. Is there a smarter way to do the
To cut a piece from a circle, I have to do the math manually first. Is there a smarter way to do the

Time:01-18

I'm trying to cut a piece from a circle using Python along with opencv, here is the code

firstly, I constructed the circle

layer1 = np.zeros((48, 48, 4))
cv2.circle(layer1, (24, 24), 23, (0, 0, 0, 255), -1)
res = layer1[:]

and I got

enter image description here

and then, I drew a smaller square on it

start_point = (24, 0); end_point = (48, 24); color = (255, 0, 0)
cv2.rectangle(res, start_point, end_point, color, -1)

which gives

enter image description here

similarly, I drew a triangle on the circle

pt1 = (24, 0); pt2 = (48, 0); pt3 = (24, 24)
triangle_cnt = np.array( [pt1, pt2, pt3] )
cv2.drawContours(res, [triangle_cnt], 0, (255,0,0), -1)

which gives

enter image description here

I can go along this way to draw a smaller triangle, 1/16, 1/32 and so on.

I have to do the math manually to get the vertices.

Is there a smarter (more elegant) way to do the job?

CodePudding user response:

import cv2
import numpy as np

# Colors (B, G, R)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)


# Create new blank 300x150 white image
width, height = 800, 500
img = np.zeros((height, width, 3), np.uint8)
img[...] = BLACK


center = (width//2, height//2)
axes = (200, 200) # axes radius, keep equal to draw circle.
angle = 0 #clockwise first axis 
startAngle = 0
endAngle = 90
color = WHITE

img = cv2.ellipse(img, center, axes, angle, startAngle, endAngle, color, thickness=-1)

cv2.imshow('image', img)
cv2.waitKey(-1)

You can play with startAngle and endAngle to change the position of the white part.

Another option is to change the angle option (to -90 for example to rotate counter clockwise).

EDIT to show the different end angles add

img = cv2.ellipse(img, center, axes, angle, startAngle, endAngle/2, (255, 0, 0), thickness=-1)
img = cv2.ellipse(img, center, axes, angle, startAngle, endAngle/4, (0, 255, 0), thickness=-1)
img = cv2.ellipse(img, center, axes, angle, startAngle, endAngle/8, (0, 0, 255), thickness=-1)
  •  Tags:  
  • Related