Simple face recognition project for getting started with OpenCV

After learning image processing and turning on the camera to obtain video streams, you can start a simple face recognition project.


Face recognition first needs to detect the face.

Detect face area and draw rectangle

# 加载图片
    img = face_recognition.load_image_file("lena.png")
    # 检测人脸区域
    f_pos = face_recognition.face_locations(img)[0]
    print("top,right.bottom,left", f_pos)
    # 在人脸区域绘制矩形
    cv2.rectangle(img,(f_pos[3],f_pos[0]),(f_pos[1],f_pos[2]),(0,0,200),2)
    cv2.imshow("",img)
    cv2.waitKey(0)

Select a face picture to detect it.
insert image description here
Approximately, the face area can be detected.

Multiple Faces for Recognition

After a single face recognition, multiple face recognition is required.

img = face_recognition.load_image_file("6.jpg")
    faces = face_recognition.face_locations(img)
    for face in faces:
        cv2.rectangle(img,(face[3],face[0]),(face[1],face[2]),(0,0,210),2)
    cv2.imshow("",img)
    cv2.waitKey(0)

Just add a for loop.
insert image description here

Draw facial features

img = face_recognition.load_image_file("18.jpg")
    faces = face_recognition.face_locations(img)
    # 五官位置
    marks = face_recognition.face_landmarks(img)
    for word,mark in enumerate(marks):
        for key,ms in mark.items():
            for i in range(len(ms)):
                point = ms[i]
                # 圆
                cv2.circle(img,(point[0],point[1]),2,(0,200,0))
    cv2.imshow("", img)
    cv2.waitKey(0)

insert image description here

Face detection in video

After detecting the face in the picture, you need to detect the face in the video.

# 摄像头
    # cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
    cap = cv2.VideoCapture(".mp4")
    while True:
        ok,frame = cap.read()
        if ok :
            # 从视频流中检测人脸
            faces = face_recognition.face_locations(frame)
            for (top, right, bottom, left) in faces:
                cv2.rectangle(frame,(left,top),(right,bottom),(0,0,100),2)
        cv2.imshow("", frame)
        cv2.waitKey(1)
    cap.release()
    cv2.destroyAllWindows()

You can choose a video file or a camera!

face recognition

After a face is detected, face comparison is required.

obama = face_recognition.load_image_file("1.jpg")
    biden = face_recognition.load_image_file("1.jpg")
    mei = face_recognition.load_image_file("1.jpg")
    # 对图片编码
    obamacode = face_recognition.face_encodings(obama)[0]
    bidencode = face_recognition.face_encodings(biden)[0]
    meicode = face_recognition.face_encodings(mei)[0]
# 已录入的人脸
    headimgs = [obamacode,bidencode]
    # 距离计算
    # dist = face_recognition.face_distance(headimgs,meicode)
    # print(dist)
    # 人脸匹配
    rs = face_recognition.compare_faces(headimgs,meicode,tolerance=0.5)
    print("摄像头中的是: ",rs)

The detected faces are encoded and compared with the registered faces.

Guess you like

Origin blog.csdn.net/qq_46556714/article/details/130869248