python · March 26, 2023 0

How to capture a image from webcam in Python?

Table of Content

To capture an image from a webcam in Python, you can use the OpenCV (Open Source Computer Vision Library) and Pygame libraries. The OpenCV library provides a video capture object that can be used to read frames from the camera, and the Pygame library provides a way to display the captured image and save it.

Here is some sample code that captures an image from a camera and saves it to a file:

import cv2
import pygame

# Initialize Pygame

# Find and open the camera
cap = cv2.VideoCapture(0)

# Read a frame from the camera
ret, frame =

# Convert the frame from BGR (OpenCV format) to RGB (Pygame format)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

# Create a Pygame surface from the frame
surface = pygame.surfarray.make_surface(frame)

# Display the image on the screen
screen = pygame.display.set_mode((640, 480))
screen.blit(surface, (0, 0))

# Wait for a key press to save the image
while True:
    event = pygame.event.wait()
    if event.type == pygame.KEYDOWN:, "image.jpg")

# Release the camera and quit Pygame

This code captures a frame from the camera and shows it on the screen using Pygame. It waits for a key press, and when a key is pressed, it saves the image to a file named "image.jpg" and exits.

%d bloggers like this: