2016年3月19日 星期六

OpenCV3: 人臉偵測


今日嘗試了人臉偵測。跟往常的影像分析一樣,都是先把相片轉換為灰階影像後再進行處理。因為 OpenCV 的緣故,代碼非常精簡。檢測人臉特徵的設定都在 XML 檔內。
##------------------------------------------------------------------------------
##  Face and eyes detection with OpenCV 3.1
##------------------------------------------------------------------------------
##  Language: Python 3.5
##  Platform: Mac OS X
##  Written by Pacess HO
##  Copyright 2016 Pacess Studio.  All rights reserved
##------------------------------------------------------------------------------

##  Import packages
import numpy as np
import cv2

##  Load image
image = cv2.imread("sita_chan_01.jpg")
 
##  Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

##  Display original image in a window
cv2.imshow("Original", image)

##------------------------------------------------------------------------------
##  Face and eyes detection
faceCascade = cv2.CascadeClassifier("/Users/pacess/opencv/data/haarcascades/haarcascade_frontalface_default.xml")
eyeCascade = cv2.CascadeClassifier("/Users/pacess/opencv/data/haarcascades/haarcascade_eye.xml")
faceArray = faceCascade.detectMultiScale(gray, 1.1, 5)
for (x, y, w, h) in faceArray:
    cv2.rectangle(image, (x, y), (x+w, y+h), (182, 89, 255), 2)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = image[y:y+h, x:x+w]

    eyeArray = eyeCascade.detectMultiScale(roi_gray)
    for (ex, ey, ew, eh) in eyeArray:
        radiusW = int(ew/2)
        radiusH = int(eh/2)
        radius = radiusW if radiusW < radiusH else radiusH
        cv2.circle(roi_color, (ex+radiusW, ey+radiusH), radius, (0, 192, 255), 2)

##------------------------------------------------------------------------------
##  Display output image
cv2.imshow("Output", image)

##  Wait any key pressed
cv2.waitKey(0)
cv2.destroyAllWindows()

沒有留言: