Life2Coding
Load Webcam Video using OpenCV in Python

This post will be helpful in learning OpenCV using Python programming. Here I will show how to implement OpenCV functions and apply it in various aspects using some examples. Then the output will be shown with some comparisons as well.

Requirements:

First, you need to setup your Python Environment with OpenCV. You can easily do it by following Life2Coding’s tutorial on YouTube: Linking OpenCV 3 with Python 3

Goals:

In this tutorial, I will show you how to show webcam video output in a window using OpenCV with Python coding.

Documentation:

Python: cv2.VideoCapture(filename) → <VideoCapture object>

Python: cv2.VideoCapture(device) → <VideoCapture object>

Open video file or a capturing device for video capturing

Parameters:          

  • filename – name of the opened video file (eg. video.avi) or image sequence (eg. img_%02d.jpg, which will read samples like img_00.jpg, img_01.jpg, img_02.jpg, …)
  • device – id of the opened video capturing device (i.e. a camera index). If there is a single camera connected, just pass 0.

Steps:

  • Initialize webcam feed using cv2.VideoCapture()
  • Read webcam images using cv2.VideoCapture. read()
  • Display each image using cv2.imshow()
  • Wait for keyboard button press using cv2.waitKey()
  • Exit window and destroy all windows using cv2.destroyAllWindows()

Example Code:

import cv2

def show_webcam(mirror=False):

    cap = cv2.VideoCapture(0)
    cv2.namedWindow('Webcam Life2Coding',cv2.WINDOW_AUTOSIZE)
    while True:
        ret_val, frame = cap.read()

        if mirror:
            frame = cv2.flip(frame, 1)

        cv2.imshow('Webcam Life2Coding', frame)

        if cv2.waitKey(1) == 27:
            break  # esc to quit

    cv2.destroyAllWindows()

def main():
    show_webcam(mirror=True)

if __name__ == '__main__':
    main()

Output:

webcam-output-opencv-313x250 Load Webcam Video using OpenCV in Python

life2coding_icon [] Load Webcam Video using OpenCV in Python

One thought on “Load Webcam Video using OpenCV in Python

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.