Created
November 25, 2024 15:37
-
-
Save hbmartin/1338f59b3f5fc95e635a9a664d8d4382 to your computer and use it in GitHub Desktop.
A simple Python script to capture webcam photos in a loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import cv2 | |
| import time | |
| import os | |
| from datetime import datetime | |
| def setup_output_directory(): | |
| output_dir = 'webcam_photos' | |
| if not os.path.exists(output_dir): | |
| os.makedirs(output_dir) | |
| return output_dir | |
| def capture_photos(interval=10): | |
| output_dir = setup_output_directory() | |
| camera = cv2.VideoCapture(0) | |
| if not camera.isOpened(): | |
| raise Exception("Could not access webcam") | |
| try: | |
| while True: | |
| ret, frame = camera.read() | |
| if not ret: | |
| print("Failed to capture frame") | |
| continue | |
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") | |
| filename = os.path.join(output_dir, f'photo_{timestamp}.jpg') | |
| cv2.imwrite(filename, frame) | |
| print(f"Saved {filename}") | |
| time.sleep(interval) | |
| except KeyboardInterrupt: | |
| print("\nStopping capture") | |
| finally: | |
| camera.release() | |
| if __name__ == '__main__': | |
| capture_photos() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment