简体   繁体   中英

Webcam + Open CV Python | Black screen

I am using the code below, but I get a black image. Could you please help me rectify the error?

import cv2
import numpy as np
c = cv2.VideoCapture(0)

while(1):
    _,f = c.read()
    cv2.imshow('e2',f)
    if cv2.waitKey(5)==27:
        break
cv2.destroyAllWindows()

Update : See github.com/opencv/opencv/pull/11880 and linked conversations, only few backends support -1 as index.


Although this is an old post, this answer can help people who are still facing the same problem. If you have a single webcam but it renders all black , use cv2.VideoCapture(-1) . This will get you the working camera.

只需将cv2.waitKey(0)更改为cv2.waitKey(30)解决此问题。

Try this:

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while(True):
    ret, frame = cap.read()

    cv2.imshow('frame',frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

I've faced with same problem. Updating neither opencv nor webcam driver works. I am using kaspersky as antivirus. When I disable the kaspersky, then black output problem solved.

BTW, I can see the running .py file in kaspersky console > reports > host intrusion prevention. It reports application privilege control rule triggered - application: myfile.py, result: blocked: access to video capturing devices

This worked for me: I did a pip install imutils . Imutils is a library with series of convenience functions to make basic image processing functions such as translation, rotation, resizing, skeletonization, displaying Matplotlib images, sorting contours, detecting edges, and much more easier with OpenCV and both Python 2.7 and Python 3.

import cv2
import imutils

cap = cv2.VideoCapture(0)  # video capture source camera (Here webcam of laptop)
ret, frame = cap.read()  # return a single frame in variable `frame`


while (True):
    # gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    (grabbed, frame) = cap.read()
    frame = imutils.resize(frame, width=400)
    cv2.imshow('img1', frame)  # display the captured image
    if cv2.waitKey(1) & 0xFF == ord('q'):  # save on pressing 'y'
        cv2.imwrite('capture.png', frame)
        cv2.destroyAllWindows()
        break

cap.release()

Try put -0 on the index and pause any antivirus running

import cv2
import numpy as np

cap = cv2.VideoCapture(-0)
cap.set(3,640)
cap.set(3,480)

while(True):
    success, img = cap.read()

    cv2.imshow('frame',img)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

I faced the same issue after many calls with:

cap = cv2.VideoCapture(0)

and it solved when I changed the index to 1:

cap = cv2.VideoCapture(1)

就我而言,只是禁用 Kaspersy 问题已解决

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM