Python Dlib使用面部标记进行裁剪

2024-06-16 10:05:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用DLIB的地标裁剪图像。在

我已经编写了我的大部分程序,工作完美,但在过去的一周里,这部分一直有困难。我需要4个坐标。在

https://i.stack.imgur.com/05uIT.jpg

我需要在坐标34,37,46上的“参考系”矩形;然后,我需要在每个轴上加上+n的额外填充

任何帮助都将不胜感激!在

# USAGE
# python facial_landmarks.py --shape-predictor shape_predictor_68_face_landmarks.dat --image images/example_01.jpg 

# import the necessary packages
from imutils import face_utils
import numpy as np
import argparse
import imutils
import dlib
import cv2

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--shape-predictor", required=True,
    help="path to facial landmark predictor")
ap.add_argument("-i", "--image", required=True,
    help="path to input image")
args = vars(ap.parse_args())

# initialize dlib's face detector (HOG-based) and then create
# the facial landmark predictor
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(args["shape_predictor"])

# load the input image, resize it, and convert it to grayscale
image = cv2.imread(args["image"])
image = imutils.resize(image, width=500)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# detect faces in the grayscale image
rects = detector(gray, 1)

# loop over the face detections
for (i, rect) in enumerate(rects):
    # determine the facial landmarks for the face region, then
    # convert the facial landmark (x, y)-coordinates to a NumPy
    # array
    shape = predictor(gray, rect)
    shape = face_utils.shape_to_np(shape)

    # convert dlib's rectangle to a OpenCV-style bounding box
    # [i.e., (x, y, w, h)], then draw the face bounding box
    (x, y, w, h) = face_utils.rect_to_bb(rect)
    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)

    # show the face number
    cv2.putText(image, "Face #{}".format(i + 1), (x - 10, y - 10),
        cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

    # loop over the (x, y)-coordinates for the facial landmarks
    # and draw them on the image
    for (x, y) in shape:
        cv2.circle(image, (x, y), 1, (0, 0, 255), -1)

# show the output image with the face detections + facial landmarks
cv2.imshow("Output", image)
cv2.waitKey(0)

Tags: andthetoimageimportargscv2detector
1条回答
网友
1楼 · 发布于 2024-06-16 10:05:20

面部标志存储在shape中。例如,shape[0][0]是第一个点的x坐标,shape[0][1]是第一个点的y坐标,依此类推。如果要在坐标34、37和46上绘制矩形:

cv2.rectangle(image,(shape[36][0], shape[36][1]), (shape[45][0],shape[33][1]), (255,0,0), 1)

enter image description here

相关问题 更多 >