Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于opencvpython的人脸识别_Python_Opencv - Fatal编程技术网

基于opencvpython的人脸识别

基于opencvpython的人脸识别,python,opencv,Python,Opencv,我有一个opencvpython人脸识别代码 import face_recognition as fr import os import cv2 import face_recognition import numpy as np from time import sleep def get_encoded_faces(): """ looks through the faces folder and encodes all the faces :retu

我有一个opencvpython人脸识别代码

import face_recognition as fr
import os
import cv2
import face_recognition
import numpy as np
from time import sleep


def get_encoded_faces():
    """
    looks through the faces folder and encodes all
    the faces

    :return: dict of (name, image encoded)
    """
    encoded = {}

    for dirpath, dnames, fnames in os.walk("./faces"):
        for f in fnames:
            if f.endswith(".jpg") or f.endswith(".png"):
                face = fr.load_image_file("faces/" + f)
                encoding = fr.face_encodings(face)[0]
                encoded[f.split(".")[0]] = encoding

    return encoded


def unknown_image_encoded(img):
    """
    encode a face given the file name
    """
    face = fr.load_image_file("faces/" + img)
    encoding = fr.face_encodings(face)[0]

    return encoding


def classify_face(im):
    """
    will find all of the faces in a given image and label
    them if it knows what they are

    :param im: str of file path
    :return: list of face names
    """
    faces = get_encoded_faces()
    faces_encoded = list(faces.values())
    known_face_names = list(faces.keys())

    img = cv2.imread(im, 1)
    #img = cv2.resize(img, (0, 0), fx=0.5, fy=0.5)
    #img = img[:,:,::-1]

    face_locations = face_recognition.face_locations(img)
    unknown_face_encodings = face_recognition.face_encodings(img, face_locations)

    face_names = []
    for face_encoding in unknown_face_encodings:
        # See if the face is a match for the known face(s)
        matches = face_recognition.compare_faces(faces_encoded, face_encoding)
        name = "Unknown"

        # use the known face with the smallest distance to the new face
        face_distances = face_recognition.face_distance(faces_encoded, face_encoding)
        best_match_index = np.argmin(face_distances)
        if matches[best_match_index]:
            name = known_face_names[best_match_index]

        face_names.append(name)

        for (top, right, bottom, left), name in zip(face_locations, face_names):
            # Draw a box around the face
            cv2.rectangle(img, (left-20, top-20), (right+20, bottom+20), (255, 0, 0), 2)

            # Draw a label with a name below the face
            cv2.rectangle(img, (left-20, bottom -15), (right+20, bottom+20), (255, 0, 0), cv2.FILLED)
            font = cv2.FONT_HERSHEY_DUPLEX
            cv2.putText(img, name, (left -20, bottom + 15), font, 1.0, (255, 255, 255), 2)


    # Display the resulting image
    while True:

        cv2.imshow('Video', img)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            return face_names 


print(classify_face("test-image");

这是我们保存用于测试的拍摄图像,但我希望它从相机中拍摄图像,然后识别它,这样这里的任何人都可以告诉我如何更改测试图像,以便它将从相机中拍摄测试图像,而不是我们保存在数据库中用于测试的图像

如果您想检查摄像机的单帧,只需使用

cap = cv2.VideoCapture(0)
status, img = cap.read()
而不是

img = cv2.imread(im, 1)

若你们想检查流中的面,那个么你们需要把所有的都放在循环中

def classify_face(im):

    faces = get_encoded_faces()
    faces_encoded = list(faces.values())
    known_face_names = list(faces.keys())

    cap = cv2.VideoCapture(0)

    while True:

        status, img = cap.read()

        face_locations = face_recognition.face_locations(img)
        unknown_face_encodings = face_recognition.face_encodings(img, face_locations)

        face_names = []
        for face_encoding in unknown_face_encodings:
            # See if the face is a match for the known face(s)
            matches = face_recognition.compare_faces(faces_encoded, face_encoding)
            name = "Unknown"

            # use the known face with the smallest distance to the new face
            face_distances = face_recognition.face_distance(faces_encoded, face_encoding)
            best_match_index = np.argmin(face_distances)
            if matches[best_match_index]:
                name = known_face_names[best_match_index]

            face_names.append(name)

            for (top, right, bottom, left), name in zip(face_locations, face_names):
                # Draw a box around the face
                cv2.rectangle(img, (left-20, top-20), (right+20, bottom+20), (255, 0, 0), 2)

                # Draw a label with a name below the face
                cv2.rectangle(img, (left-20, bottom -15), (right+20, bottom+20), (255, 0, 0), cv2.FILLED)
                font = cv2.FONT_HERSHEY_DUPLEX
                cv2.putText(img, name, (left -20, bottom + 15), font, 1.0, (255, 255, 255), 2)

        cv2.imshow('Video', img)

        print(face_names)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            return

编辑:使用视频流的完整代码(有小改动)。它对我有用。但是,如果以前的函数确实适用于您,那么这个版本可能对您没有帮助-函数
classify\u face
与前面的示例几乎相同

import os
import cv2
import face_recognition as fr
import numpy as np


def get_encoded_faces(folder="./faces"):
    """
    looks through the faces folder and encodes all
    the faces

    :return: dict of (name, image encoded)
    """
    encoded = {}

    for dirpath, dnames, fnames in os.walk(folder):
        for f in fnames:
            if f.lower().endswith(".jpg") or f.lower().endswith(".png"):

                fullpath = os.path.join(dirpath, f)
                face = fr.load_image_file(fullpath)

                # normally face_encodings check if face is on image - and it can get empty result
                height, width = face.shape[:2]
                encoding = fr.face_encodings(face, known_face_locations=[(0, width, height, 0)])
                if len(encoding) > 0:
                    encoding = encoding[0]
                    encoded[f.split(".")[0]] = encoding

    return encoded


def classify_face(im):
    """
    will find all of the faces in a given image and label
    them if it knows what they are

    :param im: str of file path
    :return: list of face names
    """
    faces = get_encoded_faces()
    faces_encoded = list(faces.values())
    known_face_names = list(faces.keys())

    cap = cv2.VideoCapture(0)

    while True:

        status, img = cap.read()
        #print('status:', status)

        face_locations = fr.face_locations(img)
        unknown_face_encodings = fr.face_encodings(img, face_locations)

        face_names = []
        for location, face_encoding in zip(face_locations, unknown_face_encodings): # I moved `zip()` in this place

            # See if the face is a match for the known face(s)
            matches = fr.compare_faces(faces_encoded, face_encoding)
            name = "Unknown"

            # use the known face with the smallest distance to the new face
            face_distances = fr.face_distance(faces_encoded, face_encoding)

            best_match_index = np.argmin(face_distances)
            if matches[best_match_index]:
                name = known_face_names[best_match_index]

            face_names.append(name)

            top, right, bottom, left = location
            # Draw a box around the face

            cv2.rectangle(img, (left-20, top-20), (right+20, bottom+20), (255, 0, 0), 2)

            # Draw a label with a name below the face
            cv2.rectangle(img, (left-20, bottom -15), (right+20, bottom+20), (255, 0, 0), cv2.FILLED)
            font = cv2.FONT_HERSHEY_DUPLEX
            cv2.putText(img, name, (left -20, bottom + 15), font, 1.0, (255, 255, 255), 2)

        print('face_names:', face_names)
        cv2.imshow('Video', img)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            return face_names 

# --- main ---

print(classify_face("test-image"))

cv2.destroyAllWindows()

编辑问题并使用特殊按钮
{}
格式化代码。在opencv的每个教程中,您应该了解如何从相机获取图像
cap=cv2.VideoCapture(0)
和循环中的
状态,frame=cap.read()
是的,我看到了很多代码,但当我把从相机拍摄图像的代码放到我现有的代码中时,它不起作用。如果你得到opencv的任何教程,你将看到如何使用它——你将在两天前创建解决方案:)下次首先使用谷歌来找到解决方案——你可能会比询问Stackoverflow更快地得到解决方案。顺便说一句:如果你想测试摄像机的单帧,然后简单地用它代替
img=cv2.imread(im,1)
——比如
cap=cv2.VideoCapture(0)
status,img=cap.read()
。如果你想检查流中的所有帧,那么你可能需要更多的更改-你需要像在教程中一样读取帧的循环。非常感谢,先生,它对图像非常有效,当我尝试使用相机的连续视频流进行循环时,它运行时没有任何错误,但它不会打开并录制???????您能告诉我有什么问题吗?请使用
print()
查看变量中的内容以及执行的代码部分。在循环内部,您需要更新窗口中图像的
imshow()
waitKey()
。{while True:imshow()waitKey()status,img=cap.read()}在True循环中,我将您提到的两个都放进去。我把print()放在下面的结尾{cv2.imshow('Video',img)print(face_names)print(),如果cv2.waitKey(1)&0xFF==ord('q'):return}整个代码的其余部分都是一样的,但是先生,它并没有给出输出,就像在我运行代码之后,它进入输出窗口,在那里开始闪烁,没有结果……:({>>>重新启动:C:\Users\ShanAli\Desktop\Mechantronic project\face detection database\face\u rec\face\u rec.py>>>}它的退出循环是这样的,没有任何错误,也没有打开camuse more
print()
-ie.在每行打印之前,命令会做什么(比如
打印(“运行外部for loop”)
打印(“我在内部for loop”)
。或者学习如何使用调试程序。如果您有错误的值或错误的缩进,它可能会运行
返回
并退出循环。请参阅我的代码。如果您仍然存在问题,请在新页面上创建新问题-您将有更多的地方放置完整的代码和说明。顺便问一下:您是否直接在终端/控制台中运行代码-
python脚本.py
-要查看错误消息吗?如果您在某个编辑器中运行,它可能会在您看到该窗口之前关闭该窗口。