Home > Net >  OPENCV error while captureing video from webcam in python
OPENCV error while captureing video from webcam in python

Time:07-03

I've been struggling for a while trying to access the webcam of my laptop (MSI GS65 stealth) through opencv-python. I've tried with python 3.9 and python 3.10, with opencv-python 4.5.3.56 and 4.6.0.66

The minimum amount of code that reproduces the error in my computer.

import cv2

capture = cv2.VideoCapture(0)

while (capture.isOpened()):
    ret, frame = capture.read()
    cv2.imshow('webCam',frame)
    if (cv2.waitKey(1) == ord('s')):
        break

capture.release()
cv2.destroyAllWindows()

Running from the console, using PyCharm with a virtual environment (or the windows Command prompt), the camera activates (a red light turns on besides the camera for a few seconds) but no window is opened and I get this error:

[ WARN:[email protected]] global D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (1752) CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -2147483638
Traceback (most recent call last):
  File "E:\OneDrive - CINVESTAV\Python\RHEED app\video_test.py", line 7, in <module>
    cv2.imshow('webCam',frame)
cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\highgui\src\window.cpp:967: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'

The strange thing is that running from the IPython console through runfile('video_test.py') appears to be working just fine, a window pops with the images captured by the camera, and closes when I click 's'. Also, a few days ago it was working fine, then stopped working. I even made a fresh Windows 10 install, it worked yesterday even from the console, but today it's broken again.

CodePudding user response:

I looks like input is 0x0 picture, thats why i cannot show, if you know your camera resolution try this maybe:

camera=0
cap = cv2.VideoCapture(camera, cv2.CAP_DSHOW)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1050)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)

while cap.isOpened():
    success, image = cap.read()
    if not success:
      print("Ignoring empty camera frame.")
      # If loading a video, use 'break' instead of 'continue'.
      continue
    cv2.imshow('Image', image)
    if cv2.waitKey(5) & 0xFF == ord("q"):
      break
cap.release()

good luck

  • Related