Last active
February 2, 2024 20:54
-
-
Save jasonhejna/974f3de54d742168fdcedf9ad0155503 to your computer and use it in GitHub Desktop.
camera_capture_test.py
This file contains 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 os | |
import time | |
def main(): | |
# Camera settings | |
width, height, fps = 640, 360, 260 | |
frame_count_to_capture = fps # Number of frames for 1 second | |
temp_image_folder = "temp_images" | |
os.makedirs(temp_image_folder, exist_ok=True) | |
# Open the camera | |
cap = cv2.VideoCapture(2) | |
cap.set(cv2.CAP_PROP_FRAME_WIDTH, width) | |
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height) | |
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG')) | |
cap.set(cv2.CAP_PROP_FPS, fps) | |
if not cap.isOpened(): | |
print("Error: Could not open camera.") | |
return | |
frame_timestamps = [] | |
try: | |
while True: | |
ret, frame = cap.read() | |
if not ret: | |
break | |
# Capture current time | |
current_time = int(time.time() * 1000) # Milliseconds | |
frame_timestamps.append(current_time) | |
if len(frame_timestamps) > frame_count_to_capture: | |
# Remove the oldest timestamp | |
frame_timestamps.pop(0) | |
# Save frame as an image | |
image_path = os.path.join(temp_image_folder, f"{current_time}.jpg") | |
cv2.imwrite(image_path, frame) | |
cv2.imshow('Camera Feed', frame) | |
# Listen for spacebar keypress | |
if cv2.waitKey(1) & 0xFF == ord(' '): | |
break | |
# Press 'q' to exit | |
if cv2.waitKey(1) & 0xFF == ord('q'): | |
break | |
# Create video from the captured images | |
create_video_from_images(frame_timestamps, temp_image_folder, fps, width, height) | |
finally: | |
cap.release() | |
cv2.destroyAllWindows() | |
# Optionally, clean up the temporary image folder | |
# for file in os.listdir(temp_image_folder): | |
# os.remove(os.path.join(temp_image_folder, file)) | |
# os.rmdir(temp_image_folder) | |
def create_video_from_images(timestamps, folder, fps, width, height): | |
timestamp = int(time.time()) | |
file_name = f'output_{timestamp}.mp4' | |
fourcc = cv2.VideoWriter_fourcc(*'mp4v') | |
out = cv2.VideoWriter(file_name, fourcc, fps, (width, height)) | |
for ts in timestamps: | |
image_path = os.path.join(folder, f"{ts}.jpg") | |
if os.path.exists(image_path): | |
frame = cv2.imread(image_path) | |
out.write(frame) | |
out.release() | |
print(f"Video saved as {file_name}") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment