在脸部周围绘制奇特的矩形 [英] Drawing fancy rectangle around face
问题描述
我正在使用以下代码检测面部并在面部上方绘制矩形.
I am using the following code to detect face and draw rectangle on top of the face.
while True:
# get video frame
ret, img = cap.read()
input_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img_h, img_w, _ = np.shape(input_img)
detected = detector(input_img, 1)
for i, d in enumerate(detected):
x1, y1, x2, y2, w, h = d.left(), d.top(), d.right() + 1, d.bottom() + 1, d.width(), d.height()
cv2.rectangle(img, (x1, y1), (x2, y2), (255, 0, 0), 2)
cv2.imshow("result", img)
key = cv2.waitKey(30)
if key == 27:
break
矩形看起来像这样:
但是我正试图得到一个与此类似的矩形:
However Im trying to get a rectangle similar to this:
有没有可以帮助我获得这种有效矩形的OpenCV或dlib函数?
Is there any OpenCV or dlib function that can help me get this sort of effective rectangle?
推荐答案
使用绘制弧.
要绘制的框架包括4个相似的部分(每个角一个),每个部分都旋转(或镜像).
The frame you want to draw consists of 4 similar parts (one per corner), each rotated (or mirrored).
让我们看一下左上角:
如您所见,我们需要绘制2个线段(长度为d
)和一条弧线(半径为r
的四分之一圆).
As you can see, we need to draw 2 line segments (of length d
) and an arc (a quarter of a circle of radius r
).
比方说,左上角的坐标是(x1, y1)
.
Let's say the coordinates of the top-left corner are (x1, y1)
.
这意味着弧将在位置(x1 + r, y1 + r)
处具有中心.
That means that the arc will have a center at position (x1 + r, y1 + r)
.
其中一行将从(x1 + r, y1)
到(x1 + r + d, y1)
.
另一行将从(x1, y1 + r)
到(x1, y1 + r + d)
.
其他情况也会发生类似的情况.
Similar situation will happen with the other corners.
示例代码:
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)
结果:
这篇关于在脸部周围绘制奇特的矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!