0

OS : Ubuntu 17.10

I am trying this code to create a dataset on face detection using Python2.7 and Open CV (installed with 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()

But I am getting following error

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
Anushi Maheshwari
  • 439
  • 1
  • 5
  • 9

1 Answers1

1

As the comments correctly mention, one possible cause is that the image is empty (not captured properly). Another possibility is that the image is not a color image.

You can add

cv2.imshow('frame', img)

Before

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

and see what the captured image looks like.

The rest of the code looks fine.

Totoro
  • 3,398
  • 1
  • 24
  • 39
  • 1
    On top of this `ret` also gives a true/false if the frame was read correctly - From [here](https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html)"cap.read() returns a bool (True/False). If frame is read correctly, it will be True. So you can check end of the video by checking this return value." – GPPK Dec 22 '17 at 08:01