Second video source /dev/video1 not working in python ubuntu - python

I am trying to use epiphan SDI2USB with ubuntu 18.04. I downloaded the correct driver from their support site and the driver is correctly installed. My kernel version is 4.15.0.
If I try to run vlc and i go to media menu --> Open Capture Device --> video device name --> Here I see both my /dev/video0 (integrated camera) and /dev/video1 (epiphan video) When I select /dev/video1 and click play, I can see it works fine.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
However when I write a simple python program from internet (i changed source from 0 to 1) and run it, I get an error
compass-admin#Alienware-13-R3:~$ sudo python3 cam.py
Insufficient buffer memory on /dev/video1 – decreasing buffers
Insufficient buffer memory on /dev/video1 – decreasing buffers
mmap: Invalid argument
munmap: Invalid argument
VIDEOIO ERROR: V4L: can’t open camera by index 1
munmap: Invalid argument
Traceback (most recent call last):
File “/home/compass-admin/.local/lib/python3.6/site-packages/numpy/lib/shape_base.py”, line 843, in split
len(indices_or_sections)
TypeError: object of type ‘int’ has no len()
I dont know if it is because of permissions or if you have to use a specific function in opencv. No matter what I do, I get the same error.
I changed permissions of /dev/video1 to 777, I also added the current user to video group but no luck. I also tried video source in opencv as 0, 1, -1 but no luck. Any help please.

Related

Error while trying to access phone camera with opencv python

I expected to receive a video feed in my laptop from my phone. In my opinion, the code is correct. The same code is running on other devices. But when I tried doing the same in my laptop, it displayed the following error:
[ERROR:0] global C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-wvn_it83\opencv\modules\videoio\src\cap.cpp (142) cv::VideoCapture::open VIDEOIO(CV_IMAGES): raised OpenCV exception:
OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-wvn_it83\opencv\modules\videoio\src\cap_images.cpp:253: error: (-5:Bad argument) CAP_IMAGES: can't find starting number (in the name of file): http://192.168.1.3:8080/video in function 'cv::icvExtractPattern'
Since I am a newbie to the world of opencv, I could'nt understand what caused the error. Hence, I did'nt try anything worthwhile other than changing a few lines of code.
My code is:
import cv2
url= 'http://192.168.1.3:8080/video'
cap=cv2.VideoCapture(url)
cap.set(3,240)
cap.set(4,240)
while(True):
ret,frame=cap.read()
if frame is not None:
cv2.imshow('frame',frame)
q=cv2.waitKey(1)
if q==ord("q"):
break
cv2.destroyAllWindows()
cap.release()
I had encountered the same issue but with a a saved video file as the input.
The file path I had entered did no exist and I got the same error.
I would suggest to check if your have given the right permissions to for accessing your phone's camera and if the feed is live and is returning images in the correct format.

Select timeout error on BeagleBone Black

