首页 > 解决方案 > 使用 opencv 在 face_recognition 中写入新图像

问题描述

嗨伙计们,我想用 face_recognition 库编写一个程序。其目的是将一张新面孔的图像片段保存到一个文件夹中,并更新该文件夹,以免将同一张面孔保存两次。我希望程序在输入视频中遇到新面孔时将图像保存到文件夹中。但目前它似乎不起作用。有时它会将同一张脸的整个剪辑保存到我不想要的文件夹中。任何人都可以帮助我使用此代码。我根据我在 youtube 上看到的 #Murtaza 的教程修改了这段代码。

谢谢

import face_recognition
import cv2
import os
import numpy as np


path = r"C:\Users\CHIJINDU\Desktop\KArtIntel"
images = []
class_names= []
myList = os.listdir(path)
for cl in myList:
    curImg= cv2.imread(f'{path}\{cl}')
    images.append(curImg)
    class_names.append(os.path.splitext(cl)[0])
print(class_names)

def find_encodings(images):
    encodelist = []
    for img in images:
        img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
        encode= face_recognition.face_encodings(img)[0]
        encodelist.append(encode)
    return encodelist

encodelistKnown = find_encodings(images)
print(len(encodelistKnown))

cap = cv2.VideoCapture(r"C:\Users\CHIJINDU\Desktop\Elastic.mp4")

while True:
    success, img = cap.read()
    imgS = cv2.resize(img, (0,0), None, 0.25,0.25)
    imgS =cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)

    faceCurFrame= face_recognition.face_locations(imgS)
    encodesCurFrame= face_recognition.face_encodings(imgS, faceCurFrame)

    for encodeFace, faceloc in zip(encodesCurFrame, faceCurFrame):
        matches =  face_recognition.compare_faces(encodelistKnown,encodeFace)
        faceDis = face_recognition.face_distance(encodelistKnown,encodeFace)
        matchIndex= np.argmin(faceDis)

        i=0
        while not [matchIndex]:
            cv2.imwrite(r'C:\Users\CHIJINDU\Desktop\KArtIntel\KUDOS-J14{index}.jpg'.format(index=i), img)
            #fps = int(video_capture.get(cv2.CAP_PROP_FPS))
            #print(fps)
            i+=1

    # Display the resulting image
    cv2.imshow('Video', img)

    # Hit 'q' on the keyboard to quit!
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release handle to the webcam
cap.release()
cv2.destroyAllWindows()

标签: pythonopencvface-recognition

解决方案


推荐阅读