0

I have been trying to run a face detection feature from my webcam using code from realpython.com and suggestions I saw on this site.

import cv2
import sys
import os

cascPath = "{base_path}/folder_with_your_xml/haarcascade_frontalface_default.xml".format(
    base_path=os.path.abspath(os.path.dirname(__file__)))

video_capture = cv2.VideoCapture(0)

while True:
    # Capture frame-by-frame
    ret, frame = video_capture.read()

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

    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30),
        flags=cv2.cv.CV_HAAR_SCALE_IMAGE
    )

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    # Display the resulting frame
    cv2.imshow('Video', frame)

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

# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()

This is the error I get when I run the code:

File "videocam.py", line 16, in <module>
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.error: /build/buildd/opencv-2.4.8+dfsg1/modules/imgproc/src/color.cpp:3737: error: (-215) scn == 3 || scn == 4 in function cvtColor

From what I've gathered, it's because frame is not 3-dimensional and a NoneType object. I am only just starting with OpenCV and face recognition, so I'm not entirely sure how to fix this.

Stargazer
  • 1
  • 2
  • Just a suggestion. I've only worked with opencv on c++, but everyone suggests putting an `if` statement to check if the frame is empty or not, before continuing with the frame processing. The reason for that it usually takes a second or so for the webcam to "fire up" as it were and an the start of your program it will return empty frames. – xonxt Mar 31 '16 at 13:23
  • I looked more into it and it turns out that video_capture.isOpened() is False. If I want to open it, I'd have to specify the device name rather than 0 in cv2.VideoCapture(0). Any ideas? – Stargazer Mar 31 '16 at 13:47
  • In `ret, frame = video_capture.read()` -- the `ret` variable is True when a frame was acquired, False otherwise. You should check that before trying to process the frame. Regarding device name, what OS? – Dan Mašek Mar 31 '16 at 18:39

0 Answers0