注意 opencv 的座標軸,x 軸向右,和 width 對應,y 軸向下,和 height 對應;
1. MOG2 與 KNN
MOG:Mixture of Gaussian
import cv2cap = cv2.VideoCapture('./data/video/768x576.avi')knn_sub = cv2.createBackgroundSubtractorKNN()mog2_sub = cv2.createBackgroundSubtractorMOG2()while True: ret, frame = cap.read() if not ret: break mog_sub_mask = mog2_sub.apply(frame) knn_sub_mask = knn_sub.apply(frame) cv2.imshow('original', frame) cv2.imshow('MOG2', mog_sub_mask) cv2.imshow('KNN', knn_sub_mask) key = cv2.waitKey(30) & 0xff if key == 27 or key == ord('q'): breakcap.release()cv2.destroyAllWindows()
2. 識別與檢測
Haar Cascade
import cv2import numpy as np# haar 級聯分類器,opencv 源檔案中data檔案夾下會有# https://github.com/opencv/opencv/tree/master/data/haarcascadesface_cascade = cv2.CascadeClassifier( './data/classifiers/haarcascade_frontalface_default.xml')eye_cascade = cv2.CascadeClassifier('./data/classifiers/haarcascade_eye.xml')cap = cv2.VideoCapture(0)while True: ret, img = cap.read() if not ret: break 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), color=(255, 0, 0), thickness=2) roi_gray = gray[y:y+h, x:x+w] roi_color = img[y:y+h, x:x+w] eyes = eye_cascade.detectMultiScale(roi_gray) try: ex, ey, ew, eh = eyes[0] cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), color=(0, 255, 0), thickness=2) ex1, ey1, ew1, eh1 = eyes[1] cv2.rectangle(roi_color, (ex1, ey1), (ex1+ew1, ey1+eh1), color=(0, 255, 0), thickness=2) except IndexError: print('') cv2.imshow('me', img) key = cv2.waitKey(30) if key == 27 or key == ord('q'): breakcap.release()cv2.destroyAllWindows()