目录
- 1 读取图片
- 2 将图片灰度转换
- 3 修改图片尺寸
- 4 绘制矩形_圆
- 5 人脸检测
- 6 检测多张人脸
- 7 检测视频中的人脸
- 8 训练数据并人脸识别
- 8.1 训练数据
- 8.2 人脸识别
1 读取图片
代码语言:javascript复制# 导入模块
import cv2 as cv
# 读取图片
img=cv.imread('E:/girl.jpg') # 路径中不能有中文,否则加载图片失败
# 将图片缩小至原来的1/2
height, width = img.shape[:2]
reSize = cv.resize(img, (int(width/3), int(height/3)), interpolation=cv.INTER_CUBIC)
# 显示图片
cv.imshow('read_reSize',reSize)
# 等待键盘输入 单位毫秒 传入0 则就是无限等待
cv.waitKey(0)
# 释放内存 由于OpenCV底层是C 编写的
cv.destroyAllWindows()
2 将图片灰度转换
代码语言:javascript复制import cv2 as cv
img=cv.imread('E:/girl.jpg')
cv.imshow('BGR_img',img)
# 将图片缩小至原来的1/2
height, width = img.shape[:2]
reSize = cv.resize(img, (int(width/3), int(height/3)), interpolation=cv.INTER_CUBIC)
#将图片灰度转换
gray_img=cv.cvtColor(reSize,cv.COLOR_BGR2GRAY)
cv.imshow('gray_img',gray_img)
#保存图片
cv.imwrite('gray_girl.jpg',gray_img)
cv.waitKey(0)
cv.destroyAllWindows()
3 修改图片尺寸
代码语言:javascript复制import cv2 as cv
img=cv.imread('E:/girl.jpg')
cv.imshow('img',img)
print('原来图片的形状',img.shape)
# resize_img=cv.resize(img,dsize=(200,240))
resize_img=cv.resize(img,dsize=(600,560))
print('修改后图片的形状:',resize_img.shape)
cv.imshow('resize_img',resize_img)
# cv.waitKey(0)
#只有输入q时候,退出
while True:
if ord('q')==cv.waitKey(0):
break
cv.destroyAllWindows()
4 绘制矩形_圆
代码语言:javascript复制import cv2 as cv
img = cv.imread('E:/girl.jpg')
# 左上角的坐标是(x,y) 矩形的宽度和高度(w,h)
# 将图片缩小至原来的1/2
height, width = img.shape[:2]
reSize = cv.resize(img, (int(width/3), int(height/3)), interpolation=cv.INTER_CUBIC)
x, y, w, h = 95, 66, 90, 90
cv.rectangle(reSize, (x, y, x w, y h), color=(0, 255, 255), thickness=3) # BGR
# 绘制圆center元组指圆点的坐标 radius:半径
x, y, r = 188, 138, 88
cv.circle(reSize, center=(x, y),radius=r, color=(0, 0, 255), thickness=2)
# 显示图片
cv.imshow('rectangle_img',reSize)
cv.waitKey(0)
cv.destroyAllWindows()
5 人脸检测
代码语言:javascript复制import cv2 as cv
def face_detect_demo():
#将图片转换为灰度图片
gray=cv.cvtColor(reSize,cv.COLOR_BGR2GRAY)
#加载特征数据
face_detector=cv.CascadeClassifier(r'E:softwarepython3.8.2Libsite-packagescv2datahaarcascade_frontalface_default.xml')
faces=face_detector.detectMultiScale(gray)
for x,y,w,h in faces:
cv.rectangle(reSize,(x,y),(x w,y h),color=(0,255,0),thickness=2)
cv.imshow('result',reSize)
# 加载图片
img=cv.imread('E:/girl.jpg')
# 将图片缩小至原来的1/2
height, width = img.shape[:2]
reSize = cv.resize(img, (int(width / 3), int(height / 3)), interpolation=cv.INTER_CUBIC)
face_detect_demo()
cv.waitKey(0)
cv.destroyAllWindows()
6 检测多张人脸
代码语言:javascript复制import cv2 as cv
def face_detect_demo():
# 将图片灰度
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
# 加载特征数据
face_detector = cv.CascadeClassifier(r'E:softwarepython3.8.2Libsite-packagescv2datahaarcascade_frontalface_default.xml')
faces = face_detector.detectMultiScale(gray)
for x, y, w, h in faces:
print(x, y, w, h)
cv.rectangle(img, (x, y), (x w, y h), color=(0, 0, 255), thickness=2)
cv.circle(img, center=(x w//2, y h//2), radius=w//2, color=(0, 255, 0), thickness=2)
# 显示图片
cv.imshow('result', img)
# 加载图片
img = cv.imread('E:/girls.jpeg')
# 调用人脸检测方法
face_detect_demo()
cv.waitKey(0)
cv.destroyAllWindows()
7 检测视频中的人脸
代码语言:javascript复制import cv2 as cv
def face_detect_demo(img):
# 将图片灰度
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
# 加载特征数据
face_detector = cv.CascadeClassifier(
'E:softwarepython3.8.2Libsite-packagescv2datahaarcascade_frontalface_default.xml')
faces = face_detector.detectMultiScale(gray)
for x, y, w, h in faces:
cv.rectangle(img, (x, y), (x w, y h), color=(0, 0, 255), thickness=2)
cv.circle(img, center=(x w//2, y h//2), radius=(w//2), color=(0,255,0),thickness=2)
cv.imshow('result',img)
# 读取视频
cap = cv.VideoCapture('E:/video.mp4')
while True:
flag, frame = cap.read()
print('flag:', flag, 'frame.shape:', frame.shape)
if not flag:
break
face_detect_demo(frame)
if ord('q') == cv.waitKey(10):
break
cv.destroyAllWindows()
cap.release()
8 训练数据并人脸识别
8.1 训练数据
代码语言:javascript复制import os
import cv2
import sys
from PIL import Image
import numpy as np
def getImageAndLabels(path):
facesSamples = []
ids = []
imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
# 检测人脸
face_detector = cv2.CascadeClassifier(
'E:/software/python3.8.2/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml')
# 遍历列表中的图片
for imagePath in imagePaths:
# 打开图片
PIL_img = Image.open(imagePath).convert('L')
# 将图像转换为数组
img_numpy = np.array(PIL_img, 'uint8')
faces = face_detector.detectMultiScale(img_numpy)
# 获取每张图片的id
id = int(os.path.split(imagePath)[1].split('.')[0])
for x, y, w, h in faces:
facesSamples.append(img_numpy[y:y h, x:x w])
ids.append(id)
return facesSamples, ids
if __name__ == '__main__':
# 图片路径
path = 'C:/Users/单纯小男子/Downloads/代码/data/jm/'
# 获取图像数组和id标签数组
faces, ids = getImageAndLabels(path)
# 获取训练对象
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.train(faces,np.array(ids))
# 保存文件
recognizer.write('trainer.yml')
8.2 人脸识别
代码语言:javascript复制import cv2
import numpy as np
import os
# 加载训练数据集文件
recogizer = cv2.face.LBPHFaceRecognizer_create()
recogizer.read('./trainer.yml')
# 准备识别的图片
img = cv2.imread(r'E:/girl.jpg')
# 将图片缩小至原来的1/2
height, width = img.shape[:2]
reSize = cv2.resize(img, (int(width / 3), int(height / 3)), interpolation=cv2.INTER_CUBIC)
gray = cv2.cvtColor(reSize, cv2.COLOR_BGR2GRAY)
face_detector = cv2.CascadeClassifier(
r'E:softwarepython3.8.2Libsite-packagescv2datahaarcascade_frontalface_default.xml')
faces = face_detector.detectMultiScale(gray)
for x, y, w, h in faces:
cv2.rectangle(reSize, (x, y), (x w, y h), (0, 255, 0), 2)
# 人脸识别
id, confidence=recogizer.predict(gray[y:y h, x:x w])
print('标签id:', id,'置信评分:', confidence)
cv2.imshow('result', reSize)
cv2.waitKey(0)
cv2.destroyAllWindows()
相关资料借鉴可下载: 链接:https://pan.baidu.com/s/1OFf2rWRA1_vKMFuuVpkwGw 提取码:azqj
我的博客即将同步至腾讯云 社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=4ggjmr46hw6c