Search code examples
pythonc++opencvcameracomputer-vision

Open CV has problem with opening webcam stream


So I'm trying to make simple computer vision app that displays different colored square around your face in live webcam feed.

The problem is when I start the app using vscode terminal my laptop webcam just turns on for some time and then closes but no app window appears?

The error in the terminal:

[ WARN:0] global C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-ttbyx0jz\opencv\modules\videoio\src\cap_msmf.cpp (1021) CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -2147483638
Traceback (most recent call last):
  File "C:\Users\asher\Downloads\Work\Work Stuff\Python Stuff\Learning Python AI blah blah\Face_Realtime.py", line 23, in <module>     
    grayscaled_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-ttbyx0jz\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

[ WARN:0] global C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-ttbyx0jz\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback

My app's code:

import cv2
from random import randrange

# loading pre-trained data from opencv (haarcascade)
# classifier is just detector

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

webcam = cv2.VideoCapture(0)  # capturing live video

# loop to capture video
while True:

    successful_frame_read, frame = webcam.read()

    # we need to convert to grayscale before detecting faces

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

    # we will detect faces using the line below
    face_coordinates = trained_face_data.detectMultiScale(grayscaled_img)

    for (x, y, w, h) in face_coordinates:  # loop to show all faces
        # create rectangles around face and randrage here creates random colors for rectangles
        cv2.rectangle(frame, (x, y), (x+w, y+h), (randrange(128, 256),randrange(128, 256), randrange(128, 256)), 10)
                  
    # this is app name for window and taking the img
    cv2.imshow('Face Detector', frame)
    key = cv2.waitKey(1)

    if key==81 or key==113:
        break

webcam.release()

print('Trippin through times lol... but code finished')


Solution

  • Try to add if successful_frame_read:, to check whether the frame got successfully read or not. The if statement ensures that only readable frames get processed. This works because the return value of successful_frame_read is a boolean which, as you may guess, tells you if the frame was successfully read. You may need it, because some frames might be corrupt and cause this error.

    Your code should look like this:

    import cv2
    from random import randrange
    
    # loading pre-trained data from opencv (haarcascade)
    # classifier is just detector
    
    trained_face_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    
    webcam = cv2.VideoCapture(0)  # capturing live video
    
    # loop to capture video
    while True:
    
        successful_frame_read, frame = webcam.read()
    
    
        if successful_frame_read: # The newly added if statement
            # we need to convert to grayscale before detecting faces
            grayscaled_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
            # we will detect faces using the line below
            face_coordinates = trained_face_data.detectMultiScale(grayscaled_img)
    
            for (x, y, w, h) in face_coordinates:  # loop to show all faces
                # create rectangles around face and randrage here creates random colors for rectangles
                cv2.rectangle(frame, (x, y), (x+w, y+h), (randrange(128, 256),randrange(128, 256), randrange(128, 256)), 10)
                        
            # this is app name for window and taking the img
            cv2.imshow('Face Detector', frame)
            key = cv2.waitKey(1)
    
            if key==81 or key==113:
                break
    
    webcam.release()
    
    print('Trippin through times lol... but code finished')
    

    Fixing the Attribute Error

    AttributeError: module 'cv2' has no attribute 'CascadeClassifier'
    

    The issue might be a wrong installation. To ensure, that there are no dependency issues, please install Virtualenv if you haven't already.

    Windows:

    1. pip install virtualenv Install Virtualenv.

    2. cd C:\Users\asher\Downloads\Work\Work Stuff\Python Stuff\Learning Python AI blah blah\ Go to the directory of the project

    3. virtualenv venv Create a virtualenv called venv

    4. venv\Scripts\activate Activate the virtualenv

    5. Install the python packages.

    To install OpenCV use pip install opencv-python.