how to run webcam through python on rpi3 - python

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

Related

ImportError: ERROR: recursion is detected during loading of "cv2" binary extensions. Check OpenCV installation

I as making a screen recorder with python and I was using OpenCV with python but its giving this output that I can't find a working answer ANYWHERE and I really need help. I am have only been using python for about a year. Here is the output it gives me:
['C:\\Users\\Diana\\Desktop\\python\\RecScreen', 'C:\\Users\\Diana\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', 'C:\\Users\\Diana\\AppData\\Local\\Programs\\Python\\Python310\\DLLs', 'C:\\Users\\Diana\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\Users\\Diana\\AppData\\Local\\Programs\\Python\\Python310', 'C:\\Users\\Diana\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages', 'C:\\Users\\Diana\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\pygooglevoice-0.5-py3.10.egg', 'C:\\Users\\Diana\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\win32', 'C:\\Users\\Diana\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\win32\\lib', 'C:\\Users\\Diana\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\Pythonwin']
Traceback (most recent call last):
File "C:\Users\Diana\Desktop\python\RecScreen\RecScreen.py", line 3, in <module>
import cv2
File "C:\Users\Diana\AppData\Local\Programs\Python\Python310\lib\cv2\__init__.py", line 180, in <module>
bootstrap()
File "C:\Users\Diana\AppData\Local\Programs\Python\Python310\lib\cv2\__init__.py", line 75, in bootstrap
raise ImportError('ERROR: recursion is detected during loading of "cv2" binary extensions. Check OpenCV installation.')
ImportError: ERROR: recursion is detected during loading of "cv2" binary extensions. Check OpenCV installation.
My code is:
# importing the required packages
import pyautogui
import cv2
import keyboard
import numpy as np
# Specify resolution
resolution = (1920, 1080)
# Specify video codec
codec = cv2.VideoWriter_fourcc(*"XVID")
# Specify name of Output file
filename = "Recording.avi"
# Specify frames rate. We can choose any
# value and experiment with it
fps = 60.0
# Creating a VideoWriter object
out = cv2.VideoWriter(filename, codec, fps, resolution)
cv2.namedWindow("Recording", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Recording", 480, 270)
while True:
# Take screenshot using PyAutoGUI
img = pyautogui.screenshot()
# Convert the screenshot to a numpy array
frame = np.array(img)
# Convert it from BGR(Blue, Green, Red) to
# RGB(Red, Green, Blue)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Write it to the output file
#out.write(frame)
# Optional: Display the recording screen
cv2.imshow('Live', frame)
# Stop recording when we press 'ctrl+esc'
if keyboard.is_pressed("Ctrl+esc"):
break
# Release the Video writer
out.release()
# Destroy all windows
cv2.destroyAllWindows()
I can't figure out how to fix this error. Any help is appreciated.
ERROR: recursion is detected during loading of "cv2" binary extensions. Check OpenCV installation
it worked for me
put this in your cmd as you run as admin
pip3 install opencv-python --upgrade --force-reinstall

python opencv format not supported

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.

OpenCV: FFMPEG: tag 0xffffffff/'����' is not found (format 'mp4 / MP4 (MPEG-4 Part 14)')'

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.

Is it possible to stream video from https:// (e.g. YouTube) into python with OpenCV?

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

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.

Categories

Resources