Python Machine learning --Capturing and processing video from a webcam

We will use a webcam to capture video data. Let’s see how to capture the video

from the webcam using OpenCV-Python.

How to do it…

1. Create a new Python file, and import the following packages:

import cv2

2. OpenCV provides a video capture object that we can use to capture images from the webcam. The 0 input argument specifies the ID of the webcam. If you connect a USB

camera, then it will have a different ID:

# Initialize video capture object

cap = cv2.VideoCapture(0)

3. Define the scaling factor for the frames captured using the webcam:

# Define the image size scaling factor

scaling_factor = 0.5

4. Start an infinite loop and keep capturing frames until you press the Esc key.

Read the frame from the webcam:

# Loop until you hit the Esc key

while True:

# Capture the current frame

ret, frame = cap.read()

5. Resizing the frame is optional but still a useful thing to have in your code:

# Resize the frame

frame = cv2.resize(frame, None, fx=scaling_factor, fy=scaling_

factor,

interpolation=cv2.INTER_AREA)

6. Display the frame:

# Display the image

cv2.imshow(‘Webcam’, frame)

7. Wait for 1 ms before capturing the next frame:

# Detect if the Esc key has been pressed

c = cv2.waitKey(1)

if c == 27:

break

8. Release the video capture object:

# Release the video capture object

cap.release()

9. Close all active windows before exiting the code:

# Close all active windows

cv2.destroyAllWindows()

10. If you run this code, you will see the video from the webcam.

--

--

At ITExamtools.com we help IT students and Professionals by providing important info. about latest IT Trends & for selecting various Academic Training courses.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Itexamtools

At ITExamtools.com we help IT students and Professionals by providing important info. about latest IT Trends & for selecting various Academic Training courses.