python-2.7 - 具有OpenCV和Python错误的数据集创建者

标签 python-2.7 opencv face-detection

操作系统:Ubuntu 17.10

我正在尝试这段代码使用Python2.7和Open CV(通过pip安装)在人脸检测上创建数据集

import cv2
import numpy as np
cam = cv2.VideoCapture(0)
detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

Id = raw_input('enter your id')
sampleNum = 0
while True:
    ret, img = cam.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = detector.detectMultiScale(gray, 1.3, 5)
    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)

        #incrementing sample number 
        sampleNum = sampleNum+1
        #saving the captured face in the dataset folder
        cv2.imwrite("dataSet/User."+Id +'.'+ str(sampleNum) + ".jpg", gray[y:y+h,x:x+w])

        cv2.imshow('frame', img)
    #wait for 100 miliseconds 
    if cv2.waitKey(100) & 0xFF == ord('q'):break
        # break if the sample number is morethan 20
    elif sampleNum > 20: break
cam.release()
cv2.destroyAllWindows()

但我收到以下错误
Traceback (most recent call last):
  File "/home/anushi/face/datasetCreator.py", line 10, in <module>
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
error: /io/opencv/modules/imgproc/src/color.cpp:10638: error: (-215) scn == 3 || scn == 4 in function cvtColor

最佳答案

正如评论正确提到的,一个可能的原因是图像为空(无法正确捕获)。另一种可能性是该图像不是彩色图像。

你可以加
cv2.imshow('frame', img)
之前

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

并查看捕获的图像。

其余代码看起来不错。

关于python-2.7 - 具有OpenCV和Python错误的数据集创建者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47927655/

相关文章:

python - 将字典导入python脚本?

python - 仅当第一列中的值相同时才根据第二列对 numpy 数组进行排序

java - Android 中的睁眼和闭眼通过 Android 眼睛检测和 OpenCV 跟踪

python - 霍夫圆中标量变量错误的无效索引

android - 使用面部检测 Android 进行面部交换

android - 使用 Camera X 和 ML Kit 进行人脸检测和跟踪 - Android

python - 逐行比较 2 个文件,忽略换行符差异

python - 比较和交换python中的指令

python - Scrapy Mysql管道如果表没有AUTO_INCRMENT并且没有UNIQUE - 如何分配category_id?

image - 无法编译第一个 opencv 程序, '/usr/bin/ld: cannot find -lcv'