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)
Try to install opencv-contrib-python via pip: pip install opencv-contrib-python or maybe try to upgrade the version of it : 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()
Related
A simple program to show the feed from my webcam is running fine. I'm getting the error only when I try to run cv2.BackgroundSubtractorKNN() within the loop.
I have applied the following fix:
Uninstalled the latest version of OpenCV (which I was using) and installed an older version 4.5.4. But the error still persists.
Here's my code and the corresponding messages in the terminal.
import cv2
cap = cv2.VideoCapture(0)
mog = cv2.BackgroundSubtractorKNN()
while(True):
ret, frame = cap.read()
fgmask = mog.apply(frame)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Message in terminal
PS D:\Python ground up\Open_CV> python -u "d:\Python ground up\Open_CV\backgroundsub.py"
Traceback (most recent call last):
File "d:\Python ground up\Open_CV\backgroundsub.py", line 7, in <module>
fgmask = mog.apply(frame)
cv2.error: Unknown C++ exception from OpenCV code
I think it's createBackgroundSubtractorKNN not BackgroundSubtractorKNN
import cv2
image_counter = 0
video = cv2.VideoCapture(0)
while True:
check, frame = video.read()
gray_f = cv2.flip(frame, 1)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
gray_flip = cv2.flip(frame, 1)
cv2.imshow("kara", gray_flip)
key = cv2.waitKey(1)
if key == ord('q'):
break
video.release()
cv2.destroyAllWindows()
I have written this code for using my camera using OpenCV python 3 it worked earlier but after I upgraded my python it gives following error:-
[ WARN:0] global
C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-j8nxabm_\opencv\modules\videoio\src\cap_msmf.cpp
(682) CvCapture_MSMF::initStream Failed to set mediaType (stream 0,
(640x480 # 30) MFVideoFormat_RGB24(unsupported media type)
Python version:3.8.5 x64
OpenCV version: 4.4.0.42
The following code resolved this issue for me:
video = cv2.VideoCapture(0,cv2.CAP_DSHOW)
It's a reported issue, See the details: https://github.com/opencv/opencv/issues/16711
i had this problem with java and Open Cv the problem is because the format of the video file (video.mp4) has sound and this is the reason why appear the trouble "MFVideoFormat_RGB32(unsupported media type)" the solution i found was use ffmpeg, I remove the audio of the video file with the next comand in cmd:
ffmpeg -i video.mp4 -an -c copy no_sound.mp4
Then I use the no_sound.mp4 in the next code:
VideoCapture cap = new VideoCapture();
cap.open("no_sound.mp4");
This worked for me.
For some reason, I cannot read camera video data using OpenCV and Python 3.
Here is the code I am using:
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while(1):
_, frame = cap.read()
cv2.imshow('frame',frame)
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
This code returns the following error:
Traceback (most recent call last):
File "C:\Path\To\File\VideoTest.py", line 10, in <module>
cv2.imshow('frame',frame)
cv2.error: D:\Build\OpenCV\opencv-3.3.1\modules\highgui\src\window.cpp:339: error: (-215) size.width>0 && size.height>0 in function cv::imshow
The computer is running Windows Server 2012 R2 and has one USB webcam permanently in use in addition to the new one I am trying to read data from. I have tried changing the line cap = cv2.VideoCapture(0) to cap = cv2.VideoCapture(1) and had an identical error.
I tried replicating the error on my laptop using the same code and USB webcam, but it worked perfectly and I was able to stream the video.
**EDIT**
To debug, I ran the following program line-by-line in the Python shell.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
print(cap.read())
cap = cv2.VideoCapture(1)
print(cap.read())
The code outputted (False, None) twice.
This link has a tidy little example of how to use python's OpenCV library, cv2 to stream data from a camera into your python shell. I'm looking to do some experiments and would like to use the following YouTube video feed: https://www.youtube.com/watch?v=oCUqsPLvYBQ.
I've tried adapting the example as follows:
import numpy as np
import cv2
cap = cv2.VideoCapture('https://www.youtube.com/watch?v=oCUqsPLvYBQ')
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Display the resulting frame
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
Which produces the error:
WARNING: Couldn't read movie file https://www.youtube.com/watch?v=oCUqsPLvYBQ
OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow, file /tmp/opencv20160107-29960-t5glvv/opencv-2.4.12/modules/highgui/src/window.cpp, line 261
Is there a simple fix that would allow me to stream this video feed into my python shell via cv2? Not absolutely committed to cv2, either, if there are other libraries out there that will accomplish the same purpose.
you need to have 2 things installed
pafy (pip install pafy)
youtube_dl (sudo pip install --upgrade youtube_dl)
after installing these two packages you can use the youtube url to play the streaming videos from youtube.
Please refer the code below
url = 'https://youtu.be/W1yKqFZ34y4'
vPafy = pafy.new(url)
play = vPafy.getbest(preftype="webm")
#start the video
cap = cv2.VideoCapture(play.url)
while (True):
ret,frame = cap.read()
"""
your code here
"""
cv2.imshow('frame',frame)
if cv2.waitKey(20) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
it is possible with pafy (https://pypi.python.org/pypi/pafy)
import cv2, pafy
url = "https://www.youtube.com/watch?v=aKX8uaoy9c8"
videoPafy = pafy.new(url)
best = videoPafy.getbest(preftype="webm")
video=cv2.VideoCapture(best.url)
#incBrain's suggestion to download the youtube video to local mp4 was the way to go here. Here were the steps that I used to set up a remote server environment on EC2, with output piped into my local computer via X11 forwarding:
ssh -X -i "<ssh_key.pem>" ubuntu#<IP-address>.compute-1.amazonaws.com (Note the -X option is an important addition here. It's what we use to pass output from the EC-2 server to a local X11 client)
sudo pip install --upgrade youtube_dl (I know, sudo pip is bad. I blame the site instructions)
Download youtube video to local file: youtube-dl https://www.youtube.com/watch?v=VUjF1fRw9sA -o motocross.mp4
python demo_cv.py
X11 forwarding can be tricky. If you run into any hangups there this post might be helpful to you also.
I've added Youtube URL source support in my VidGear Python Library that automatically pipelines YouTube Video into OpenCV by providing its URL only. Here is a complete python example:
For VidGear v0.1.9 below:
# import libraries
from vidgear.gears import CamGear
import cv2
stream = CamGear(source='https://youtu.be/dQw4w9WgXcQ', y_tube = True, logging=True).start() # YouTube Video URL as input
# infinite loop
while True:
frame = stream.read()
# read frames
# check if frame is None
if frame is None:
#if True break the infinite loop
break
# do something with frame here
cv2.imshow("Output Frame", frame)
# Show output window
key = cv2.waitKey(1) & 0xFF
# check for 'q' key-press
if key == ord("q"):
#if 'q' key-pressed break out
break
cv2.destroyAllWindows()
# close output window
# safely close video stream.
stream.stop()
For VidGear v0.2.0 and above: (y_tube changed to stream_mode)
# import libraries
from vidgear.gears import CamGear
import cv2
stream = CamGear(source='https://youtu.be/dQw4w9WgXcQ', stream_mode = True, logging=True).start() # YouTube Video URL as input
# infinite loop
while True:
frame = stream.read()
# read frames
# check if frame is None
if frame is None:
#if True break the infinite loop
break
# do something with frame here
cv2.imshow("Output Frame", frame)
# Show output window
key = cv2.waitKey(1) & 0xFF
# check for 'q' key-press
if key == ord("q"):
#if 'q' key-pressed break out
break
cv2.destroyAllWindows()
# close output window
# safely close video stream.
stream.stop()
Code Source
#pip install pafy
#sudo pip install --upgrade youtube_dl
import cv2, pafy
url = "https://www.youtube.com/watch?v=qvyTx01ZcQQ"
video = pafy.new(url)
best = video.getbest(preftype="mp4")
capture = cv2.VideoCapture(best.url)
while True:
check, frame = capture.read()
print (check, frame)
cv2.imshow('frame',frame)
cv2.waitKey(10)
capture.release()
cv2.destroyAllWindows()
Try this, works well on live streams too
I'm using ubuntu 13.10 along with opencv 2.4.9 with python 2.7.
I have written the following code but it seems to fails on runtime.
import cv2
c1=cv2.VideoCapture(2) #camera id
c2=cv2.VideoCapture(1) #camera id
while(True):
ret,frame = c1.read()
ret,frame2 = c2.read()
frame = cv2.cvtColor(frame,0)
frame2 = cv2.cvtColor(frame2,0)
cv2.imshow('frame',frame)
cv2.imshow('frame2',frame2)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
c1.release()
c2.release()
cv2.destroyAllWindows()
But on running this in Ubuntu i get the following error :
VIDIOC_QUERYMENU: Invalid argument
libv4l2: error turning on stream: Invalid argument
VIDIOC_STREAMON: Invalid argument
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file
/build/buildd/opencv-2.4.5+dfsg/modules/imgproc/src/color.cpp, line 3358
Traceback (most recent call last):
File "/home/bini/KV/IP_Proj/webcam basics opencv.py", line 8, in <module>
frame2 = cv2.cvtColor(frame2,0)
cv2.error: /build/buildd/opencv-2.4.5+dfsg/modules/imgproc/src/color.cpp:3358: error:
(-215) scn == 3 || scn == 4 in function cvtColor
The same code used to work fine on windows.
Can someone help me please as to why is this occuring..??? i have on idea.
Thanks in advance
For linux,if you're using 1 camera , at first you must change your camera id to 0 , but it seems that you want use 2 camera , this is because the resolution, framerate and protocol used by your cameras overloads the USB connection so read this link! also this is a base code for connect and use linux webcam:
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
#set the width and height, and UNSUCCESSFULLY set the exposure time
cap.set(3,1080)
cap.set(4,1024)
cap.set(15, 0.1)
while True:
ret, img = cap.read()
cv2.imshow("input",img)
key = cv2.waitKey(10)
if key == 27:
break
cv2.destroyAllWindows()
cv2.VideoCapture(0).release()
One (or both) of your cameras isn't initializing correctly. I just ran your code on my machine (Ubuntu 14.04) and both frames come up showing live views from my two connected cameras. Can you view both cameras in cheese or guvcview?
I do get a bunch of these messages:
VIDIOC_QUERYMENU: Invalid argument
errors but neither of these:
libv4l2: error turning on stream: Invalid argument
VIDIOC_STREAMON: Invalid argument