How to capture a image from webcam in Python?

Published on Aug. 22, 2023, 12:15 p.m.

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
pygame.init()

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

# Read a frame from the camera
ret, frame = cap.read()

# 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))
pygame.display.flip()

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

# Release the camera and quit Pygame
cap.release()
pygame.quit()

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.

Tags:

cv2

related content