关于detectMultiScale返回值为空元组的解决办法

本文介绍了如何通过opencv进行人脸识别,修复了detectMultiScale返回值为元组的问题。作者提供了完整的代码示例,包括设置摄像头、检测人脸、保存样本,并强调了将imshow函数放在循环外的重要性,以便在检测到人脸后正确显示图像。
摘要由CSDN通过智能技术生成

关于detectMultiScale返回值为元组的解决办法

1 网上纠错

完整代码:

import os
import cv2


def face_dateset():

    cam = cv2.VideoCapture(0, cv2.CAP_DSHOW)
    cam.set(3, 640)  # set video width
    cam.set(4, 480)  # set video height
    i = 0
    face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

    # For each person, enter one numeric face id
    face_id = input('\n enter user id end press <return> ==>  ')
    #face_id = 10

    print("\n [INFO] Initializing face capture. Look the camera and wait ...")
    # Initialize individual sampling face count
    count = 0
    files = './dataset/'+str(face_id)
    folder = os.path.exists(files)
    if not folder:
        os.makedirs(files)
        os.chmod(files, 0o777)
    while (True):

        ret, img = cam.read()
        img = cv2.flip(img, 1)  # flip video image vertically
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        faces = face_detector.detectMultiScale(
            gray,

            scaleFactor=1.2,
            minNeighbors=5
            ,
            minSize=(20, 20)
        )


        if len(faces)>0:
            for (x, y, w, h) in faces:
                cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
                count += 1

                # Save the captured image into the datasets folder
                cv2.imwrite(files + '.' + str(count) + ".jpg", gray[y:y + h, x:x + w])

        cv2.imshow('image', img)
        k = cv2.waitKey(100) & 0xff  # Press 'ESC' for exiting video
        if k == 27:
            break
        elif count >= 30:  # Take 30 face sample and stop video
            break

    # Do a bit of cleanup
    print("\n [INFO] Exiting Program and cleanup stuff")
    cam.release()
    cv2.destroyAllWindows()
    return face_id

找了很多网上教程,说什么face_detector = cv2.CascadeClassifier(‘haarcascade_frontalface_default.xml’) 没有正确调用。
最后发现问题是:

cv2.imshow('image', img)

需要把这个写在循环if len(faces)>0:的外面,当启动这个界面后,需要把人脸放到摄像头下面,当检测到人脸后,detectMultiScale的返回元组就不为空咯

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值