一.技术介绍
1.安装cv2
命令行输入 pip install opencv-python
cv2(Opencv):图像识别,摄像头调用
2.人脸检测技术关键
HARR特征级联分类器,大家自行下载haarcascades分类器,github连接附下:
https://github.com/opencv/opencv/tree/master/data/haarcascades
二.代码
import cv2
# 分模块,可以用函数表示,也可以用类表示
# 统一接口, frame: 帧, int fun(int a, int b) def fun(a: int, b: int)
# 类的继承
# 类名用驼峰命名法,其他的用微软命名法
class Model:
def __init__(self, name):
self.name = name
def run(self, frame: dict):
return frame
class GetCamera(Model): # 图片读取模块
# 子类应该继承父类的:除了构造函数之外的所有成员函数和成员变量
def __init__(self, name: str = 'get_camera'):
# 构造函数
super().__init__(name)
self.camera = cv2.VideoCapture(0)
def run(self, frame: dict):
ret, img = self.camera.read()
frame['img'] = img
return frame
# 翻转照片
class Flip(Model):
def __init__(self, name):
super().__init__(name)
def run(self, frame: dict):
img = frame['img']
img = cv2.flip(img, 1)
frame['img'] = img
return frame
class ChalkEffects(Model):
def __init__(self, name):
super().__init__(name)
def run(self, frame: dict):
img = frame['img']
#img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 灰度化
#img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
# cv2.THRESH_BINARY, 5, 3)
# img = cv2.bitwise_not(img)
frame['img'] = img
return frame
class DetectionFace(Model):
def __init__(self, name):
super().__init__(name)
def run(self, frame: dict):
img = frame['img']
# TODO: 检测
face_cascade = cv2.CascadeClassifier("E:\Download\haarcascade_frontalface_default.xml")
eye_cascade = cv2.CascadeClassifier("E:\Download\haarcascade_eye.xml")
# 显示图片(渲染画面)
face = face_cascade.detectMultiScale(img, # 输入的灰度图像
scaleFactor=1.1, # 图像缩放的比例
minNeighbors=5, # 构成目标矩形的最少相邻矩形个数
minSize=(30, 30), # 目标尺寸的最小大小
flags=cv2.CASCADE_SCALE_IMAGE)
frame['face'] = face
eye = eye_cascade.detectMultiScale(img, scaleFactor=1.1, minNeighbors=2, minSize=(7, 7))
frame['eye'] = eye
return frame
class DrawBbox(Model):
def __init__(self, name):
super().__init__(name)
def run(self, frame: dict):
face = frame['face']
eye = frame['eye']
img = frame['img']
# TODO: 画bbox框
# 标记位置 说明:(x,y)为绘制的边框的左上角 (x+w,y+h)为绘制的边框的右下角 (255, 0, 0)为RGB三色值 1为线条的粗细值
for (x, y, w, h) in face:
img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 1)
frame['img']=img
for (x, y, w, h) in eye:
img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 1)
frame['img'] = img
return frame
class Show(Model):
def __init__(self, name):
super().__init__(name)
def run(self, frame: dict):
# 4. 显示图片
img = frame['img']
cv2.imshow('img', img)
cv2.waitKey(1)
return frame
if __name__ == '__main__':
task = [
GetCamera(),
Flip('f'),
ChalkEffects('ce'),
DetectionFace('df'),
DrawBbox('db'),
Show('s'),
]
while True:
frame = {}
for model in task:
frame = model.run(frame)