简体   繁体   中英

Get Live Stream from a Camera connected via usb using python

I want to grab live images from a camera which is connected via USB with my computer.

I am using an Industrial Camera with usb port.

At device manager the camera is shown with its name and id so I think it is connected to PC.

I ran a 'findcam' program but it is not showing any existance of camera

import cv2

cap = cv2.VideoCapture(0)


while True:
    ret, frame = cap.read()
    cv2.imshow('Live Video', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

The given code which i tried is running for webcam on my laptop but when the same code i run on my PC with an external camera.

it constantly showing an error.

The Error:

Traceback (most recent call last):
  
File "C:/Users/Admin/PycharmProjects/industrialcamera/ICvideocapture.py", line 11, in <module>

cv2.imshow('Live Video', frame)

cv2.error: OpenCV(4.1.0) C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:352: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'

I tried changing Index -1, 0, 1 but the error is constant

please help to find, weather it is my PC problem or camera problem or is their is any other way to stream(in python)

Thank You

I started your code on my PC and it works fine. Try to set the camera resolution manually, if you have an error with size.width and size.height , something like this:

cap = cv2.VideoCapture(0)
cap.set(3,1280)
cap.set(4,920)

You may have installed the wrong version of OpenCV which doesn't support video. Uninstall everything of opencv and then run:

pip install opencv-python

(Source: cv2.VideoCapture.open() always returns FALSE )

尝试通过 pip 安装opencv-contrib-pythonpip install opencv-contrib-python或者尝试升级它的版本: pip install opencv-python --upgrade

you can debugg by checking the ret value:

import cv2
cap = cv2.VideoCapture(0)
counter = 0
while True:.       
    ret, frame = cap.read()
    if ret :
        cv2.imshow('Live Video', frame)
        print(f" frame {counter} : ok ")
    if not ret :
        print(f" frame {counter} : ...")
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM