记录一次人脸识别的学习(代码)

读取摄像头信息并且带上文字

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/7/23 20:11
# @Author  : Yuxinxin
# @Site    : 
# @File    : cv2读取摄像头图像信息.py
# @Software: PyCharm

import cv2
from PIL import Image, ImageDraw
import numpy as  np

# 1、调用摄像头
# 2、读取摄像头的头像信息
# 3、在图像上添加文字
# 4、保存图像


capture = cv2.VideoCapture(0, cv2.CAP_DSHOW)  # 调用第一个摄像头的信息
while True:
    ret, frame = capture.read()  # 返回一帧的数据
    #  pil的方法只能处理pil的图像,所以这里进行转换 从cv2的BGR转换为pil的RGB
    image_pil = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
    draw = ImageDraw.Draw(image_pil)
    draw.text((100, 100), "press q to quit", fill=(255, 255, 255))
    # 将frame对象转换回cv2格式
    frame = cv2.cvtColor(np.asarray(image_pil), cv2.COLOR_RGB2BGR)
    cv2.imshow("capture", frame)
    k = cv2.waitKey(1) & 0xff
    if k == 27:
        cv2.imwrite("../images/out.jpg", frame)
        break

capture.release()

将多人照中的每个头像勾勒出来

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/7/20 21:02
# @Author  : Yuxinxin
# @Site    : 
# @File    : test_compare_faces  .py
# @Software: PyCharm

import face_recognition
from PIL import Image, ImageDraw

image = face_recognition.load_image_file("../images/3.jpg")

face_landmarks_list = face_recognition.face_landmarks(image)
image_pil = Image.fromarray(image)
d = ImageDraw.Draw(image_pil)  # 生成一张PIL图像
i = 1
for face_landmarks in face_landmarks_list:
    facial_features = [
        'chin',
        'left_eyebrow',
        'right_eyebrow',
        'nose_tip',
        'left_eye',
        'right_eye',
        'top_lip',
        'bottom_lip'
    ]
    for facial_feature in facial_features:
        print("第{}人的{}的位置在{}".format(i, facial_feature, face_landmarks[facial_feature]))
        d.line(face_landmarks[facial_feature], width=2)  # 在pil图片上回值线条
    i = i+1
image_pil.show()



用矩形选框标识人脸

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/7/20 20:02
# @Author  : Yuxinxin
# @Site    : 
# @File    : test_face_recognition.py
# @Software: PyCharm

import face_recognition
from PIL import Image
import cv2

# 加载要识别的人脸图像,加载返回Numpy数组 ,记录了图片的所有像素的特征向量
image = face_recognition.load_image_file("../images/3.jpg")
# 定位所有图中人脸的位置 返回一个列表,列表每一行就是一张人脸的位置信息,包括[top,right,bottom,left]
locations = face_recognition.face_locations(image)
for location in locations:
    top, right, bottom, left = location
    print("已识别到人脸部位的像素区域:top:{}, right:{}, bottom:{}, left:{}".format(top, right, bottom, left))
    # 借用PIL库的Image方法把人脸抠出来
    # image_face = image[top:bottom, left:right]
    # image_pil = Image.fromarray(image_face)
    # image_pil.show()

    # 借助cv2 画个矩形 去标识人脸
    start = (left, top)
    end = (right, bottom)
    cv2.rectangle(image, start, end, (0, 0, 255), thickness=2)  # 在image上以start开始 end结束 颜色是 框的粗细是2
cv2.imshow('win1', image)
cv2.waitKey()

显示未知图片中的已知头像

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/7/21 20:58
# @Author  : Yuxinxin
# @Site    : 
# @File    : 显示未知图片中已知人物的脸.py
# @Software: PyCharm

import face_recognition
import cv2


known_image = face_recognition.load_image_file("../images/雷子.jpg")
unknown_image = face_recognition.load_image_file("../images/2.jpg")

results = []

known_face_encoding = face_recognition.face_encodings(known_image)[0]
unknown_face_encodings = face_recognition.face_encodings(unknown_image)
face_locations = face_recognition.face_locations(unknown_image)

for i in range(len(face_locations)):    # face_locations的长度代表有多少张脸
    top, right, bottom, left = face_locations[i]
    face_image = unknown_image[top:bottom, left:right]
    face_encoding = face_recognition.face_encodings(face_image)
    if face_encoding:
        result = {}
        matches = face_recognition.compare_faces([unknown_face_encodings[i]], known_face_encoding, tolerance=0.39)
        print(matches)
        if True in matches:
            print("在未知图片中找到了已知面孔")
            result['face_encoding'] = face_encoding
            result['isView'] = True
            result['location'] = face_locations[i]
            result['face_id'] = i+1
            results.append(result)

for result in results:
    if result['isView']:
        print("已知面孔匹配上第{}张脸".format(result['face_id']))
        top, right, bottom, left = result['location']
        start = (left, top)
        end = (right, bottom)
        cv2.rectangle(unknown_image, start, end, (0, 0, 255), thickness=2)
        font = cv2.FONT_HERSHEY_COMPLEX
        cv2.putText(unknown_image, "yuxinxin", (left+6, bottom+24), font, 1.0, (255, 2555, 255))
cv2.imshow('win1', unknown_image)
cv2.waitKey()




最终的监控系统

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/7/23 20:58
# @Author  : Yuxinxin
# @Site    : 
# @File    : 人脸识别监控系统.py
# @Software: PyCharm

import face_recognition
import os
import cv2
from PIL import ImageDraw, Image, ImageFont
import numpy as np


# 解析已有人员的照片的照片名和任务面部编码信息
def load_image(path):
    print("正在加载已知人员的图片")
    for dirpath, dirnames, filenames in os.walk(path):
        print(dirpath, dirnames, filenames)
        facelib = []
        for filename in filenames:
            filepath = os.sep.join([dirpath, filename])
            face_image = face_recognition.load_image_file(filepath)
            face_encodings = face_recognition.face_encodings(face_image)[0]
            facelib.append(face_encodings)
        return facelib, filenames


facelib, filenames = load_image("./images")

# 调用摄像头
capture = cv2.VideoCapture(0)

while True:
    ret, frame = capture.read()  # 返回一帧的数据
    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)  # 缩小图片 提高对比效率
    rgb_small_frame = small_frame[:, :, ::-1]  # 将openCV的bgr格式转为face_recognition需要的rgb
    face_locations = face_recognition.face_locations(rgb_small_frame)
    face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)  # 因为只有一个人脸信息
    for face_encoding in face_encodings:
        matches = face_recognition.compare_faces(facelib, face_encoding, tolerance=0.3)
        # 如果摄像头中的头像和头像库中的匹配了 取出这个头像
        print(matches)
        face_names = []
        name = "未知头像"
        if True in matches:
            first_match_index = matches.index(True)
            name = filenames[first_match_index][:-4]  # 取出文件的名字
        face_names.append(name)

        for (top, right, bottom, left), name in zip(face_locations, face_names):
            top *= 4
            right *= 4
            bottom *= 4
            left *= 4

            # 借助cv2 画个矩形 去标识人脸
            start = (left, top)
            end = (right, bottom)
            cv2.rectangle(frame, start, end, (0, 0, 255), thickness=2)

            #  pil的方法只能处理pil的图像,所以这里进行转换 从cv2的BGR转换为pil的RGB
            image_pil = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
            font = ImageFont.truetype("simhei.ttf", 40)
            draw = ImageDraw.Draw(image_pil)
            draw.text((100, 100), name, font=font, fill=(255, 255, 255))
            # 将frame对象转换回cv2格式
            frame = cv2.cvtColor(np.asarray(image_pil), cv2.COLOR_RGB2BGR)
        cv2.imshow("capture", frame)
        if cv2.waitKey(1) & 0xff == ord("q"):
            break





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值