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.
Related
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()
I am trying to save a background subtracted video in python and the following is my code.
import cv2
import numpy as np
capture = cv2.VideoCapture('MAH00119.mp4')
size = (int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
fourcc = cv2.VideoWriter_fourcc(*'X264')
out = cv2.VideoWriter('output.mp4', -1 , 20.0 , size)
fgbg= cv2.createBackgroundSubtractorMOG2()
while True:
ret, img = capture.read()
if ret==True:
fgmask = fgbg.apply(img)
out.write(fgmask)
cv2.imshow('img',fgmask)
if(cv2.waitKey(27)!=-1):
break
capture.release()
out.release()
cv2.destroyAllWindows()
However, this keeps throwing the following error: "OpenCV: FFMPEG: tag 0xffffffff/'����' is not found (format 'mp4 / MP4 (MPEG-4 Part 14)')'"
I have FFMPEG installed and have added it to the environment variables. My background subtraction code without having to save to a file works fine, so I know there's nothing wrong with openCV installation. I am stuck at this place. I know that my python doesn't seem to recognize FFMPEG but I don't know what else to do apart from adding FFMPEG to the environment variables.
I am using OpenCV version 3.2 on Windows 10 and Python 2.7.
Any help will be much appreciated!
Modified the code a little bit. It works on my PC with OpenCV 3.2 for Python 2.7 on Windows 10 64-bit.
import cv2
import numpy as np
capture = cv2.VideoCapture('./videos/001.mp4')
size = (int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
fourcc = cv2.VideoWriter_fourcc(*'DIVX') # 'x264' doesn't work
out = cv2.VideoWriter('./videos/001_output.mp4',fourcc, 29.0, size, False) # 'False' for 1-ch instead of 3-ch for color
fgbg= cv2.createBackgroundSubtractorMOG2()
while (capture.isOpened()): #while Ture:
ret, img = capture.read()
if ret==True:
fgmask = fgbg.apply(img)
out.write(fgmask)
cv2.imshow('img',fgmask)
#if(cv2.waitKey(27)!=-1): # observed it will close the imshow window immediately
# break # so change to below
if cv2.waitKey(1) & 0xFF == ord('q'):
break
capture.release()
out.release()
cv2.destroyAllWindows()
Check this for the parameters setting on cv2.VideoWriter().
Hope this help.
I am trying to use a MS lifecam with my raspberry-pi-3. It works on the command line, when I type the following command:
$ fswebcam img.jpg
Trying source module v4l2...
/dev/video0 opened.
...
Writing JPEG image to 'img.jpg' # this works fine
Now I want to run the camera through a python code:
import pygame
import pygame.camera
from pygame.locals import *
DEVICE = '/dev/video0'
SIZE = (640, 480) # I also tried with img size (384,288), same error
FILENAME = 'capture.jpg'
pygame.init()
pygame.camera.init()
camera = pygame.camera.Camera(DEVICE, SIZE)
camera.start() # error on executing this line
pygame.image.save(screen, FILENAME)
camera.stop()
The reported error is:
SystemError: ioctl(VIDIOC_S_FMT) failure: no supported formats
I am puzzled here. The camera is supported by rasp-pi, so it looks like my python code has to be updated somewhere. Can you help?
Try use this:
camera = pygame.camera.Camera(pygame.camera.list_cameras()[0])
camera.start()
img = camera.get_image()
pygame.image.save(img, FILENAME)
Had problem and once I stopped a process using the video stream the error was resolved.
details
I had the same problem. And while
/dev/video0
was listed, camera.start() resulted in the same error.
I had ran
sudo motion
earlier. so I verified the service was running, stopped it, then tried pygame. and it worked.
sudo service --status-all
sudo service motion stop
you can also use this :
import cv2
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)
if vc.isOpened():
rval, frame = vc.read()
else:
rval = False
while rval:
cv2.imshow("preview", frame)
rval, frame = vc.read()
key = cv2.waitKey(20)
if key == 27: # exit on ESC
break
cv2.destroyWindow("preview")
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 need hikvision camera which has ip 20.0.0.14 and user name/password is admin/12345 to run by python code
the original camera code is
import cv2.cv as cv
import time
cv.NamedWindow("camera", 1)
capture = cv.CaptureFromCAM(0)
while True:
img = cv.QueryFrame(capture)
cv.ShowImage("camera", img)
if cv.WaitKey(10) == 27:
break
cv.DestroyAllWindows()
i need help please
Here's the solution when using OpenCV3. In your sample code, you are not only not using the OpenCV2 interface, but you are accessing the very old cv (prior to OpenCV 2) interface. So my first suggestion is to get a current install of OpenCV working.
Possible source of rtsp urls for use with hikvision cameras:
https://www.ispyconnect.com/man.aspx?n=Hikvision
import cv2
# Note the following is the typical rtsp url for streaming from an ip cam
# source = "rtsp://user:password#ipaddress:port/<camera specific stuff>"
# Each manufacturer is different. For my alibi cameras, this would be
# a valid url to use with the info you provided.
source = "rtsp://admin:12345#20.0.0.14//Streaming/Channels/2"
cap = cv2.VideoCapture(source)
ok_flag = True
while ok_flag:
(ok_flag, img) = cap.read()
if not ok_flag: break
cv2.imshow("some window", img)
if cv2.waitKey(10) == 27:
break
cv2.destroyAllWindows()
Also note that this code works the same if the source is the path to a valid video file (like an .avi), or for a web camera (in which case you pass the integer number of the webcam, like 0).
Another error in your post is the cv.CaptureFromCAM(0), which would be capturing from the first webcam installed on the computer, not an ip stream.