參考 OpenCV 自帶範例,用三十行左右的 Python 就能做出人臉檢測。不得不說 Python 的優勢太明顯——幾乎把所有複雜細節都屏蔽掉了。雖然執行效率不如 C/C++,但因為 OpenCV 底層是以 C 撰寫,實際差距並沒有想像中那麼大。
本範例直接使用 OpenCV 內建的 Haar 級聯分類器。
#!/usr/bin/env python
import cv2
def faceDetect(img, face_cascade):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
return img
def main():
cap = cv2.VideoCapture(1)
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
if ret == True:
frame = faceDetect(frame, face_cascade)
# Display the resulting frame
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
main()1. 用 cv2.VideoCapture 取得攝影機。
2. 載入 haarcascade_frontalface_default.xml 這個預訓練模型。
3. 每一幀先轉成灰階,再交給 detectMultiScale 偵測,後兩個參數分別是縮放比例與最小鄰域數。
4. 把回傳的邊界框用 rectangle 畫出來,顯示後按 q 離開。
《Python核心編程 第二版》(Wesley J. Chun)[高清PDF中文版] https://www.linuxidc.com/Linux/2013-06/85425.htm
零基礎如何入門Python https://www.linuxidc.com/Linux/2016-10/136485.htm
Ubuntu 14.04安裝Python 3.3.5 https://www.linuxidc.com/Linux/2014-05/101481.htm
CentOS 6.5 腳本自動化裝 Python2.6升級2.7 https://www.linuxidc.com/Linux/2017-02/140406.htm
CentOS上源碼安裝Python3.4 https://www.linuxidc.com/Linux/2015-01/111870.htm
Ubuntu 14.04下Python數據處理環境搭建 https://www.linuxidc.com/Linux/2017-01/139568.htm
Python Paramiko模塊安裝和使用 https://www.linuxidc.com/Linux/2017-01/139973.htm
《Python開發技術詳解》(周偉,宗傑)[高清PDF掃描版+隨書視頻+代碼] https://www.linuxidc.com/Linux/2013-11/92693.htm
在CentOS 6.5上安裝Python2.7 https://www.linuxidc.com/Linux/2016-10/136206.htm
Ubuntu 14.04 LTS下編譯安裝Open Babel和Python語言綁定 https://www.linuxidc.com/Linux/2017-01/139569.htm
Python常見數據結構整理 https://www.linuxidc.com/Linux/2017-02/140613.htm