深度阅读

How to capture a image from webcam in Python?

作者
作者
2023年08月22日
更新时间
13.62 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。