一、OpenCV简介
二、OpenCV的基本使用
1.安装OpenCV模块
pip install opencv-python
2.读取图片
示例代码:
# 导入模块
import cv2 as cv
# 读取图片
image = cv.imread('test.png') # 路径中不能有中文,否则加载图片失败
# 显示图片
cv.imshow('read_img', image)
# 等待键盘输入 单位毫秒 传入0则是无限等待
cv.waitKey(0)
# 由于OpenCV底层是C++编写的,需要释放内存
cv.destroyAllWindows()
测试图片:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vkdwYgoD-1657533164863)(assets/20220711163742.png)]](https://file.cfanz.cn/uploads/jpeg/2022/07/12/17/fL2e8NC2Ne.jpeg)
测试效果:![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ae3Aakip-1657533164865)(assets/20220711164020.png)]](https://file.cfanz.cn/uploads/jpeg/2022/07/12/17/GHdP93067W.jpeg)
3.图片灰度转换
示例代码:
import cv2 as cv
# 加载图片
img = cv.imread('test.png')
# 显示图片
cv.imshow('BGR image', img)
# cv2读取图片的通道是BGR(蓝绿红)
# PIL读取图片的通道是RGB
# 将图片灰度转换
gray_img = cv.cvtColor(img, code=cv.COLOR_BGR2GRAY)
# 显示转换后的图片
cv.imshow('gray_image', gray_img)
# 保存图片
cv.imwrite('gray_test.png', gray_img)
# 等待键盘输入
cv.waitKey(0)
# 释放内存
cv.destroyAllWindows()
效果:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ITsuMXuI-1657533164866)(assets/20220711164214.png)]](https://file.cfanz.cn/uploads/jpeg/2022/07/12/17/33SZb57102.jpeg)
4.修改图片尺寸
示例代码:
import cv2 as cv
# 加载图片
img = cv.imread('test.png')
# 显示图片
# cv.imshow('input image', img)
print("原图片的形状", img.shape)
# 修改图片尺寸
# resize_img = cv.resize(img, dsize=(110, 160))
resize_img = cv.resize(img, dsize=(400, 360))
print("修改后图片的形状", resize_img.shape)
cv.imshow('resize_img', resize_img)
# 键盘输入q的时候,退出
while True:
if ord('q') == cv.waitKey(0):
break
# 释放内存
cv.destroyAllWindows()
效果:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4VfcjlTI-1657533164868)(assets/20220711164753.png)]](https://file.cfanz.cn/uploads/png/2022/07/12/17/8Ad3N9DfZT.png)
5.绘制矩形、圆
OpenCV可以对图片进行任意编辑、处理。
示例代码
import cv2 as cv
img = cv.imread('test.png')
# 左上角的坐标是(x,y),矩形的宽度为w,高度为h
x, y, w, h = 50, 50, 80, 80
# 画矩形
cv.rectangle(img, (x, y, x+w, y+h), color=(0, 255, 255), thickness=2) # color=BGR,thickness参数表示画笔的粗细/线条宽度
# 画圆
# center元组指原点的坐标,radius为半径
cv.circle(img, center=(x+w//2, y+h//2), radius=w//2, color=(0, 0, 255), thickness=2)
resize_img = cv.resize(img, dsize=(420, 360))
# 显示图片
cv.imshow('result_image', resize_img)
cv.waitKey(0)
# 释放内存
cv.destroyAllWindows()
效果:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JC8j8C9T-1657533164869)(assets/20220711165258.png)]](https://file.cfanz.cn/uploads/png/2022/07/12/17/E935Ya68K9.png)
6.人脸检测
6.1Haar级联的概念
6.2获取Haar级联数据
6.3使用OpenCV进行人脸检测
6.3.1静态图像中人脸检测
6.3.1.1检测人脸
示例代码:
import cv2 as cv
def face_detect_demo():
# 将图片转换为灰度
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# 加载特征数据
face_detector = cv.CascadeClassifier('D:\software\Python\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')
# faces为检测区域
faces = face_detector.detectMultiScale(gray)
for x, y, w, h in faces:
# 绘制矩形
cv.rectangle(img, (x, y), (x+w, y+h), color=(0, 255, 0), thickness=2)
# 显示图片
cv.imshow('result', img)
# 加载图片
img = cv.imread('huge.jpeg')
face_detect_demo()
# cv.imshow('input image', img)
cv.waitKey(0)
cv.destroyAllWindows()
效果:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UJKYaVVJ-1657533164870)(assets/20220711104954.png)]](https://file.cfanz.cn/uploads/jpeg/2022/07/12/17/4CE6f06G19.jpeg)
6.3.1.2检测多张人脸
示例代码:
import cv2 as cv
# 定义人脸检测方法
def face_detect_demo():
# 将图片灰度
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# 加载特征数据
face_detector = cv.CascadeClassifier(
'D:\software\Python\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')
# faces为检测区域
# 发现有一些没检测出来
faces = face_detector.detectMultiScale(gray, scaleFactor=1.01, minNeighbors=3, maxSize=(40, 40), minSize=(35, 35))
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('2.jpeg')
# 调用人脸检测方法
face_detect_demo()
cv.waitKey(0)
cv.destroyAllWindows()
测试图片:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QhDsacfc-1657533164871)(assets/2.jpeg)]](https://file.cfanz.cn/uploads/jpeg/2022/07/12/17/fZf1b8G3dV.jpeg)
效果:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XdVlQGyl-1657533164872)(assets/20220711171924.jpg)]](https://file.cfanz.cn/uploads/jpeg/2022/07/12/17/6XASY1dB0J.jpeg)
6.3.2视频中的人脸检测
示例代码:
import cv2 as cv
def face_detect_demo(img):
# 将图片转换为灰度
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# 加载特征数据
face_detector = cv.CascadeClassifier(
'D:\software\Python\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')
# faces为检测区域
faces = face_detector.detectMultiScale(gray, flags=cv.CASCADE_SCALE_IMAGE)
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.namedWindow('result', 0)
# 调整窗口大小
cv.resizeWindow('result', 500, 500)
# 显示图片
cv.imshow('result', img)
# 读取视频
cap = cv.VideoCapture('test.mp4')
while True:
# frame就是每一帧的图像,是个三维矩阵(按帧读取)
flag, frame = cap.read()
print(f'flag:{flag}, frame.shape:{frame.shape}')
if not flag:
# 视频播放结束,退出
break
face_detect_demo(frame)
if ord('q') == cv.waitKey(0):
break
# 释放内存
cv.destroyAllWindows()
cap.release()
效果:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-idqVVKkC-1657533164872)(assets/20220711172317.jpg)]](https://file.cfanz.cn/uploads/jpeg/2022/07/12/17/765e3IfV9J.jpeg)
6.3.3人脸识别
6.3.3.1训练数据
在使用Python 3&OpenCV 3.0.0进行人脸识别训练时发现异常:
AttributeError:'module' object has no attribute 'LBPHFaceRecognizer_create' OpenCV ,需要安装opencv-contrib-python模块:
pip install opencv-contrib-python
示例代码:
import os
import cv2
import numpy as np
from PIL import Image
def getImageAndLabels(path):
facesSamples = []
ids = []
imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
# 检测人脸
face_detector = cv2.CascadeClassifier(
'D:\software\Python\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为检测区域
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 = './data/jm/'
# 获取图像数组和id标签数组
faces, ids = getImageAndLabels(path)
# 获取循环对象
"""
AttributeError: module 'cv2' has no attribute 'face'
"""
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.train(faces, np.array(ids))
# 保存文件
recognizer.write('trainer/trainer.yml')
训练部分图像:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LVOKHwTR-1657533164873)(assets/20220711172816.jpg)]](https://file.cfanz.cn/uploads/jpeg/2022/07/12/17/H115H159D4.jpeg)
6.3.3.2基于LBPH的人脸识别
示例代码:
import cv2
# 加载训练数据集文件
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer/trainer.yml')
# 准备识别的图片
img = cv2.imread('7.bmp')
# 将图片转换为灰度
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 加载特征数据
face_detector = cv2.CascadeClassifier(
'D:\software\Python\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')
# faces为检测区域
faces = face_detector.detectMultiScale(gray)
for x, y, w, h in faces:
# 绘制矩形
cv2.rectangle(img, (x, y), (x + w, y + h), color=(0, 255, 0), thickness=2)
# 人脸识别
id,confidence = recognizer.predict(gray[y:y+h, x:x+w])
print(f"标签id:{id},置信评分:{confidence}")
# 显示图片
cv2.imshow('result', img)
cv2.waitKey(0)
# 释放内存
cv2.destroyAllWindows()
测试图像:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AsglNF4W-1657533164874)(assets/7.bmp)]](https://file.cfanz.cn/uploads/bmp/2022/07/12/17/OY2O477P1X.bmp)
测试效果:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lPYiqfXL-1657533164874)(assets/20220711173412.jpg)]](https://file.cfanz.cn/uploads/jpeg/2022/07/12/17/753HfQ31F5.jpeg)
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7NY7Vmpx-1657533164875)(assets/20220711173445.jpg)]](https://file.cfanz.cn/uploads/jpeg/2022/07/12/17/451BRfPW42.jpeg)
因为上面这个图像不在训练数据中,所以置信评分高于80。
换成下面这个图像(jim文件夹下的11.bmp)进行测试:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TjCbFTRw-1657533164875)(assets/11.bmp)]](https://file.cfanz.cn/uploads/bmp/2022/07/12/17/Md1ddJ9BSe.bmp)
测试效果:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SfYek7M2-1657533164876)(assets/20220711174034.jpg)]](https://file.cfanz.cn/uploads/jpeg/2022/07/12/17/N26d37c3d3.jpeg)
在训练数据中,置信评分为0。
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3kzoF2Mw-1657533164877)(assets/20220711174126.jpg)]](https://file.cfanz.cn/uploads/jpeg/2022/07/12/17/6423b3NeS1.jpeg)
参考文章及其它:
- https://blog.csdn.net/weixin_43493559/article/details/106600471
- B站视频:OpenCv人脸识别开发实战
- https://blog.csdn.net/shangxiaqiusuo1/article/details/84888408
- ORL人脸数据库40个:http://www.qudong51.net/qudong/1040.html
- http://www.webzuan.cn/szk/7194.html
- https://blog.csdn.net/qq_52131774/article/details/121265931










