Python opencv2 其分类器

Python opencv2 haar classifier

我正在尝试结合两个脚本来获取面部识别,以便与来自我的笔记本电脑网络摄像头的实时视频馈送一起使用。我有一个可用的 opencv2 脚本,可与我的网络摄像头配合使用以查看实时镜头,另一个是面部识别脚本,在 jpeg 静止图像上带有 haar 分类器。我正在使用 Python 3.6 IDE,打开 cv2。下面的脚本可用于通过我的笔记本电脑网络摄像头查看实时提要。

import numpy as np
import cv2, time

video = cv2.VideoCapture(0)  
a = 0

while True:

    a = a + 1    
    check, frame = video.read()

    print(check)
    print(frame)

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow("Capturing", gray)
    cv2.waitKey(1)

    key = cv2.waitKey(1)    
    if key == ord('q'):
        break

print(a)

video.release()

我得到了这个脚本,它在一张脸上画了一个框,用于 haar 分类器,它在静止的 .jpeg 图像上有一个函数。我将如何结合这两个脚本并使用 haar 分类器对实时视频源进行面部识别? haar 分类器 XML 和 jpeg 是我本地 PC 目录中的文件。

import cv2
import matplotlib.pyplot as plt
import time 



def detect_faces(f_cascade, colored_img, scaleFactor = 1.1):
    img_copy = colored_img.copy()          
    gray = cv2.cvtColor(img_copy, cv2.COLOR_BGR2GRAY)           
    faces = f_cascade.detectMultiScale(gray, scaleFactor=scaleFactor, minNeighbors=5);           
    for (x, y, w, h) in faces:
        cv2.rectangle(img_copy, (x, y), (x+w, y+h), (0, 255, 0), 2)               
    return img_copy



test2 = cv2.imread('C:/Python/opencv/sAndb.jpg')
haar_face_cascade = cv2.CascadeClassifier('C:/Python/opencv/opencv-master/opencv-master/data/haarcascades/haarcascade_frontalface_alt.xml')
faces_detected_img = detect_faces(haar_face_cascade, test2)
cv2.imshow('Faces', faces_detected_img)

试试这个:

import numpy as np
import cv2, time
import matplotlib.pyplot as plt

haar_face_cascade = cv2.CascadeClassifier('C:/Python/opencv/opencv-master/opencv-master/data/haarcascades/haarcascade_frontalface_alt.xml')
video = cv2.VideoCapture(0)  
a = 0

while True:

    a = a + 1    
    check, frame = video.read()

    print(check)
    print(frame)

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = f_cascade.detectMultiScale(gray, scaleFactor=scaleFactor, minNeighbors=5);
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2)


    cv2.imshow("Face Detector", frame)
    cv2.waitKey(1)

    key = cv2.waitKey(1)    
    if key == ord('q'):
        break

print(a)

video.release()