OpenCV2: Access your USB camera in python


To access your USB camera on your laptop with the help of OpenCV2 in Python is a matter of a few lines of code. I tested it in Anaconda environment with Python 3.7. and OpenCV-4.1.1 library running on Win 10.

I assume that you have a working Anaconda environment. Unless, please follow the official instructions for installing one, here.

To install OpenCV in your Anaconda environment, you have to run the following:

(base) C:\WINDOWS\system32>conda install -c conda-forge opencv

To access your USB camera, open spyder editor (it comes with Anaconda environment) and the run the following code:

# -*- coding: utf-8 -*-
"""
Created on Sun May  3 20:50:56 2020
@author: Ilias Sachpazidis
"""

import cv2
print(cv2.__version__)
cap = cv2.VideoCapture(0)

if not (cap.isOpened()):
    print("Could not open video device")

# cap.set(cv2.CAP_PROP_FRAME_WIDTH, 600)
# cap.set(cv2.CAP_PROP_FRAME_HEIGHT,800)

while(True):    
    # Capture frame-by-frame    
    ret, frame = cap.read()    
    
    # Display the resulting frame    
    # cv2.imshow('preview',frame)    
    
    #gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
    #cv2.imshow('frame', gray)

    cv2.imshow('frame', frame)
    
    #Waits for a user input to quit the application    
    if cv2.waitKey(1) & 0xFF == ord('q'):    
        break
    
cap.release()
cv2.destroyAllWindows()