Python-opencv人臉馬賽克處理+錄製影片到本地

ZeroZN發表於2024-09-17
 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()

相關文章