要从圆上切下一块,我必须先手动计算。使用 Python 和 opencv 是否有更聪明的方法来完成这项工作?

To cut a piece from a circle, I have to do the math manually first. Is there a smarter way to do the job using Python along with opencv?

我正在尝试使用 Python 和 opencv 从圆中切出一块,这是代码

首先,我构建了圆圈

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

我得到了

然后,我在上面画了一个小方块

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

这给出了

同样,我在圆上画了一个三角形

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)

这给出了

我可以沿着这个方向画一个更小的三角形,1/16,1/32等等。

我必须手动计算才能得到顶点。

有没有更聪明(更优雅)的方法来完成这项工作?

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)

你可以玩startAngleendAngle来改变白色部分的位置。

另一种选择是更改 angle 选项(例如逆时针旋转到 -90)。

编辑以显示不同的结束角度添加

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)