OpenCV
人脸检测+绘制logo
- 检测人脸
- 绘制人脸区域
- 绘制logo
"""
绘制logo
1. 检测人脸区域
如何检测到人脸
眼睛、鼻子、嘴巴、眉毛、下巴等
级联的过程
OpenCV、Mediapipe、YOLOFace、DBFace等
2. 把logo粘贴在人脸上方
"""
import cv2
import numpy as np
class FaceDetect:
def __init__(self):
classifier = cv2.CascadeClassifier()
classifier.load('./haarcascade_frontalface_alt.xml')
self.classifier = classifier
self.logo = cv2.imread('./fans.jpg')
pass
def capVideo(self):
cap = cv2.VideoCapture(0)
while cap.isOpened():
retval, frame = cap.read()
if not retval:
print('can not read frame')
break
self.detect(frame)
cv2.imshow('frame', frame)
key = cv2.waitKey(25)
if key == ord('z'):
break
cap.release()
pass
def detect(self, face_img):
face_rects = self.classifier.detectMultiScale(face_img)
for face_rect in face_rects:
x, y, w, h = face_rect
cv2.rectangle(face_img, (x, y), (x + w, y + h), color=(0, 0, 255), thickness=2)
self.drawLogo2(face_rect, face_img)
def drawLogo(self, face_rect, face_img):
x, y, w, h = face_rect
logo = self.logo
ratio = min(logo.shape[:2]) / max(logo.shape[:2])
scale_logo = cv2.resize(logo, dsize=(w, round(w * ratio)))
scale_logo_h, scale_logo_w, _ = scale_logo.shape
face_img[y - scale_logo_h:y, x:x + scale_logo_w] = scale_logo
def drawLogo2(self, face_rect, face_img):
"""
1. 找轮廓
- 原图:三通道彩色图
- 灰度图(0-255)
- 黑白二值图(0/255)
2. 绘制轮廓
- 绘制在背景是白色的图
:param face_rect:
:param face_img:
:return:
"""
logo_gray = cv2.cvtColor(self.logo, cv2.COLOR_BGR2GRAY)
retval, logo_binary = cv2.threshold(logo_gray, 100, 255, cv2.THRESH_OTSU)
contours, hierarchy = cv2.findContours(logo_binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
mask = np.zeros_like(self.logo)
cv2.drawContours(mask, contours, 1, color=(255, 255, 255), thickness=-1)
x, y, w, h = face_rect
logo = self.logo
ratio = min(logo.shape[:2]) / max(logo.shape[:2])
scale_logo = cv2.resize(logo, dsize=(w, round(w * ratio)))
scale_mask = cv2.resize(mask, dsize=(w, round(w * ratio)))
scale_logo_h, scale_logo_w, _ = scale_logo.shape
idx = scale_mask == 255
after_mask_logo = scale_logo[idx]
face_img[y - scale_logo_h:y, x:x + scale_logo_w][idx] = after_mask_logo
pass
if __name__ == '__main__':
face_img = cv2.imread('./lyf.png')
face_detect = FaceDetect()
face_detect.detect(face_img)
cv2.imshow('frame', face_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
人脸原图
![lyf.png](https://i-blog.csdnimg.cn/blog_migrate/510949b18f9895cfba42a006a0ba3282.png)
logo图
![fans.jpg](https://i-blog.csdnimg.cn/blog_migrate/74d932041af7d5bb7cc4803700787de0.jpeg)
人脸检测+绘制logo效果图
![image.png](https://i-blog.csdnimg.cn/blog_migrate/f071d48f0ed59137647d2b2618590582.png)