The code:
import cv2
cap= cv2.VideoCapture(1)
if not cap.isOpened():
raise IOError("Cannot open webcam")
cntr =0
while True:
ret,frame = cap.read()
cntr= cntr+1;
if ((cntr%30)==0):
cv2.putText(frame,'cool' ,(50,50), cv2.FONT_HERSHEY_SIMPLEX, 0.7,(0,0,255),2)
cv2.imshow('Text Detection Tutorial',frame)
if cv2.waitKey(2) & 0xff == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
The error in the jupyter-notebook window:
17 raise IOError("Cannot open webcam")
OSError: Cannot open webcam
I have two devices, a built-in webcam /dev/video0
and an USB webcam /dev/video1.
They both appear listed with ls -ltrh /dev/video*
Both cameras work fine with guvcview
.
I use jupyter-notebook to run the code above.
When I use cap= cv2.VideoCapture(0)
it works fine. But when I use cap= cv2.VideoCapture(1) for the USB camera I get the next error in the terminal:
[ WARN:0] global /tmp/pip-req-build-ms668fyv/opencv/modules/videoio/src/cap_v4l.cpp (893) open VIDEOIO(V4L2:/dev/video1): can't open camera by index
I tried to give all permissions to /dev/video1, sudo chmod 777 /dev/video1.
I'm using linux mint.
Linux creates 2 files in the
/dev/video
for each webcam. The lower numbered one (/dev/video0
in your case ) is for capturing stream and the following one (/dev/video1
in your case) includes some data about camera.So when you tried with the index number 0, it works fine and opens the camera with
VideoCapture(0)
. But what about the 2nd camera ? There may be some different reasons why it is missing:As a result, its not bacause of
VideoCapture
can not read; its just because of you are trying to open it with wrong index which is data file of camera.Note: I suggest you to try
VideoCapture(-1)
also, this also works in some cases interestingly. Sometimes for substreams of webcams or luckiliy opening a camera's substream which has its own driver.