天天看點

python opencv3 攝像頭人臉檢測

git:https://github.com/linyi0604/Computer-Vision

1 # coding:utf8
 2 
 3 import cv2
 4 
 5 
 6 def detect():
 7     # 建立人臉檢測的對象
 8     face_cascade = cv2.CascadeClassifier("../data/haarcascade_frontalface_default.xml")
 9     # 建立眼睛檢測的對象
10     eye_cascade = cv2.CascadeClassifier("../data/haarcascade_eye.xml")
11     # 連接配接攝像頭的對象 0表示攝像頭的編号
12     camera = cv2.VideoCapture(0)
13 
14     while True:
15         # 讀取目前幀
16         ret, frame = camera.read()
17         # 轉為灰階圖像
18         gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
19         # 檢測人臉 傳回清單 每個元素都是(x, y, w, h)表示矩形的左上角和寬高
20         faces = face_cascade.detectMultiScale(gray, 1.3, 5)
21         # 畫出人臉的矩形
22         for (x, y, w, h) in faces:
23             # 畫矩形 在frame圖檔上畫, 傳入左上角和右下角坐标 矩形顔色 和線條寬度
24             img = cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
25             # 把臉單獨拿出來
26             roi_gray = gray[y: y+h, x: x+w]
27             # 在臉上檢測眼睛   (40, 40)是設定最小尺寸,再小的部分會不檢測
28             eyes = eye_cascade.detectMultiScale(roi_gray, 1.03, 5, 0, (40, 40))
29             # 把眼睛畫出來
30             for(ex, ey, ew, eh) in eyes:
31                 cv2.rectangle(img, (x+ex, y+ey), (x+ex+ew, y+ey+eh), (0, 255, 0), 2)
32 
33         cv2.imshow("camera", frame)
34         if cv2.waitKey(5) & 0xff == ord("q"):
35             break
36 
37     camera.release()
38     cv2.destroyAllWindows()
39 
40 
41 if __name__ == '__main__':
42     detect()      
python opencv3 攝像頭人臉檢測

我很醜哦 不要笑啊

轉載于:https://www.cnblogs.com/Lin-Yi/p/9417748.html