USB Camera is not detected by OpenCV Python - python

I am working on a project that has to detect a USB camera (CM3-U3-13S2C-CS a 1.3 Megapixel USB 3.0 camera), opencv failed to detect the id of the camera I have tried the code below to display the IDS of available cameras but all that openCV detects is the ID of the webcam, the camera is working fine on Labview.
I would really appreciate any help !
> import cv2
>
> openCvVidCapIds = []
>
> for i in range(100):
> try:
> cap = cv2.VideoCapture(i)
> if cap is not None and cap.isOpened():
> openCvVidCapIds.append(i)
> # end if
> except:
> pass
> # end try
> # end for
>
> print(str(openCvVidCapIds))

which OS are you running your OpenCV codes? have you checked if your USB camera is shown up in your OS device layers?
for windows, in the Device Manager under the "Imaging devices" tree
for Linux, in /dev like "/dev/video1" and "/dev/video2" and then do
cap =
cv2.VideoCapture("/dev/videox")

Related

Pyrealsense2 (Librealsense SDK 2.0): choose cam from Serial Number

I've 2 Intel realsense D415. I'm Using a NUC with Xubuntu 16.04 and python 3.5.2.
I can find only this documentation and examples: https://github.com/IntelRealSense/librealsense/tree/master/wrappers/python
My problem is that I need to select the camera to use by serial number to be sure to select everytime the same camera.
import pyrealsense2 as rs
pipeline = rs.pipeline()
config = rs.config()
profile = config.resolve(pipeline)
profile = config.resolve(pipeline)
print(profile.get_device())
This code print this: < pyrealsense2.device: Intel RealSense D415 (S/N: 805212060066) >
I need to check the S/N and in case it's not the right one, I would need to pass to the second camera, then the third....
I would need a guide or a documentation about pyrealsense2 but I don't think it exists
EDIT - I found a solution:
import pyrealsense2 as rs
ctx = rs.context()
if len(ctx.devices) > 0:
for d in ctx.devices:
print ('Found device: ', \
d.get_info(rs.camera_info.name), ' ', \
d.get_info(rs.camera_info.serial_number))
else:
print("No Intel Device connected")
You can specify device serial number in config.
config = re.config()
config.enable_device('805212060066')
profile = config.resolve(pipeline)

How to correctly check if a camera is available?

I am using OpenCV to open and read from several webcams. It all works fine, but I cannot seem to find a way to know if a camera is available.
I tried this code (cam 2 does not exist):
import cv2
try:
c = cv2.VideoCapture(2)
except:
print "Cam 2 is invalid."
But this just prints a lot of errors:
VIDEOIO ERROR: V4L: index 2 is not correct!
failed to open /usr/lib64/dri/hybrid_drv_video.so
Failed to wrapper hybrid_drv_video.so
failed to open /usr/lib64/dri/hybrid_drv_video.so
Failed to wrapper hybrid_drv_video.so
GStreamer Plugin: Embedded video playback halted; module v4l2src0 reported: Internal data stream error.
OpenCV Error: Unspecified error (GStreamer: unable to start pipeline
) in cvCaptureFromCAM_GStreamer, file /builddir/build/BUILD/opencv-3.2.0/modules/videoio/src/cap_gstreamer.cpp, line 832
VIDEOIO(cvCreateCapture_GStreamer(CV_CAP_GSTREAMER_V4L2, reinterpret_cast<char *>(index))): raised OpenCV exception:
/builddir/build/BUILD/opencv-3.2.0/modules/videoio/src/cap_gstreamer.cpp:832: error: (-2) GStreamer: unable to start pipeline
in function cvCaptureFromCAM_GStreamer
OpenCV Error: Unspecified error (unicap: failed to get info for device
) in CvCapture_Unicap::initDevice, file /builddir/build/BUILD/opencv-3.2.0/modules/videoio/src/cap_unicap.cpp, line 139
VIDEOIO(cvCreateCameraCapture_Unicap(index)): raised OpenCV exception:
/builddir/build/BUILD/opencv-3.2.0/modules/videoio/src/cap_unicap.cpp:139: error: (-2) unicap: failed to get info for device
in function CvCapture_Unicap::initDevice
CvCapture_OpenNI::CvCapture_OpenNI : Failed to enumerate production trees: Can't create any node of the requested type!
<VideoCapture 0x7fa5b5de0450>
No exception is thrown. When using c.read() later, I do get False, but I would like to do this in the initialisation phase of my program.
So, how do I find out how many valid cameras I have or check if a certain number 'maps' to a valid one?
Using cv2.VideoCapture( invalid device number ) does not throw exceptions. It constructs a <VideoCapture object> containing an invalid device - if you use it you get exceptions.
Test the constructed object for None and not isOpened() to weed out invalid ones.
For me this works (1 laptop camera device):
import cv2 as cv
def testDevice(source):
cap = cv.VideoCapture(source)
if cap is None or not cap.isOpened():
print('Warning: unable to open video source: ', source)
testDevice(0) # no printout
testDevice(1) # prints message
Output with 1:
Warning: unable to open video source: 1
Example from: https://github.com/opencv/opencv_contrib/blob/master/samples/python2/video.py
lines 159ff
cap = cv.VideoCapture(source)
if 'size' in params:
w, h = map(int, params['size'].split('x'))
cap.set(cv.CAP_PROP_FRAME_WIDTH, w)
cap.set(cv.CAP_PROP_FRAME_HEIGHT, h)
if cap is None or not cap.isOpened():
print 'Warning: unable to open video source: ', source
Another solution, which is available in Linux is to use the /dev/videoX device in the VideoCapture() call. The devices are there when the cam is plugged in. Together with glob(), it is trivial to get all the cameras:
import cv2, glob
for camera in glob.glob("/dev/video?"):
c = cv2.VideoCapture(camera)
Of course a check is needed on c using isOpened(), but you are sure you only scan the available cameras.
Here is a "NOT working" solution to help you prevent tumbling over in this pitfall:
import cv2 as cv
import PySpin
print (cv.__version__)
# provided by Patrick Artner as solution to be working for other cameras than
# those of Point Grey (FLIR).
def testDevice(source):
cap = cv.VideoCapture(source)
if cap is None or not cap.isOpened():
print('Warning: unable to open video source: ', source)
# ... PySpin / Spinnaker (wrapper/SDK libary) ...
system = PySpin.System.GetInstance()
cam_list = system.GetCameras()
cam = ''
cam_num = 0
for ID, cam in enumerate(cam_list):
# Retrieve TL device nodemap
if ID == cam_num:
print ('Got cam')
cam = cam
cam.Init()
# ... CV2 again ...
for i in range(10):
testDevice(i) # no printout
You can try this code:
from __future__ import print_function
import numpy as np
import cv2
# detect all connected webcams
valid_cams = []
for i in range(8):
cap = cv2.VideoCapture(i)
if cap is None or not cap.isOpened():
print('Warning: unable to open video source: ', i)
else:
valid_cams.append(i)
caps = []
for webcam in valid_cams:
caps.append(cv2.VideoCapture(webcam))
while True:
# Capture frame-by-frame
for webcam in valid_cams:
ret, frame = caps[webcam].read()
# Display the resulting frame
cv2.imshow('webcam'+str(webcam), frame)
k = cv2.waitKey(1)
if k == ord('q') or k == 27:
break
# When everything done, release the capture
for cap in caps:
cap.release()
cv2.destroyAllWindows()

Turtlebot subscriber pointcloud2 shows color in Gazebo simulator but not in robot

I am subscribing to topic "/camera/depth/points" and message PointCloud2 on a turtlebot (deep learning version) with ASUS Xtion PRO LIVE camera.
I have used the python script below under the gazebo simulator environment and i can receive x, y, z and rgb values successfully.
However, when i run it in the robot, the rgb values are missing.
Is this a problem of my turtlebot version, or camera or is it that i have to specify somewhere that i want to receive PointCloud2 type="XYZRGB"? or is it a sync problem? Any clues please thanks!
#!/usr/bin/env python
import rospy
import struct
import ctypes
import sensor_msgs.point_cloud2 as pc2
from sensor_msgs.msg import PointCloud2
file = open('workfile.txt', 'w')
def callback(msg):
data_out = pc2.read_points(msg, skip_nans=True)
loop = True
while loop:
try:
int_data = next(data_out)
s = struct.pack('>f' ,int_data[3])
i = struct.unpack('>l',s)[0]
pack = ctypes.c_uint32(i).value
r = (pack & 0x00FF0000)>> 16
g = (pack & 0x0000FF00)>> 8
b = (pack & 0x000000FF)
file.write(str(int_data[0])+","+str(int_data[1])+","+str(int_data[2])+","+str(r)+","+str(g)+","+str(b)+"\n")
except Exception as e:
rospy.loginfo(e.message)
loop = False
file.flush
file.close
def listener():
rospy.init_node('writeCloudsToFile', anonymous=True)
rospy.Subscriber("/camera/depth/points", PointCloud2, callback)
rospy.spin()
if __name__ == '__main__':
listener()
The contents of Published topics are determined by the software that provides them - i.e. the drivers for your camera. To fix this you therefore need to get the right driver and use the topic that it says contains the required information.
You can find recommended drivers for your cameras on the ROS wiki or on some community websites - like this. In your case, the ASUS devices should use openni2 and set depth_registration:=true - as documented here.
At this point, /camera/depth_registered/points should now show the combined xyz and RGB point cloud. To use it, your new listener() code should look something like this:
def listener():
rospy.init_node('writeCloudsToFile', anonymous=True)
# Note the change to the topic name
rospy.Subscriber("/camera/depth_registered/points", PointCloud2, callback)
rospy.spin()

web cam stops again and again after once code is run in ubuntu opencv python

I want to capture images from webcam and then further do image processing for ANPR (Automatic number plate Recognition) in python 2.7 using opencv 2.4.10 in Ubuntu 14.04. When I run this simple code, it detects my camera once and then camera stops working.
Code is:
import cv2
cam = cv2.VideoCapture(0)
s, img = cam.read()
winName = "Movement Indicator"
cv2.namedWindow(winName, cv2.CV_WINDOW_AUTOSIZE)
while s:
cv2.imshow( winName,img )
s, img = cam.read()
key = cv2.waitKey(10) & 0xFF
if key == 27:
cv2.destroyWindow(winName)
break
print "Goodbye"
Can someone please help me with this?
Got the answer. I was not releasing cam. It works fine now

Capturing network video using opencv

I am using ffserver and ffmpeg combination to capture web camera video and transmit it through my network.
I want to capture this video using opencv and python from another computer.
I can see the video (cam1.asf) in the browser of another computer. But my opencv + python code could not capture any frame.
Code for ffserver
HTTPPort 8090
HTTPBindAddress 0.0.0.0
MaxHTTPConnections 2000
MaxClients 1000
MaxBandWidth 2000
<Feed feed1.ffm>
File ./tmp/feed1.ffm
FileMaxSize 1G
ACL allow 127.0.0.1
</Feed>
<Stream cam1.asf>
Feed feed1.ffm
Format asf
VideoCodec msmpeg4v2
VideoFrameRate 30
VideoSize vga
</Stream>
FFmpeg
$ffmpeg -f video4linux2 -i /dev/video0 192.168.1.3 /cam1.ffm
This stream can be seen in the browser
But with opencv code
import sys
import cv2.cv as cv
import numpy
video="http://http://192.168.1.3:8090/cam1.asf"
capture =cv.CaptureFromFile(video)
cv.NamedWindow('Video Stream', 1 )
while True:
# capture the current frame
frame = cv.QueryFrame(capture)
#if frame is None:
# break
#else:
#detect(frame)
cv.ShowImage('Video Stream', frame)
if cv.WaitKey(10) == 27:
print 'ESC pressed. Exiting ...'
break
I donot get any output in the stream
My aim is to work with the web camera video both at the base station (ie where the web camera is connected) and also at the network location

Categories