Skip to content

Instantly share code, notes, and snippets.

@ereli
Last active February 15, 2023 05:36
Show Gist options
  • Save ereli/c9998a6911c2f426cd41dd85c99cda7a to your computer and use it in GitHub Desktop.
Save ereli/c9998a6911c2f426cd41dd85c99cda7a to your computer and use it in GitHub Desktop.
capture still images from multiple cameras using python pygame
import time
from pathlib import Path
import pygame
import pygame.camera
from pygame.locals import *
from datetime import datetime
pygame.init()
pygame.camera.init()
try:
pygame.camera.list_cameras() # Camera detected or not
except:
raise("couldn't read camera")
actual_cam_list = pygame.camera.list_cameras()
cam_list = ['cam0', 'cam1', 'cam2', 'cam3']
active_cameras = []
for x, y in zip(actual_cam_list, cam_list):
globals()[y] = pygame.camera.Camera(
x, (1920, 1080)) # generate_function(x,'data/')
globals()[y].start()
active_cameras.append(globals()[y])
def init(folder):
folder_path = Path(folder).resolve()
try:
folder_path.mkdir(exist_ok=False)
except FileExistsError:
pass
def capture(camera, folder="data/"):
t = time.localtime()
folder_path = Path(folder).resolve()
init(folder)
# print(camera)
img = camera.get_image()
now = datetime.now()
timestamp = now.strftime("%H:%M:%S.%f")
out_file = str(folder_path.joinpath(
"img_{0}.jpg".format(timestamp)).absolute())
print("Saving filename: {0}".format(out_file))
pygame.image.save(img, out_file)
if __name__ == '__main__':
for i in active_cameras:
capture(i)
@Wakebgh
Copy link

Wakebgh commented Jan 19, 2023

hey, i hope you are well i just have a question if i have large number of cameras say millions and i want to capture images from millions cameras and path them to detection model this code will be efficient or not ?

@ereli
Copy link
Author

ereli commented Feb 15, 2023

@Wakebgh no, that's not what you're looking for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment