Problem with Opencv and Python - python

I'm new to python and Opencv and I tried to put in the following code to save an image to my computer from my webcam:
import cv
if __name__=='__main__':
pCapturedImage = cv.CaptureFromCAM(1)
rospy.sleep(0.5)
pSaveImg=cv.QueryFrame(pCapturedImage)
cv.SaveImage("test.jpg", pSaveImg)
But when I try to open it,
I find that the jpeg is empty.
Could someone please help?
Also, I tried a program to show what my webcam is seeing:
import cv
if __name__=='__main__':
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.DestroyedWindow("camera")
But when I run it, I get an application that just shows me a gray screen.
Could someone help with this too?
Thanks.

Have you tried the demo programs? They show how to use the webcam among many other things.
For the first problem, I am not familiar with using cameras in opencv, but I got it to work by opening the capture (capture.open(device_id) in the code below)
Here is a working python sample (I use the newer c++ interface: imread, imwrite, VideoCapture, etc... which you can find in the OpenCV docs listed as "cv2" when it is available for python.):
import cv2
capture = cv2.VideoCapture() # this is the newer c++ interface
capture.open(0) # Use your device id; I think this is what you are missing.
image = capture.read()[1]
cv2.imwrite("test.jpg", image)
I got your second sample also working just by using open on the capture object:
import cv2
cv2.namedWindow("camera", 1) # this is where you will put the video images
capture = cv2.VideoCapture()
capture.open(0) # again, use your own device id
while True:
img = capture.read()[1]
cv2.imshow("camera", img)
if cv2.waitKey(10) == 27: # waiting for the esc key
break
cv2.destroyWindow("camera")

Related

Receive NDI video stream in open cv

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.

Sending OpenCV output to VLC stream

This has been keeping me busy for a good part of the afternoon and I haven't been able to get it to work but I feel like I'm really close.
I've got openCV set up which takes the videofeed from a webcam. To be able to access this video feed (with openCV overlay) I want to pipe the output of the openCV python script to a VLC stream. I managed to get the stream up and running and can connect to it. VLC resizes to the correct aspect ratio and resolution so it gets some correct data but the image I get is just Jitter;
python opencv.py | cvlc --demux=rawvideo --rawvid-fps=30 --rawvid-width=320 --rawvid-height=240 --rawvid-chroma=RV24 - --sout "#transcode{vcodec=h264,vb=200,fps=30,width=320,height=240}:std{access=http{mime=video/x-flv},mux=ffmpeg{mux=flv},dst=:8081/stream.flv}" &
The output of the script is a constant video feed sent to stdout as follows
from imutils.video import WebcamVideoStream
vs = WebcamVideoStream(src=0)
while True:
frame = vs.read()
sys.stdout.write(frame.tostring())
Above example is a dumbed down version of the script I'm using; Also as seen I'm making use of the imutils library; https://github.com/jrosebr1/imutils
If anyone could give me a nudge in the right direction I would appreciate it greatly. My guess is the stdout.write(frame.tostring()) is not what vlc expects but I haven't been able to figure it out myself.
The following works for me under Python 3
import numpy as np
import sys
import cv2
cap = cv2.VideoCapture(0)
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
sys.stdout.buffer.write(frame.tobytes())
else:
break
cap.release()
And the command line (my webcam has a different resolution, and I only display the result, but you did not have problems with that)
python opencv.py | vlc --demux=rawvideo --rawvid-fps=25 --rawvid-width=640 --rawvid-height=480 --rawvid-chroma=RV24 - --sout "#display"
Of course this requires a conversion from BGR to RGB as the former is default in OpenCV.
This worked for me, though I am sending to RTSP stream and not using imutils library:
import numpy as np
import sys
import cv2
input_rtsp = "rtsp://10.10.10.9:8080"
cap = cv2.VideoCapture(input_rtsp)
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
sys.stdout.write(frame.tostring())
else:
break
cap.release()
Then in command line:
python opencv.py | cvlc --demux=rawvideo --rawvid-fps=25 --rawvid-width=1280 --rawvid-height=720 --rawvid-chroma=RV24 - --sout "#transcode{vcodec=h264,vb=200,fps=25,width=1280,height=720}:rtp{dst=10.10.10.10,port=8081,sdp=rtsp://10.10.10.10:8081/test.sdp}"
Note that you do not need to convert opencv BGR to RGB.

Assertion failure : size.width>0 && size.height>0 in function imshow

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.

Can't open video with opencv2

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.

Problems using webcam in python + openCV

I am using the following code to access my webcam using openCV + python...
import cv
cv.NamedWindow('webcam_feed', cv.CV_WINDOW_AUTOSIZE)
cam = cv.CaptureFromCAM(-1)
I am then getting the following error in the console...
VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument
I was originally using,
cv.CaptureFromCAM(0)
to access the same and had the same issue and used -1 because it is suppose to pick up any webcam.
I also tested to see if Ubuntu recognizes the webcam and it does. I am using v4l2 for the webcam.
{EDIT}
I am using the following code to display a video feed, it seems to only be showing just one image the web cam captured instead of a continuous video feed...
import cv
cv.NamedWindow('webcam_feed', cv.CV_WINDOW_AUTOSIZE)
cam = cv.CaptureFromCAM(-1)
feed = cv.QueryFrame(cam)
cv.ShowImage("webcam_feed", feed)
cv.WaitKey(-1)
WOW, answered my own question in 15 after me posting this. I did some research and the reason for the web cam only grabbing one image is because of the...
cv.WaitKey(-1)
This doesn't allow the contents of the window to refresh. I set the number to 10...
cv.WaitKey(10)
and it worked beautifully. I also tried 100, but saw no difference. I only saw a difference when the number was 1000. I use 1 because seems that it runs the smoothest.
Here is the full code to display a web cam feed
import cv
cv.NamedWindow("webcam", 1)
cam = cv.CaptureFromCAM(-1)
While True:
feed = cv.QueryFrame(cam)
cv.ShowImage("webcam", feed)
cv.WaitKey(1)
I believe you need to put
frame = cv.QueryFrame(cam)
cv.ShowImage("Webcam Feed", frame)
in a loop to continuously update the image shown in the window. That is, the frame from cv.QueryFrame is a static image, not a continuous video.
If you want to be able to exit with a key press, test cv.WaitKey with a small timeout in the loop too.
For me, the command in root
xhost +
save my time, Note to close and open new terminal.
See you.

Categories