python - 在脸周围画出花哨的矩形

标签 python opencv image-processing dlib

我正在使用以下代码检测人脸并在人脸上方绘制矩形。

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

矩形看起来像这样:

但是我试图得到一个类似这样的矩形:

是否有任何 OpenCV 或 dlib 函数可以帮助我获得这种有效的矩形?

最佳答案

你可以通过绘制lines的函数来实现你想要的。和 arcs .

您要绘制的框架由 4 个相似的部分(每个角一个)组成,每个部分都旋转(或镜像)。

让我们看一下左上角:

Illustration

如您所见,我们需要绘制 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)

结果:

Result

关于python - 在脸周围画出花哨的矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46036477/

相关文章:

python - 如何判断图像是否暗?

c# - 如何正确调整/重新压缩图像

python - 如何安装 python .egg 文件

python比较两个列表,将每个失败视为独立失败而不是单一失败

image - 打印 YUV 图像的像素值

python - 使用 Python openCV PIL 将黑色更改为白色但不将白色更改为黑色

python - pandas ffill 的设置值

python - 如何在 sqlalchemy 中使用 psycopg2.extras?

visual-c++ - 如何使用OpenCV将Bayer转换为RGB,反之亦然

python - 平滑像素化二值图像python代码的边缘