Webcam + Open CV Python | Black screen

12,918

Solution 1

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.

Solution 2

Just change cv2.waitKey(0) to cv2.waitKey(30) and this issue will be resolved.

Solution 3

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

Solution 4

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()
Share:
12,918
Akanksha Dangi
Author by

Akanksha Dangi

Updated on June 13, 2022

Comments

  • Akanksha Dangi
    Akanksha Dangi almost 2 years

    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()
    
  • rayryeng
    rayryeng about 9 years
    Not sure if that will help. I think it has something to do with the webcam itself.
  • Aphire
    Aphire about 9 years
    Hah yeah just noticed that as I posted.
  • Aphire
    Aphire about 9 years
    Well hopefully OP will update with more system info. then someone more hardware orientated will be able to assist.
  • rayryeng
    rayryeng about 9 years
    lol no worries. BTW, this is better code than the OP has posted. It's more robust. The variable names in the original code are just awful.
  • thsieh
    thsieh almost 6 years
    This happens to me after continuously running the capture a couple hours. No matter it is logitech or other brands. After went black, I run this cv2/VideoCapture(-1) and it comes back to life. Wonder if @praveen you know whats the reason and how this helped? And what this is different from cv2.release()
  • Praveen
    Praveen almost 5 years
    Just realized that only few backends support the use of '-1' to search for the first available/free camera. See github.com/opencv/opencv/pull/11880 and linked conversations.
  • OscarSan
    OscarSan over 3 years
    Thanks, I disable Kaspersky and it worked like a charm