opencv: VideoCapture can't open camera by index
Running the following code on my raspberry pi 4b and OpenCV installed via “pip install opencv-python” I have no issues:
import cv2
cam = cv2.VideoCapture(0)
cam.isOpened() # True
However, when I installed OpenCV with the manual build described here, running the same code gives this error:
[ WARN:0] global /tmp/pip-req-build-4nusm4mm/opencv/modules/videoio/src/cap_gstreamer.cpp (1825) handleMessage OpenCV | GStreamer warning: Embedded video playback halted; module v4l2src0 reported: Failed to allocate required memory.
[ WARN:0] global /tmp/pip-req-build-4nusm4mm/opencv/modules/videoio/src/cap_gstreamer.cpp (914) open OpenCV | GStreamer warning: unable to start pipeline
[ WARN:0] global /tmp/pip-req-build-4nusm4mm/opencv/modules/videoio/src/cap_gstreamer.cpp (501) isPipelinePlaying OpenCV | GStreamer warning: GStreamer: pipeline have not been created
[ WARN:0] global /tmp/pip-req-build-4nusm4mm/opencv/modules/videoio/src/cap_v4l.cpp (893) open VIDEOIO(V4L2:/dev/video0): can't open camera by index
I believe I have all the required dependencies and gstreamer dev libs. /dev/video0 is fully readable. This same issue occurs when I build from other methods not involving the python package.
OpenCV 4.5.1 GStreamer 1.14.4 gcc 8.3.0 debian buster
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Comments: 25 (5 by maintainers)
Commits related to this issue
- VideoCapture can't open camera by index, #19527, https://github.com/opencv/opencv/issues/19527 — committed to jasonc1025-333/Raspberry-pi-web-control--ForkedFrom_3LucasZ-22_08 by jasonc1025-333 7 months ago
I faced this issue and got it resolved in my case:
[ WARN:0] global /tmp/pip-req-build-ms668fyv/opencv/modules/videoio/src/cap_v4l.cpp (893) open VIDEOIO(V4L2:/dev/video0): can't open camera by index
I was trying to live stream webcam video on local host server.Here is my error code:
`
from flask import Flask, render_template, Response import cv2
app = Flask(name) cap = cv2.VideoCapture(0) # wrong position, error def igen_frames():
Here is my resolved code:
` from flask import Flask, render_template, Response import cv2 app = Flask(name) def igen_frames(): cap = cv2.VideoCapture(0) #resolved, correct position
As you can see, it was resolved when cap = cv2.VideoCapture(0) was inside the function. So make sure that you place "cap = cv2.VideoCapture(0) " in a correct position if you are reading the frames inside a function.
Try to specify videoio backend:
or disable GStreamer backend in runtime or during the build.
[ WARN:0@0.332] global /io/opencv/modules/videoio/src/cap_v4l.cpp (902) open VIDEOIO(V4L2:/dev/video0): can’t open camera by index. This is the error i have when running python demo.py on WSL ubuntu , python 3.6, opencv 4.6
Below is the code.
‘’‘MIT License Copyright © 2020 Prokofiev Kirill, Intel Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.’‘’
import argparse import inspect import os.path as osp import sys
import cv2 as cv import glog as log import numpy as np
current_dir = osp.dirname(osp.abspath(inspect.getfile(inspect.currentframe()))) parent_dir = osp.dirname(current_dir) sys.path.insert(0, parent_dir) import utils from demo_tools import TorchCNN, VectorCNN, FaceDetector
def pred_spoof(frame, detections, spoof_model): “”“Get prediction for all detected faces on the frame”“” faces = [] for rect, _ in detections: left, top, right, bottom = rect # cut face according coordinates of detections faces.append(frame[top:bottom, left:right]) if faces: output = spoof_model.forward(faces) output = list(map(lambda x: x.reshape(-1), output)) return output return None, None
def draw_detections(frame, detections, confidence, thresh): “”“Draws detections and labels”“” for i, rect in enumerate(detections): left, top, right, bottom = rect[0] if confidence[i][1] > thresh: label = f’spoof: {round(confidence[i][1]*100, 3)}%’ cv.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), thickness=2) else: label = f’real: {round(confidence[i][0]*100, 3)}%’ cv.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), thickness=2) label_size, base_line = cv.getTextSize(label, cv.FONT_HERSHEY_SIMPLEX, 1, 1) top = max(top, label_size[1]) cv.rectangle(frame, (left, top - label_size[1]), (left + label_size[0], top + base_line), (255, 255, 255), cv.FILLED) cv.putText(frame, label, (left, top), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0))
def run(params, capture, face_det, spoof_model, write_video=False): “”“Starts the anti spoofing demo”“” fourcc = cv.VideoWriter_fourcc(*‘MP4V’) resolution = (1280,720) fps = 24 writer_video = cv.VideoWriter(‘output_video_demo.mp4’, fourcc, fps, resolution) win_name = ‘Antispoofing Recognition’ while cv.waitKey(1) != 27: has_frame, frame = capture.read() if not has_frame: return detections = face_det.get_detections(frame) confidence = pred_spoof(frame, detections, spoof_model) frame = draw_detections(frame, detections, confidence, params.spoof_thresh) cv.imshow(win_name, frame) if write_video: writer_video.write(cv.resize(frame, resolution)) capture.release() writer_video.release() cv.destroyAllWindows()
def main(): “”“Prepares data for the antispoofing recognition demo”“”
if name == ‘main’: main()
when i run the command based on the argparser argument python3 demo.py --fd_model /home/adesoji/light-weight-face-anti-spoofing-master/light-weight-face-anti-spoofing-master/MN3_antispoof.xml --spf_model /home/adesoji/light-weight-face-anti-spoofing-master/MN3_antispoof.mapping.xml --cam_id 0 --config config.py;
i get the error
[ WARN:0@0.357] global /io/opencv/modules/videoio/src/cap_v4l.cpp (902) open VIDEOIO(V4L2:/dev/video0): can’t open camera by index Traceback (most recent call last): File “demo.py”, line 137, in <module> main() File “demo.py”, line 122, in main assert cap.isOpened() AssertionError
please how do i rectify this