I am testing an opencv video capture code on my BBB (running Debian Wheezy: Linux beaglebone 3.8.13-bone79 #1 SMP Tue Oct 13 20:44:55 UTC 2015 armv7l GNU/Linux) but getting a select timeout error everytime i run the program. Now i am behind schedule of my final year Iris recognition system Project. (In case you want to know why i am going through this video capture code, it is for tracking the eyes then capture an image that will be processed to obtain an IrisCode.)
I installed opencv 3.0.0 following instructions on http://www.pyimagesearch.com/2015/06/22/install-opencv-3-0-and-python-2-7-on-ubuntu/#comment-393561 , but had to turn off ffmpeg (suggested on one of the forums: OpenCV 3.0.0 make error with FFMPEG ) after obtaining a compilation errors but firstly i had compiled ffmpeg from source.
Below is the Video_Capturing code i tested with;
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
After running the code i am obtaining the following information (Note: The frame is only opening when i run the python script in LXTerminal accessed through tightvnc. It is failing to run through ssh);
root#beaglebone:~/Project/Testing# python Video_Streaming.py
(process:1488): Gtk-WARNING **: Locale not supported by C library.
Using the fallback 'C' locale.
Xlib: extension "RANDR" missing on display ":1".
select timeout
select timeout
select timeout
select timeout
^Cselect timeout
Traceback (most recent call last):
File "Video_Streaming.py", line 8, in <module>
ret, frame = cap.read()
KeyboardInterrupt
root#beaglebone:~/Project/Testing#
I'm stuck i need your help.

Memory leak with VideoCapture in Python OpenCV

I am using 3 webcams to occasionally take snapshots in OpenCV. They are connected to the same usb bus, which does not allow for all 3 connections at the same time due to usb bandwidth limitations (lowering the resolutions allows at most 2 simultaneous connections and I don't have more usb buses).
Because of this, I have to switch webcam connections every time I want to take a snapshot, but this causes a memory leak after some 40 switches.
This is the error I get:
libv4l2: error allocating conversion buffer
mmap: Cannot allocate memory
munmap: Invalid argument
munmap: Invalid argument
munmap: Invalid argument
munmap: Invalid argument
Unable to stop the stream.: Bad file descriptor
munmap: Invalid argument
munmap: Invalid argument
munmap: Invalid argument
munmap: Invalid argument
libv4l1: error allocating v4l1 buffer: Cannot allocate memory
HIGHGUI ERROR: V4L: Mapping Memmory from video source error: Invalid argument
HIGHGUI ERROR: V4L: Initial Capture Error: Unable to load initial memory buffers.
OpenCV Error: Bad flag (parameter or structure field) (Unrecognized or
unsupported array type) in cvGetMat, file
/build/buildd/opencv-2.3.1/modules/core/src/array.cpp, line 2482
Traceback (most recent call last):
File "/home/irobot/project/test.py", line 7, in <module>
cv2.imshow('cam', img)
cv2.error: /build/buildd/opencv-2.3.1/modules/core/src/array.cpp:2482:
error: (-206) Unrecognized or unsupported array type in function cvGetMat
This is a simple piece of code that generates this error:
import cv2
for i in range(0,100):
print i
cam = cv2.VideoCapture(0)
success, img = cam.read()
cv2.imshow('cam', img)
del(cam)
if cv2.waitKey(5) > -1:
break
cv2.destroyAllWindows()
Maybe a worthy note is that I get VIDIOC_QUERYMENU: Invalid argument errors every time the camera connects, although I can then still use it.
As some extra info, this is my v4l2-ctl -V output of the webcam:
~$ v4l2-ctl -V
Format Video Capture:
Width/Height : 640/480
Pixel Format : 'YUYV'
Field : None
Bytes per Line: 1280
Size Image : 614400
Colorspace : SRGB
What causes these errors and how can I fix them?
The relevant snippet of the error message is Unrecognised or unsupported array type in function cvGetMat. The cvGetMat() function converts arrays into a Mat. A Mat is the matrix data type that OpenCV uses in the world of C/C++ (Note: the Python OpenCV interface you are utilising uses Numpy arrays, which are then converted behind the scenes into Mat arrays). With that background in mind, the problem appears to be that that the array im you're passing to cv2.imshow() is poorly formed. Two ideas:
This could be caused by quirky behaviour on your webcam... on some
cameras null frames are returned from time to time. Before you pass
the im array to imshow(), try ensuring that it is not null.
If the error occurs on every frame, then eliminate some of the
processing that you are doing and call cv2.imshow() immediately
after you grab the frame from the webcam. If that still doesn't
work, then you'll know it's a problem with your webcam. Else, add
back your processing line by line until you isolate the problem. For
example, start with this:
while True:
# Grab frame from webcam
retVal, image = capture.read(); # note: ignore retVal
# faces = cascade.detectMultiScale(image, scaleFactor=1.2, minNeighbors=2, minSize=(100,100),flags=cv.CV_HAAR_DO_CANNY_PRUNING);
# Draw rectangles on image, and then show it
# for (x,y,w,h) in faces:
# cv2.rectangle(image, (x,y), (x+w,y+h), 255)
cv2.imshow("Video", image)
i += 1;
source: Related Question: OpenCV C++ Video Capture does not seem to work

cv2.videocapture.read() does not return a numpy array

I have this code trying to capture a frame from my webcam on raspberry pi, and saving it as an image. I use opencv 2, but I get strange errors when I run the code..
import time
import sys
from subprocess import call
import cv2
cam = cv2.VideoCapture()
while True:
cam.open(-1)
image = cam.read()
cv2.imwrite("current.jpeg",image)
time.sleep(10);
This is what the program returns:
VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument
Traceback (most recent call last):
File "kvamskogen.py", line 18, in <module>
cv2.imwrite("current.jpeg",image)
TypeError: <unknown> is not a numpy array
What is wrong here?
Reading (cam.read()) from a VideoCapture returns a tuple (return value, image). With the first item you check wether the reading was successful, and if it was then you proceed to use the returned image.
This is documented at https://opencv-tutorial.readthedocs.io/en/latest/intro/intro.html#capture-live-video
Everything mmgp said is spot-on; cam.read() returns first a boolean indicating whether the read was successful, and then the image itself (which will be empty if the return value was False). Also note that if you're not using the return value for anything, you can just set that portion to _, which tells Python "ignore me"; that line would then look something like _, image = cam.read(). Additionally, it is generally good practice to specify the index at which your camera is located (usually 0 if you have only one camera connected) when calling cv2.VideoCapture(), so that, in the event that you do have multiple cameras connected, OpenCV knows which camera to read from (otherwise it might just crash because it doesn't know what to do).
You should use arguments in cv2.VideoCapture()
Try this to capture from the default camera
cam = cv2.VideoCapture(0)
Try this to capture from ip camera
cam = cv2.VideoCapture('http://ip-address') # to check video source's ip address right click video and select "copy image address" and put the exact address in above line of code
If you are trying to capture video using inbuilt webcam then following code line will give you best results
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)

