你可以使用绘制lines和arcs的函数来实现你想要的。
您要绘制的框架由 4 个相似的部分(每个角一个)组成,每个部分都旋转(或镜像)。
让我们看看左上角:
如您所见,我们需要绘制 2 条线段(长度为 d)和圆弧(半径为四分之一圆 r)。
假设左上角的坐标是(x1, y1)。
这意味着圆弧的中心点在(x1 + r, y1 + r)。
其中一行将从(x1 + r, y1) 变为(x1 + r + d, y1)。
另一行将从(x1, y1 + r) 转到(x1, y1 + r + d)。
其他角落也会发生类似的情况。
示例代码:
import cv2
import numpy as np
# ============================================================================
def draw_border(img, pt1, pt2, color, thickness, r, d):
x1,y1 = pt1
x2,y2 = pt2
# Top left
cv2.line(img, (x1 + r, y1), (x1 + r + d, y1), color, thickness)
cv2.line(img, (x1, y1 + r), (x1, y1 + r + d), color, thickness)
cv2.ellipse(img, (x1 + r, y1 + r), (r, r), 180, 0, 90, color, thickness)
# Top right
cv2.line(img, (x2 - r, y1), (x2 - r - d, y1), color, thickness)
cv2.line(img, (x2, y1 + r), (x2, y1 + r + d), color, thickness)
cv2.ellipse(img, (x2 - r, y1 + r), (r, r), 270, 0, 90, color, thickness)
# Bottom left
cv2.line(img, (x1 + r, y2), (x1 + r + d, y2), color, thickness)
cv2.line(img, (x1, y2 - r), (x1, y2 - r - d), color, thickness)
cv2.ellipse(img, (x1 + r, y2 - r), (r, r), 90, 0, 90, color, thickness)
# Bottom right
cv2.line(img, (x2 - r, y2), (x2 - r - d, y2), color, thickness)
cv2.line(img, (x2, y2 - r), (x2, y2 - r - d), color, thickness)
cv2.ellipse(img, (x2 - r, y2 - r), (r, r), 0, 0, 90, color, thickness)
# ============================================================================
img = np.zeros((256,256,3), dtype=np.uint8)
draw_border(img, (10,10), (100, 100), (127,255,255), 1, 10, 20)
draw_border(img, (128,128), (240, 160), (255,255,127), 1, 5, 5)
cv2.imwrite('round_rect.png', img)
结果: