在opencv Python中仅捕获每个人的一张脸部照片并自动保存(无需按键)

发布于 2025-01-14 22:31:14 字数 1134 浏览 1 评论 0原文

我正在尝试使用 Python 中的 opencv 构建带有网络摄像头的人脸检测器。 当检测到人脸时,系统需要能够只捕获每个人的一张脸部照片并自动保存(无需按键),直到该人离开画面并且另一个人进入,再次检测到该人脸并将其保存在一个图像文件。 我正在使用 while 循环来进行实时视频流和连续面部检测。我尝试创建一个内部 while 循环来保存面部照片,但它需要多个帧。

代码:

import numpy as np
import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

cap=cv2.VideoCapture(0)


while True:
    ret, img=cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5, minSize=(150, 150), maxSize=(300, 300))

    for (x,y,w,h) in faces:

        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

        face_img_gray = gray[y:y+h, x:x+w]
        face_img_color = img[y:y+h, x:x+w]
        laplacian_var = cv2.Laplacian(face_img_gray, cv2.CV_64F).var()
        #print(laplacian_var)
        
        if laplacian_var > 140:                          # avoid blur frame capture
            cv2.imwrite('Frame.jpg', face_img_color)
        cv2.imshow('img', img)


    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release() 
cv2.destroyAllWindows()

I'm trying to build a face detector with webcam using opencv in Python.
When human face is detected, the system need to be able to capture only one photo of face per person and save it automatically (without pressing a key), until the person leaves the frame and another person enters and again his face detected and saved in an image file.
I'm using a while loop for the live video stream and the continous face detection. I tried to create an inner while loop for saving the face photo, but it takes multiple frames.

The code:

import numpy as np
import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

cap=cv2.VideoCapture(0)


while True:
    ret, img=cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5, minSize=(150, 150), maxSize=(300, 300))

    for (x,y,w,h) in faces:

        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

        face_img_gray = gray[y:y+h, x:x+w]
        face_img_color = img[y:y+h, x:x+w]
        laplacian_var = cv2.Laplacian(face_img_gray, cv2.CV_64F).var()
        #print(laplacian_var)
        
        if laplacian_var > 140:                          # avoid blur frame capture
            cv2.imwrite('Frame.jpg', face_img_color)
        cv2.imshow('img', img)


    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release() 
cv2.destroyAllWindows()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文