You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
gesture_rec/utils/capture_photo.py

80 lines
2.9 KiB
Python

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import cv2
import os
import sys
import time
from pathlib import Path
def capture_photo(output_dir='captured', camera_id=0, mirror=True):
"""
Простой инструмент для захвата фото с камеры.
При нажатии 's' запускается отсчёт 3 секунды, затем делается снимок.
При нажатии 'q' выход.
"""
# Создаём папку, если её нет
Path(output_dir).mkdir(parents=True, exist_ok=True)
cap = cv2.VideoCapture(camera_id)
if not cap.isOpened():
print("Не удалось открыть камеру")
sys.exit(1)
print("Нажмите 's' для захвата фото (отсчёт 3 секунды)")
print("Нажмите 'q' для выхода")
capture_count = 0
countdown = 0
countdown_start = 0
while True:
ret, frame = cap.read()
if not ret:
break
if mirror:
frame = cv2.flip(frame, 1)
display = frame.copy()
# Отображение отсчёта, если активен
if countdown > 0:
elapsed = time.time() - countdown_start
remaining = max(0, 3 - elapsed)
if remaining > 0:
cv2.putText(display, f"Capturing in {int(remaining)}", (display.shape[1]//2-100, display.shape[0]//2),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), 2)
else:
# Сохраняем фото
timestamp = time.strftime("%Y%m%d_%H%M%S")
filename = f"photo_{timestamp}.jpg"
filepath = os.path.join(output_dir, filename)
cv2.imwrite(filepath, frame)
print(f"Сохранено: {filepath}")
capture_count += 1
countdown = 0
else:
# Подсказка
cv2.putText(display, "Press 's' to capture, 'q' to quit", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,255,0), 2)
cv2.imshow('Capture', display)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
elif key == ord('s') and countdown == 0:
countdown = 1
countdown_start = time.time()
cap.release()
cv2.destroyAllWindows()
print(f"Завершено. Сохранено {capture_count} фото.")
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--dir', default='captured', help='Папка для сохранения')
parser.add_argument('--camera', type=int, default=0, help='ID камеры')
parser.add_argument('--no-mirror', action='store_true', help='Отключить зеркалирование')
args = parser.parse_args()
capture_photo(output_dir=args.dir, camera_id=args.camera, mirror=not args.no_mirror)