How to view video stream in OpenCV2 python - 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)

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.

Problem streaming from IP camera with python openCV

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)

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.

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