opencv getImage() error

I wrapped opencv today with simplecv python interface. After going through the official SimpleCV Cookbook I was able to successfully Load, Save, and Manipulate images. Thus, I know the library is being loaded properly.
However, under the Using a Camera, Kinect, or Virtual Camera heading I was unsuccessful in running some commands. In particular, mycam = Camera() worked, but img = mycam.getImage() produced the following error:
In [35]: img = mycam.getImage().save()
OpenCV Error: Bad argument (Array should be CvMat or IplImage) in cvGetSize, file /home/jordan/OpenCV-2.2.0/modules/core/src/array.cpp, line 1237
---------------------------------------------------------------------------
error Traceback (most recent call last)
/home/simplecv/<ipython console> in <module>()
/usr/local/lib/python2.7/dist-packages/SimpleCV-1.1-py2.7.egg/SimpleCV/Camera.pyc in getImage(self)
332
333 frame = cv.RetrieveFrame(self.capture)
--> 334 newimg = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_8U, 3)
335 cv.Copy(frame, newimg)
336 return Image(newimg, self)
error: Array should be CvMat or IplImage
I'm running Ubuntu Natty on a HP TX2500 tablet. It has a built in webcam, (CyberLink Youcam?) Has anybody seen this error before? I've been all over the web today looking for a solution, but nothing seems to be doing the trick.
Update 1: I tested cv.QueryFrame(capture) using the code found here in a separate Stack Overflow question and it worked; so I've pretty much nailed this down to a webcam issue.
Update 2: In fact, I get the exact same errors on a machine that doesn't even have a webcam! It's looking like the TX2500 is not compatible...
since the error raised from Camera.py of SimpleCV, you need to debug the getImage() method. If you can edit it:
def getImage(self):
if (not self.threaded):
cv.GrabFrame(self.capture)
frame = cv.RetrieveFrame(self.capture)
import pdb # <-- add this line
pdb.set_trace() # <-- add this line
newimg = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_8U, 3)
cv.Copy(frame, newimg)
return Image(newimg, self)
then run your program, it will be paused as pdb.set_trace(), here you can inspect the type of frame, and try to figure out how get the size of frame.
Or you can do the capture in your code, and inspect the frame object:
mycam = Camera()
cv.GrabFrame(mycam.capture)
frame = cv.RetrieveFrame(mycam.capture)
To answer my own question...
I bought a Logitech C210 today and the problem disappeared.
I'm now getting warnings:
Corrupt JPEG data: X extraneous bytes before marker 0xYY.
However, I am able to successfully push a video stream to my web-browser via JpegStreamer(). If I cannot solve this error, I'll open a new thread.
Thus, for now, I'll blame the TX2500.
If anybody finds a fix in the future, please post.
Props to #HYRY for the investigation. Thanks.
I'm geting the camera with OpenCV
from opencv import cv
from opencv import highgui
from opencv import adaptors
def get_image()
cam = highgui.cvCreateCameraCapture(0)
im = highgui.cvQueryFrame(cam)
# Add the line below if you need it (Ubuntu 8.04+)
#im = opencv.cvGetMat(im)
return im
Anthony, one of the SimpleCV developers here.
Also instead of using image.save(), this function writes the file/video to disk, you instead probably want to use image.show(). You can save if you want, but you need to specify a file path like image.save("/tmp/blah.png")
So you want to do:
img = mycam.getImage()
img.show()
As for that model of camera I'm not sure if it works or not. I should note that we also wrapper different camera classes not just OpenCV, this is because OpenCV has a problem with webcams over 640x480, we now can do high resolution cameras.
Also I should mention, which I didn't realize, is that OpenCV less than 2.3 is broken with webcams on Ubuntu 11.04 and up. I didn't realize this as I was running Ubuntu 10.10 before, by the looks of your output you are using python 2.7 which makes me think you are on Ubuntu 11.04 or higher. Anyway, we have a fix for this problem. It is now pushed up into the master, it basically does a check to see if OpenCV is working, if not it will fall back to pygame.
This fix will also be in the 1.2 release of SimpleCV (It's in the master branch now)

Categories

Resources