Python 3 and OpenCV Part 3: How to Read the Webcam with OpenCV (cv2)

GeeXLab - Python 3 - Webcam video capture with OpenCV


For this third tutorial (part 1, part 2) about OpenCV in Python 3, we’re going to look at how to read the webcam output.

OpenCV has an object for video capturing from video files, image sequences or cameras: VideoCapture. Let’s see how to create a VideoCapture object and use it to grab a frame from the webcam.

INIT script:

import cv2

video_capture_device_index = 0
webcam = cv2.VideoCapture(video_capture_device_index)

ret, video_frame =

That’s all.

If you have several webcams, you can specify the webcam by its index. Most users have only one webcam, therefore the video_capture_device_index is set to 0.

The read() grabs, decodes and returns a video frame. The video_frame is an NumPy array and, thanks to the part 2 we know how to convert it in a GeeXLab texture and how to display it. But before creating the texture, we need to know the size of the video frame. One way to do it is to read the video capture properties:

frame_width = int(round(webcam.get(cv2.CAP_PROP_FRAME_WIDTH)))
frame_height = int(round(webcam.get(cv2.CAP_PROP_FRAME_HEIGHT)))

We can now create the texture and update it with the video frame:

PF_U8_RGB = 1
PF_U8_BGR = 2
PF_U8_RGBA = 3

# BGR U8 is the default pixel format of OpenCV images.
# We create an empty texture
frame_texture = gh_texture.create_2d(frame_width, frame_height, PF_U8_BGR)

# and we update the texture pixmap with the OpenCV image.
gh_texture.update_gpu_memory_from_numpy_img(frame_texture, video_frame)

In the FRAME script, we can update the the texture every 50 ms and display it every frame:

dt = gh_utils.get_time_step()

gh_texture.bind(frame_texture, 0)

video_dt = video_dt + dt
if (video_dt > 0.05):
  video_dt = 0
  ret, frame =
  gh_texture.update_gpu_memory_from_numpy_img(frame_texture, frame)


Here is the demo:
GeeXLab - Python 3 - Webcam video capture with OpenCV

Keep in mind that frame_texture is a regular 2D texture you can map on any object (torus, sphere, …):

Webcam output mapped on a sphere:
GeeXLab - Python 3 - Webcam video capture with OpenCV

Webcam output mapped on a donut:
GeeXLab - Python 3 - Webcam video capture with OpenCV

The demo shows how to save a file with OpenCV too. At the end of the FRAME script there is the following piece of code:

if (gh_imgui.button("Screenshot", 100, 20) == 1):
  demo_dir = gh_utils.get_demo_dir() 	
  screenshot_counter = screenshot_counter + 1	
  cv_img_filename = "%s/webcam_frame_%.2d.jpg" % (demo_dir, screenshot_counter)
  cv2.imwrite(filename=cv_img_filename, img=frame)

You can easily save an OpenCV image on disk using cv2.imwrite().

One thought on “Python 3 and OpenCV Part 3: How to Read the Webcam with OpenCV (cv2)”

Leave a Comment

Your email address will not be published. Required fields are marked *