Code:
from imutils.video import VideoStream
import cv2
# Read rtsp stream
rtsp = u"rtsp://admin:admin#10.64.1.31:554/1/h264major"
#vs = VideoStream(src=0).start() # for capturing from webcam
vs = VideoStream(src=rtsp).start()
while True:
frame = vs.read()
# show the output frame
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
# if the `q` key was pressed, break from the loop
if key == ord("q"):
break
# do a bit of cleanup
cv2.destroyAllWindows()
vs.stop()
I have faced the same problem when using opencv's VideoCapture [ cap.isOpened() returns False ]
The standalone executable works fine when capturing from webcam in both cases i.e. cv2.VideoCapture(0) or VideoStream(src=0).start()
The rtsp stream capture works fine in both cases when the script is run in python i.e. without turning it into a standalone executable.
The rtsp stream was tested on VLC player and works fine.
I am using Python 3.6.2 | OpenCV 3.2.0 | Windows
Could this be due to utf-8 etc encoding issues of the RTSP link? Any other alternatives?
Solved: Included opencv_ffmpeg320_64.dll next to my executable.
Included opencv_ffmpeg320_64.dll next to my executable.
Alternatively, copy that dll file to the DLLs folder in python directory
I'm trying to read a video file in opencv (python 2.7), and I just copied the example in the opencv tutorial, but nothing happens:
import numpy as np
import cv2
cap = cv2.VideoCapture('input.mp4')
while(cap.isOpened()):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
The function cap.isOpened always returns FALSE.I have already tried to use absolute path in the argument of VideoCapture, but I still get the same result. What am I getting wrong?
Maybe your OpenCV version is not properly installed. You can check your build infos with print cv2.getBuildInformation() if there is any weird components.
I would suggest to rebuild it, or install it via Anaconda to be sure not to miss any package.
You need to define video location or move the video where python is installed
Keep the full path of the video file.
For example :-
cap = cv2.VideoCapture("D:\\Video Folder\\input.mp4")
I believe this would solve this issue.
i am using opencv2 and python on raspberry pi. and i am new with python and opencv. i tried to read a jpeg image and display image it shows the following error:
/home/pi/opencv-2.4.9/modules/highgui/src/window.cpp:269: \
error: (-215) size.width>0 && size.height>0 in function imshow.
and the code is:
import cv2
# windows to display image
cv2.namedWindow("Image")
# read image
image = cv2.imread('home/pi/bibek/book/test_set/bbb.jpeg')
# show image
cv2.imshow("Image", image)
# exit at closing of window
cv2.waitKey(0)
cv2.destroyAllWindows()
The image fails to load (probably because you forgot the leading / in the path). imread then returns None. Passing None to imshow causes it to try to create a window of size 0x0, which fails.
The poor error handling in cv probably owes to its quite thin wrapper layer on the C++ implementation (where returning NULL on error is a common practice).
it's the path which is causing the problem, i had the same problem but when i gave the full path of the image it was working perfectly.
While using Raspbian in Rpi 3 I had the same problem when trying to read qrcodes. The error is because cv2 was not able to read the image. If using png image install pypng module.
sudo pip install pypng
Use r in the code where you specified the file address.
For Example:
import cv2
img = cv2.imread(r'D:\Study\Git\OpenCV\resources\lena.png')
cv2.imshow('output', img)
cv2.waitKey(0)
r stands for "raw" and will cause backslashes in the string to be interpreted as actual backslashes rather than special characters.
In my case, I had forgotten to change the working directory of my terminal to that of my code+testImage. Hence, it failed to find the image there.
Finally, this is what worked for me:
I saved the image and Python file on Desktop. I changed my cmd directory to it,
cd Desktop
And then checked for my file:
ls
And this was my code that worked:
import cv2
import numpy as np
im = cv2.imread('unnamed.jpg')
#Display the image
cv2.imshow('im',im)
cv2.waitKey(2000) #Milliseconds
I am also getting a similar error, so instead of opening a new question, I thought maybe it would be a good idea to gather it all here since there's already some helpful answers...
My code (textbook code to open a video using OpenCV in Python):
import cv2 as cv
import os
path = 'C:/Users/username/Google Drive/Master/THESIS/uva_nemo_db/videos/'
os.chdir(path)
video_file = '001_deliberate_smile_2.mp4'
cap = cv.VideoCapture(video_file)
if not cap.isOpened():
print("Error opening Video File.")
while True:
# Capture frame-by-frame
ret, frame = cap.read()
cv.imshow('frame',frame)
if cv.waitKey(1) & 0xFF == ord('q'):
break
# if frame is read correctly, ret is True
if not ret:
print("Can't retrieve frame - stream may have ended. Exiting..")
break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
The reason why I am dumbfounded is that I am getting the same error - BUT - the video is actually played... When running the code the Python interpreter opens up an instance of Python running the video. Once the video ends, it breaks out of the loop, closes the video and throws the error:
Traceback (most recent call last):
File "C:/Users/username/Documents/smile-main/video-testing.py", line 24, in
cv.imshow('frame',frame)
cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-wwma2wne\opencv\modules\highgui\src\window.cpp:376: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'
I'd appreciate any input!
**
EDIT: How I fixed my error!
**
I encased my code in a try/except like this:
# Import required libraries
import cv2 as cv
import os
path = 'C:/Users/username/Google Drive/Master/THESIS/uva_nemo_db/videos/'
# test_path = 'C:/Users/username/Downloads'
os.chdir(path)
os.getcwd()
video_file = '001_deliberate_smile_2.mp4'
cap = cv.VideoCapture(video_file) #cap for "Video Capture Object"
if not cap.isOpened():
print("Error opening Video File.")
try:
while True:
# Capture frame-by-frame
ret, frame = cap.read()
cv.imshow('frame',frame)
if cv.waitKey(1) & 0xFF == ord('q'):
break
# if frame is read correctly, ret is True
if not ret:
print("Can't retrieve frame - stream may have ended. Exiting..")
break
except:
print("Video has ended.")
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
I'd still appreciate any input on why this error popped up even though the video played fine, and why the try/except eliminated it.
Thank you!
One of the reasons, this error is caused is when there is no file at the path specified. So, a good practice will be to verify the path like this ( If you are on a linux based machine ):
ls <path-provided-in-imread-function>
You will get an error if the path is incorrect or the file is missing.
While reading the image file, specifying the color option should solve this,
for example:
image=cv2.imread('img.jpg',cv2.IMREAD_COLOR)
adding the cv2.IMREAD_COLOR should solve this
This problem happened to me when i just failed to write the extension of the image.
Please check if you forgot to write the extension or any other part of the full path to the image.
Remember, extension is required whether you are printing image using OpenCV or Mathplotlib.
I solve it by using this code
os.chdir(f"{folder_path}")
It is because the image is not loaded. For me at VScode the relative path was problem but after copying the file path from VSCode itself the problem was solved.
I had the same problem too, on VSCode. Tried running the same code on Notepad++ and it worked. To fix this issue on VSCode, don't forget to open the folder that you're working in on the left pane. This solved my issue.
I'm trying to grab the images from a video file but I can't succeed to open it and I don't know why.
Below is a code sample that print False where I'm expecting to get a True. I don't get why I can't open this simple video file, any lead would be very much appreciated!
I tried with a relative path first then moved to an absolute path to see if anything changed and it's still the same...
video = cv2.VideoCapture()
path = "C:\\Users\\Leo\\Dropbox\\Projet VISORD\\TP3\\video.mpg"
print video.open(path)
The codecs that cv2 supports out of the box are limited. A few of the formats can be found at the link below. I haven't tried them all yet.
http://opencv.willowgarage.com/wiki/documentation/cpp/highgui/VideoWriter
I've had some luck with mp42 codec. Had to convert my camera's mp4 (h264) format to an avi in the correct format.
Using a tool ffmpeg at the moment.
ffmpeg -i input.mp4 -codec:v msmpeg4v2 output.avi
This still leaves something to be desired as it loses resolution, so I am working toward a better solution myself. I only just started at this myself.
The following code works for me:
import cv2
Load the video file:
capture = cv2.VideoCapture('videos/my_video.avi')
Frame is the image you want, flag is success/failure:
flag, frame = capture.read()
Loop through the video's frames:
while True:
flag, frame = capture.read()
if flag == 0:
break
cv2.imshow("Video", frame)
key_pressed = cv2.waitKey(10) #Escape to exit
if key_pressed == 27:
break
However, MPEG is a compressed format, which means that you need the correct codecs to be installed and might have to do some more work to handle the conversion. You can read about the supported different types of video formats at the OpenCV VideoCodec documentation.
(However, if you just want a simple working example, try using a .AVI file and see if it works for you.)
Had a similar problem. Try changing
path = "C:\\Users\\Leo\\Dropbox\\Projet VISORD\\TP3\\video.mpg"
to
path = "C:/Users/Leo/Dropbox/Projet VISORD/TP3/video.mpg"
and see if it works.
I would like to access my webcam from Python.
I tried using the VideoCapture extension (tutorial), but that didn't work very well for me, I had to work around some problems such as it's a bit slow with resolutions >320x230, and sometimes it returns None for no apparent reason.
Is there a better way to access my webcam from Python?
OpenCV has support for getting data from a webcam, and it comes with Python wrappers by default, you also need to install numpy for the OpenCV Python extension (called cv2) to work.
As of 2019, you can install both of these libraries with pip:
pip install numpy
pip install opencv-python
More information on using OpenCV with Python.
An example copied from Displaying webcam feed using opencv and python:
import cv2
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)
if vc.isOpened(): # try to get the first frame
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
vc.release()
cv2.destroyWindow("preview")
gstreamer can handle webcam input. If I remeber well, there are python bindings for it!