Python+OpenCV: cv2.imwrite

后端 未结 3 1179
离开以前
离开以前 2021-01-30 09:23

I\'m trying to detect a face and write down area with the face in a separate file. How can I do it? I think that i must use \"faces\" (you can see this var in code). But how?

3条回答
  •  春和景丽
    2021-01-30 10:05

    Alternatively, with MTCNN and OpenCV(other dependencies including TensorFlow also required), you can:

    1 Perform face detection(Input an image, output all boxes of detected faces):

    from mtcnn.mtcnn import MTCNN
    import cv2
    
    face_detector = MTCNN()
    
    img = cv2.imread("Anthony_Hopkins_0001.jpg")
    detect_boxes = face_detector.detect_faces(img)
    print(detect_boxes)
    

    [{'box': [73, 69, 98, 123], 'confidence': 0.9996458292007446, 'keypoints': {'left_eye': (102, 116), 'right_eye': (150, 114), 'nose': (129, 142), 'mouth_left': (112, 168), 'mouth_right': (146, 167)}}]

    2 save all detected faces to separate files:

    for i in range(len(detect_boxes)):
        box = detect_boxes[i]["box"]
        face_img = img[box[1]:(box[1] + box[3]), box[0]:(box[0] + box[2])]
        cv2.imwrite("face-{:03d}.jpg".format(i+1), face_img)
    

    3 or Draw rectangles of all detected faces:

    for box in detect_boxes:
        box = box["box"]
        pt1 = (box[0], box[1]) # top left
        pt2 = (box[0] + box[2], box[1] + box[3]) # bottom right
        cv2.rectangle(img, pt1, pt2, (0,255,0), 2)
    cv2.imwrite("detected-boxes.jpg", img)
    

提交回复
热议问题