Search code examples
pythonopencvvideo-capture

OpenCV freezes while trying to run VideoCapture(0)


I am playing around with OpenCV. I am following the documentation example (link)

I installed GTK webcam application on Ubuntu to validate that my webcam works. I am able to start the webcam and see the video feedback in GTK.

I added some print message in the tutorial code to see where I get. I added a print before and after this line: cap = cv2.VideoCapture(0)

All I get, when running the Python file, is the print that I added before the cap = cv2.VideoCapture(0) and nothing else.

I tried increasing the waitKey to 20, 40, 100 but it didn't help.

Does anyone know why it does not get further and display the frame?

My code:

import numpy as np 
import cv2 

videoFeed = cv2.VideoCapture(0) 
while (True): 
    ret, frame = videoFeed.read() 
    frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 
    cv2.imshow('Feed', frame_gray) 
    if cv2.waitKey(10) & 0xFF = ord("q"): 
        break 
videoFeed.release() 
cv2.destroyAllWindows() 

My setup:

  • Windows 10 host
  • Ubuntu 18.04 guest host
  • Integrated Webcam
  • Using PIP to install python module (numpy, scipi, pillow, open_cv, etc.)
  • Using venv python

Solution

  • You have a bug in your code at if cv2.waitKey(10) & 0xFF = ord("q"):. You should've gotten a syntax error here though.

    import numpy as np 
    import cv2 
    
    videoFeed = cv2.VideoCapture(0) 
    while (True): 
        ret, frame = videoFeed.read()
        if ret == False:
            print("Failed to retrieve frame")
            break 
        frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 
        cv2.imshow('Feed', frame_gray) 
        if cv2.waitKey(10) & 0xFF == ord("q"): 
            break 
    videoFeed.release() 
    cv2.destroyAllWindows() 
    

    Tested your code. Works fine. Only other suggestion is to check whether your Ubuntu guest has permission to access your webcam. If you're using VirtualBox I remember seeing an option for this in the interface