Problem streaming from IP camera with python openCV - python

Before asking this question I searched the site for a similar problem for the last 2 days but I couldn't find the one specific to me.
I have an IP camera whose IP address, username, etc. I have been given full access to. I can actually open the stream and watch it live by writing the IP into VLC Player >> Open Network Stream >> Network.
But what I want is to be able to watch the same live stream with python. Here's my code:
import urllib.request
import cv2
import numpy
url = 'rtsp://10.10.111.200/profile2/media.smp'
while True:
resp = urllib.request.urlopen(url)
b_array = bytearray(resp.read())
img_np = numpy.array(b_array, dtype=numpy.uint8)
img = cv2.imdecode(img_np, -1)
cv2.imshow('test', img)
if cv2.waitkey(10) == ord('q'):
exit(0)
When I run this code, it gives me the following error:
urllib.error.URLError: .
Then I figured that maybe I should change rtsp to http in url, but when I do, it gives me the following error,
cv2.error: OpenCV(3.4.3)
D:\Build\OpenCV\opencv-3.4.3\modules\imgcodecs\src\loadsave.cpp:737:
error: (-215:Assertion failed) !buf.empty() && buf.isContinuous() in
function 'cv::imdecode_' in the line img = cv2.imdecode(img_np,
-1)
which I think is because there's no data coming from the (very likely wrong since I changed to http) source.
I'm on Windows 10 64bit.

The library you are using to read the data stream does not support the rtsp protocol so it will never work, maybe you can use the following instead:
import cv2
capture_video = cv2.VideoCapture('rtsp://10.10.111.200/profile2/media.smp')
while(True):
ret, img = capture_video.read()
cv2.imshow('Test', img)
if cv2.waitKey(10) == ord('q'):
exit(0)

Related

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.

Port missing in uri warning: Error opening file with Python OpenCV cv2.VideoCapture()

I got a blunder as depicted beneath when I endeavor to stream ipcam
"[tcp # 000000000048c640] Port missing in uri
warning: Error opening file (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:901)"
import numpy as np
import cv2
cv2.__file__
cap = cv2.VideoCapture('http://admin:password#http://192.168.1.***/')
#cap = cv2.VideoCapture('https://www.youtube.com/watch?v=Mus_vwhTCq0')
while(True):
ret, frame = cap.read()
try:
cv2.resizeWindow('Stream IP Camera OpenCV', 120300, 800)
cv2.imshow('Stream IP Camera OpenCV',frame)
except Exception as ex:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
print (message)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
First open VLC player and ensure your ipcam stream link is working. If it works, we can now check if OpenCV can connect to the camera with isOpened() and check the frame retrieval status:
while True:
if cap.isOpened():
ret, frame = cap.read()
if ret:
# Process here
Start with making the url working in VLC. Try this website to get a working link/port/user/password combination that works for you camera.

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.

How to view video stream in OpenCV2 python

I'm starting to play with Opencv. I am using the python bindings for opencv2 on Linux. I wrote a quick test program but it seems to hang indefinitely.
import cv2
weblink = "http://continuous-video-stream-here"
cv2.namedWindow("video")
vid = cv2.VideoCapture(weblink)
key = -1
while (key < 0):
success, img = vid.read()
cv2.imshow("video", img)
But it hangs on this output:
(video:14388): GStreamer-CRITICAL **: gst_caps_unref: assertion `caps != NULL' failed
I have also tried reading from urllib2:
vid = cv2.VideoCapture(urllib2.urlopen(weblink).read())
But that didn't work either.
I am using Opencv 2.4.2, ffmpeg-0.11.2
EDIT: The video feed uses realplayer to display the video over http in the browser.
Code safely and test the return of the method:
vid = cv2.VideoCapture(weblink)
if not vid:
print("!!! Failed VideoCapture: invalid parameter!")
The address you are using is probably not supported by OpenCV.
The same practice should be used whenever a method can fail:
while (key < 0):
success, img = vid.read()
if not img:
print("!!! Failed vid.read()")
break
cv2.imshow("video", img)

Categories

Resources