1. 程式人生 > >opencv3視訊中檢測主播人臉 python 專案完整原始碼例項

opencv3視訊中檢測主播人臉 python 專案完整原始碼例項

專案完整原始碼下載

包含:

py檔案、測試視訊、xml檔案

效果圖


原始碼

# -*- coding: utf-8 -*-
import cv2
import numpy as np

cv2.namedWindow("test")
# cap = cv2.VideoCapture(0) #載入攝像頭錄製
cap = cv2.VideoCapture("test.mp4") #開啟視訊檔案
success, frame = cap.read()
classifier = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")  # 確保此xml檔案與該py檔案在一個資料夾下,否則將這裡改為絕對路徑

while success:
    success, frame = cap.read()
    size = frame.shape[:2]
    image = np.zeros(size, dtype=np.float16)
    image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.equalizeHist(image, image)
    divisor = 8
    h, w = size
    minSize = (w / divisor, h / divisor)
    faceRects = classifier.detectMultiScale(image, 1.2, 2, cv2.CASCADE_SCALE_IMAGE, minSize)
    if len(faceRects) > 0:
        for faceRect in faceRects:
            x, y, w, h = faceRect
            cv2.circle(frame, (x + w / 4, y + h / 4 + 30), min(w / 8, h / 8), (255, 0, 0))
            cv2.circle(frame, (x + 3 * w / 4, y + h / 4 + 30), min(w / 8, h / 8), (255, 0, 0))
            cv2.rectangle(frame, (x + 3 * w / 8, y + 3 * h / 4), (x + 5 * w / 8, y + 7 * h / 8), (255, 0, 0))
    cv2.imshow("test", frame)
    key = cv2.waitKey(10)
    c = chr(key & 255)
    if c in ['q', 'Q', chr(27)]:
        break
cv2.destroyWindow("test")