人脸识别(笔记)

案例一:显示图片
#1、导入库
import cv2
# 2、加载图片
img = cv2.imread(r'C:\Users\HASEE\Desktop\image1.jpg')
#  3、创建一个窗口
cv2.namedWindow('meinv')
#  4、显示图片
cv2.imshow('meinv', img)
# 5、暂停图片(如果不暂停,会关闭窗口)
cv2.waitKey(0)
# 6、关闭窗口
cv2.destroyAllWindows()
# 案例二:检查图片中的人脸
# 1、导入库
import cv2
# 2、加载图片
img = cv2.imread('C:/Users/HASEE/Desktop/image1.jpg')
# 3、加载人物模型库
face = cv2.CascadeClassifier('')
# 4、调整图片灰度
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# 5、检查人脸(用人脸模型库去检测灰度图片中的人脸)
faces = face.detectMultiScale(gray)
# 6、标记人脸
for (x, y, w, h) in faces:
    #   参数一:标记图片
    #   参数二:左上角的坐标
    #   参数三:人脸大小
    #   参数四:矩形的颜色RGB (0, 255, 0)red:0 green:255 blue:0
    #   参数五:线框大小
    cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 10)
# 7、创建显示窗口
cv2.namedWindow('chun')
# 8显示图片
cv2.imshow('meinv',img)
# 9暂停窗口
cv2.waitKey()
# 10关闭窗口
cv2.destroyAllWindows()
# 案例三:
# 1、导入库
import cv2
# 2、打开摄像头
capture = cv2.VideoCapture(0)
# 3、获取摄像头实时画面
cv2.namedWindow('chunchun')
while True:
    # 3.1读取摄像头的每一帧的画面
    # capture.read()会返回两个参数
    # ret接收的值是True(有值),False(没有值)   frame是尺寸大小
    ret, frame = capture.read()
    # 3.2显示图片
    cv2.imshow('chun', frame)
    # 暂停窗口
    if cv2.waitKey(5) & 0xFF == ord('q'):
        break
# 4、释放资源
capture.release()
# 5、关闭窗口
cv2.destroyAllWindows()


# 案例四:人脸识别
# 思路:1、导入库
import cv2
# 2、加载人脸模型
face = cv2.CascadeClassifier(r'C:\Users\HASEE\Desktop\haarcascade_frontalface_alt.xml')
# 3、打开摄像头
capture = cv2.VideoCapture(0)
# 4、创建窗口
cv2.namedWindow('lalala')
# 5、获取摄像头真实画面
while True:
    # 5.1读取摄像头每一帧的画面
    ret, frame = capture.read()
    # 5.2灰度图片(彩色的图片占用内存大,性能慢)
    gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
    # 5.3检查人脸
    faces = face.detectMultiScale(gray, 1.1, 3, 0, (100, 100))
    # 5.4标记人脸
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        # 显示图片
        cv2.imshow('chun', frame)
        # 暂停图片
        if cv2.waitKey(5) & 0xFF == ord('q'):
            break
# 6、释放资源
capture.release()
# 7、关闭窗口
cv2.destroyAllWindows()

简单的人脸识别,当然Bug特别多。

猜你喜欢

转载自blog.csdn.net/weixin_42351003/article/details/83040009