Python-opencv人脸马赛克处理+录制视频到本地

 1 import cv2
 2 
 3 camera = cv2.VideoCapture(0)
 4 
 5 frame_width = int(camera.get(3))
 6 frame_height = int(camera.get(4))
 7 
 8 #  训练好的模型
 9 face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
10 
11 #  处理视频文件
12 fourcc = cv2.VideoWriter_fourcc(*'mp4v')   # 编解码器
13 out = cv2.VideoWriter('test.mp4', fourcc, 30.0, (frame_width, frame_height))  # 保存位置 编解码器 帧数 分辨率
14 
15 while camera.isOpened():
16     ret, frame = camera.read()
17     frame = cv2.flip(frame, 1)  # 参数:0垂直镜像 1水平镜像
18     #  图像处理
19     gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)  #  灰度图像
20     faces = face_cascade.detectMultiScale(gray, 1.1, 5)
21     if ret:
22         for (x, y, w, h) in faces:
23             cv2.rectangle(frame, (x,  y), (x + w, y + h), (0, 255, 0), 2)  #  人脸旁边的框
24             cv2.putText(frame, "Unknown", (x + 5, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 1)  #  框旁边的标签
25             #  对人脸进行马赛克处理
26             face_img = frame[y:y + h, x:x + w]
27             face_img = cv2.resize(face_img, (w//30, h//30))  #  缩小人脸区域
28             face_img = cv2.resize(face_img, (w, h), interpolation=cv2.INTER_NEAREST)  #  恢复人脸区域
29             #  处理后的图像放回源中
30             frame[y:y+h, x:x+w] = face_img
31         out.write(frame)
32         cv2.imshow("Test", frame)
33         #  按Q停止程序
34         if cv2.waitKey(1) & 0xFF == ord('q'):
35             break
36     else:
37         break
38 
39 #  释放对象
40 out.release()
41 camera.release()
42 cv2.destroyAllWindows()

 

posted @ 2024-09-17 03:10  ZeroZN  阅读(103)  评论(0)    收藏  举报