forked from cbh123/narrator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
capture.py
52 lines (40 loc) · 1.3 KB
/
capture.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import os
import time
import cv2
import numpy as np
from PIL import Image
# Folder
folder = "frames"
# Create the frames folder if it doesn't exist
frames_dir = os.path.join(os.getcwd(), folder)
os.makedirs(frames_dir, exist_ok=True)
# Initialize the webcam
cap = cv2.VideoCapture(0)
# Check if the webcam is opened correctly
if not cap.isOpened():
raise IOError("Cannot open webcam")
# Wait for the camera to initialize and adjust light levels
time.sleep(2)
while True:
ret, frame = cap.read()
if ret:
# Convert the frame to a PIL image
pil_img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
# Resize the image
max_size = 250
ratio = max_size / max(pil_img.size)
new_size = tuple([int(x * ratio) for x in pil_img.size])
resized_img = pil_img.resize(new_size, Image.LANCZOS)
# Convert the PIL image back to an OpenCV image
frame = cv2.cvtColor(np.array(resized_img), cv2.COLOR_RGB2BGR)
# Save the frame as an image file
print("📸 Say cheese! Saving frame.")
path = f"{folder}/frame.jpg"
cv2.imwrite(path, frame)
else:
print("Failed to capture image")
# Wait for 2 seconds
time.sleep(2)
# Release the camera and close all windows
cap.release()
cv2.destroyAllWindows()