Open CV 在打开网络摄像头流时出现问题

Open CV has problem with opening webcam stream

所以我正在尝试制作简单的计算机视觉应用程序,在实时网络摄像头中在您的脸上显示不同颜色的方块。

问题是当我使用 vscode 终端启动应用程序时,我的笔记本电脑网络摄像头只打开了一段时间然后关闭,但没有应用程序 window 出现?

终端错误:

[ 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

我的应用代码:

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')

尝试添加if successful_frame_read:,检查帧是否读取成功。 if 语句确保只处理可读帧。这是有效的,因为 successful_frame_read 的 return 值是一个布尔值,正如您可能猜到的那样,它告诉您帧是否已成功读取。您可能需要它,因为某些帧可能已损坏并导致此错误。

您的代码应如下所示:

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')

修复属性错误

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

问题可能是安装错误。为确保没有依赖性问题,请安装 Virtualenv(如果您尚未安装)。

Windows:

  1. pip install virtualenv 安装 Virtualenv。

  2. cd C:\Users\asher\Downloads\Work\Work Stuff\Python Stuff\Learning Python AI blah blah\进入项目目录

  3. virtualenv venv 创建一个名为 venv 的虚拟环境

  4. venv\Scripts\activate 激活虚拟环境

  5. 安装 python 包。

要安装 OpenCV,请使用 pip install opencv-python