Referring to this similar question How to parse mjpeg http stream from ip camera? I was able to read the stream from IP camera, by using requests:
stream = requests.get('http://<user>:<pass>#<addr>:<port>/videostream.cgi', stream=True)
bytez = ''
while True:
bytez += stream.raw.read(16384)
...
and it works beautifully, but would like to get there by using cv2.VideoCapture() instead requests.
I tried variations in a manner of:
cap = cv2.VideoCapture()
cap.open('http://<user>:<pass>#<addr>:<port>/videostream.cgi?.mjpg')
while(True):
ret, frame = cap.read()
...
but wasn't able to get anything, but Exception about empty frame.
How to read IP camera stream with cv2.VideoCapture()?
Pass the location of the camera in your cap = cv2.VideoCapture() line:
cap = cv2.VideoCapture('http://<user>:<pass>#<addr>:<port>/videostream.cgi?.mjpg')
Add C:\OpenCV\3rdparty\ffmpeg\ to the Windows PATH environment variable or copy opencv_ffmpeg.dll from that directory to C:\Python27. This has been answered in this question OpenCV 2.4 VideoCapture not working on Windows
I haven't yet tried accessing an IP camera from VideoCapture, but on your method
cap = cv2.VideoCapture() the video capture is expecting a number representing the camera usually 0.
By leaving it empty, it doesn't access any camera thus the Exception about an empty frame (even though later on you declare cap.open(), openCV already tried to open a camera and determined that is empty)
Related
I'm trying to use python to capture a photo from my ip cameras every 1 minute and save it as a file for later use.
I'm still not good at python and I don't get why some of the times I get the right image and sometimes I get a corrupted gray image.
I'm using hikvision api to get the rtsp stream and while the stream is working sometimes the images are still fully gray.
Here is the code I wrote:
import cv2
import time
count = 0
while True:
for x in range(1, 9):
count = count +1
RTSP_URL = f'rtsp://user:password#ip:port/ISAPI/Streaming/Channels/{x}01'
cap = cv2.VideoCapture(RTSP_URL, cv2.CAP_FFMPEG)
result, image = cap.read()
if result:
cv2.imwrite(f"pictures/{x}{count}.png", image)
time.sleep(60)
I would be happy to hear suggestions to find the best way to do this task.
I'm trying to save video stream, and to timelapse it. I know how to read any video from computer (for example mp4 format) and make a timelapse (I tried, I succeeded). Now I'm trying to do the same with a video stream.
I have link for m3u8 video https://wstream.comanet.cz:1943/live/Vrchlabi-sjezdovka2.stream_360p/playlist.m3u8, I'm reading video like this:
(Initialization:)
import cv2 as cv
url = 'https://wstream.comanet.cz:1943/live/Vrchlabi-sjezdovka2.stream_360p/playlist.m3u8'
fourcc = cv.VideoWriter_fourcc(*'mp4v')
height = video.get(cv.CAP_PROP_FRAME_HEIGHT)
width = video.get(cv.CAP_PROP_FRAME_WIDTH)
outp = cv.VideoWriter(save_path, fourcc, 60,(int(width), int(height)))
video = cv.VideoCapture("url")
dir_stream = "streamframes"
if not os.path.exists(dir_stream):
os.makedirs(dir_stream)
if not video.isOpened():
print("Error opening video file.")
(There is a main part - loop:)
name = 0
while video.isOpened():
ret, frame = video.read()
name += 1
filename = f"{dir_stream}/{name}.jpg"
cv.imwrite(filename, frame)
f = cv.imread(filename)
outp.write(f)
I don't like the way of saving the video... anyway - it's not completely wrong... it kind of works, but after few read frames (sometimes it's 153, 212 etc), ret value is returning False value and code gets into infinite loop. After I stopped the program, my video was saved and I could play it, it was just short (cause it was not recording as long as I wanted, because of infinite loop)...
In the "while" part I also tried...:
while video.isOpened():
ret, frame = video.read()
if ret:
frame_r = cv.imread(frame)
outp.write(frame_r)
... it's much more nice, but cv.imread(frame) was not working so I did it in dirty way u can see above.
My goal is recording online stream with python for some time (e.g. for 5 hours), I don't need record with 30fps, (e.g. 1fps is also fine).
Can anyone help me with this problem? Or do you have some advice? Why ret value returns False after some random time? Do you have other solution? I'll be really thankful for your help, it's for my school project.
We have a videostream from camera with the help of NDI. How can we get it in OpenCV?
import cv2
cap = cv2.VideoCapture("tcp://192.168.1.69")
while cap.isOpened():
_, frame = cap.read()
# frame processing
We have tried the following variation of a string:
tcp://192.168.1.69
tcp://192.168.1.69:8080
http://192.168.1.69
http://192.168.1.69:8080
udp://192.168.1.69:8080
But we get an error every time. What is the correct string to use NDI stream?
A bit late and I'm sure you may have already come across the solution. You also failed to state the platform requirements. So the solution I have is currently Windows only at the moment.
The "NDI Virtual Input" driver allows an NDI network stream to be treated as a Webcam source. Thus you can just set the video capture source to the ID of the device. This requires the driver be installed on the client system
import cv2
cap = cv2.VideoCapture(1) # Could be any number, it's system specific, but it's u=usually 0, 1 etc.
while cap.isOpened():
_, frame = cap.read()
# frame processing
Have a look at PyNDI - I added some examples there to show you how to get NDI into openCV.
The SimpleSourceViewer is command line based, the GUIExample uses TKInter to give you an interface.
I have recently set up a Raspberry Pi camera and am streaming the frames over RTSP. While it may not be completely necessary, here is the command I am using the broadcast the video:
raspivid -o - -t 0 -w 1280 -h 800 |cvlc -vvv stream:///dev/stdin --sout '#rtp{sdp=rtsp://:8554/output.h264}' :demux=h264
This streams the video perfectly.
What I would now like to do is parse this stream with Python and read each frame individually. I would like to do some motion detection for surveillance purposes.
I am completely lost on where to start on this task. Can anyone point me to a good tutorial? If this is not achievable via Python, what tools/languages can I use to accomplish this?
Using the same method listed by "depu" worked perfectly for me.
I just replaced "video file" with "RTSP URL" of actual camera.
Example below worked on AXIS IP Camera.
(This was not working for a while in previous versions of OpenCV)
Works on OpenCV 3.4.1 Windows 10)
import cv2
cap = cv2.VideoCapture("rtsp://root:pass#192.168.0.91:554/axis-media/media.amp")
while(cap.isOpened()):
ret, frame = cap.read()
cv2.imshow('frame', frame)
if cv2.waitKey(20) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Bit of a hacky solution, but you can use the VLC python bindings (you can install it with pip install python-vlc) and play the stream:
import vlc
player=vlc.MediaPlayer('rtsp://:8554/output.h264')
player.play()
Then take a snapshot every second or so:
while 1:
time.sleep(1)
player.video_take_snapshot(0, '.snapshot.tmp.png', 0, 0)
And then you can use SimpleCV or something for processing (just load the image file '.snapshot.tmp.png' into your processing library).
use opencv
video=cv2.VideoCapture("rtsp url")
and then you can capture framse. read openCV documentation visit: https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html
Depending on the stream type, you can probably take a look at this project for some ideas.
https://code.google.com/p/python-mjpeg-over-rtsp-client/
If you want to be mega-pro, you could use something like http://opencv.org/ (Python modules available I believe) for handling the motion detection.
Here is yet one more option.
It's much more complicated than the other answers.
But this way, with just one connection to the camera, you could "fork" the same stream simultaneously to several multiprocesses, to the screen, recast it into multicast, write it to disk, etc.
Of course, just in the case you would need something like that (otherwise you'd prefer the earlier answers)
Let's create two independent python programs:
Server program (rtsp connection, decoding) server.py
Client program (reads frames from shared memory) client.py
Server must be started before the client, i.e.
python3 server.py
And then in another terminal:
python3 client.py
Here is the code:
(1) server.py
import time
from valkka.core import *
# YUV => RGB interpolation to the small size is done each 1000 milliseconds and passed on to the shmem ringbuffer
image_interval=1000
# define rgb image dimensions
width =1920//4
height =1080//4
# posix shared memory: identification tag and size of the ring buffer
shmem_name ="cam_example"
shmem_buffers =10
shmem_filter =RGBShmemFrameFilter(shmem_name, shmem_buffers, width, height)
sws_filter =SwScaleFrameFilter("sws_filter", width, height, shmem_filter)
interval_filter =TimeIntervalFrameFilter("interval_filter", image_interval, sws_filter)
avthread =AVThread("avthread",interval_filter)
av_in_filter =avthread.getFrameFilter()
livethread =LiveThread("livethread")
ctx =LiveConnectionContext(LiveConnectionType_rtsp, "rtsp://user:password#192.168.x.x", 1, av_in_filter)
avthread.startCall()
livethread.startCall()
avthread.decodingOnCall()
livethread.registerStreamCall(ctx)
livethread.playStreamCall(ctx)
# all those threads are written in cpp and they are running in the
# background. Sleep for 20 seconds - or do something else while
# the cpp threads are running and streaming video
time.sleep(20)
# stop threads
livethread.stopCall()
avthread.stopCall()
print("bye")
(2) client.py
import cv2
from valkka.api2 import ShmemRGBClient
width =1920//4
height =1080//4
# This identifies posix shared memory - must be same as in the server side
shmem_name ="cam_example"
# Size of the shmem ringbuffer - must be same as in the server side
shmem_buffers =10
client=ShmemRGBClient(
name =shmem_name,
n_ringbuffer =shmem_buffers,
width =width,
height =height,
mstimeout =1000, # client timeouts if nothing has been received in 1000 milliseconds
verbose =False
)
while True:
index, isize = client.pull()
if (index==None):
print("timeout")
else:
data =client.shmem_list[index][0:isize]
img =data.reshape((height,width,3))
img =cv2.GaussianBlur(img, (21, 21), 0)
cv2.imshow("valkka_opencv_demo",img)
cv2.waitKey(1)
If you got interested, check out some more in https://elsampsa.github.io/valkka-examples/
Hi reading frames from video can be achieved using python and OpenCV . Below is the sample code. Works fine with python and opencv2 version.
import cv2
import os
#Below code will capture the video frames and will sve it a folder (in current working directory)
dirname = 'myfolder'
#video path
cap = cv2.VideoCapture("your rtsp url")
count = 0
while(cap.isOpened()):
ret, frame = cap.read()
if not ret:
break
else:
cv2.imshow('frame', frame)
#The received "frame" will be saved. Or you can manipulate "frame" as per your needs.
name = "rec_frame"+str(count)+".jpg"
cv2.imwrite(os.path.join(dirname,name), frame)
count += 1
if cv2.waitKey(20) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Use in this
cv2.VideoCapture("rtsp://username:password#IPAddress:PortNO(rest of the link after the IPAdress)").
In my project i want to save streaming video.
import cv2;
if __name__ == "__main__":
camera = cv2.VideoCapture(0);
while True:
f,img = camera.read();
cv2.imshow("webcam",img);
if (cv2.waitKey (5) != -1):
break;
`
using above code it is possible to stream video from the web cam. How to write this streaming video to a file?
You can simply save the grabbed frames into images:
camera = cv2.VideoCapture(0)
i = 0
while True:
f,img = camera.read()
cv2.imshow("webcam",img)
if (cv2.waitKey(5) != -1):
break
cv2.imwrite('{0:05d}.jpg'.format(i),img)
i += 1
or to a video like this:
camera = cv2.VideoCapture(0)
video = cv2.VideoWriter('video.avi', -1, 25, (640, 480));
while True:
f,img = camera.read()
video.write(img)
cv2.imshow("webcam",img)
if (cv2.waitKey(5) != -1):
break
video.release()
When creating VideoWriter object, you need to provide several parameters that you can extract from the input stream. A tutorial can be found here.
In ubuntu create video from given pictures using following code
os.system('ffmpeg -f image2 -r 8 -i %05d.bmp -vcodec mpeg4 -y movie3.mp4')
where name of picture is 00000.bmp,00001.bmp,00002.bmp etc..
If you really want to use the codec provided for your pc to compress the frames.
You should set the 2nd parameter of cv2.VideoWriter([filename, fourcc, fps, frameSize[, isColor]]) with the flag value = -1. This will allow you to see a list of codec compress utilized in your pc.
In my case, the codec provided by Intel is named IYUV or I420. I don't know for another manufacturers. fourcc webpage.
Set this information as follow
fourcc = cv2.cv.CV_FOURCC('I','Y','U','V')
# or
fourcc = cv2.cv.CV_FOURCC('I','4','2','0')
# settting all the information
out = cv2.VideoWriter('output1.avi',fourcc, 20, (640,480))
Remember two small parameters which gave me a big headache:
Don't forget the cv2.cv prefix
Introduce the correct frame Size
For everything else, you can use the code provided by Ekalic