Раскад

Программа для извлечения кадров из видео с привязкой к GPS-координатам

Скачать скрипт

Оглавление

1. Обзор программы

Раскад — это инструмент для извлечения кадров из видео с привязкой к координатам из GPX-трека. Программа анализирует видео и GPX-файл, синхронизирует их по времени и сохраняет наиболее четкие кадры с GPS-метаданными в формате EXIF.

Типичный сценарий использования: Вы записали видео с видеорегистратора и параллельно вели GPS-трек. Программа поможет вам получить геопривязанные кадры из видео с указанием точного местоположения, высоты и направления движения.

2. Основные возможности

3. Требования и зависимости

Для работы программы требуется:

Важно: Для обработки видео в форматах MOV или MP4 рекомендуется установить ffmpeg. В Linux установите его командой:

sudo apt-get install ffmpeg

4. Установка

  1. Скачайте скрипт (кнопка выше)
  2. Установите зависимости (см. раздел выше)
  3. Поместите скрипт в удобную директорию
  4. Готово к использованию!

5. Использование

5.1. Базовое использование

Минимальная команда для запуска:

            python3 rascad.py \
                --video input.mp4 \
                --gpx track.gpx \
                --sync-time "2025-08-15 10:37:26"
                

Эта команда:

5.2. Расширенные примеры

Пример 1: Извлечение кадров каждые 5 секунд с автоматическим определением четкости

            python3 rascad.py \
                --video input.mp4 \
                --gpx track.gpx \
                --output my_frames \
                --interval 5.0 \
                --sharpness auto \
                --sync-time "2025-08-15 10:37:26" \
                --sync-first \
                --timezone Europe/Moscow
                

Пример 2: Обработка с высоким порогом четкости и большим интервалом

            python3 rascad.py \
                --video travel.mp4 \
                --gpx path.gpx \
                --interval 10.0 \
                --sharpness 200 \
                --sync-time "2025-08-15 08:00:00" \
                --timezone UTC
                

6. Параметры командной строки

Параметр Описание Значения По умолчанию
--video Обязательный. Путь к видеофайлу Любой видеофайл, поддерживаемый OpenCV (MP4, MOV, AVI) -
--gpx Обязательный. Путь к GPX-файлу с треком Стандартный GPX-файл -
--output Директория для сохранения кадров Любое допустимое имя папки output_frames
--interval Интервал извлечения кадров (в секундах) Положительное число (0.1-3600) 1.0
--sharpness Порог четкости (вариация лапласиана) Число или 'auto' 100
--sync-time Обязательный. Время синхронизации Формат: "YYYY-MM-DD HH:MM:SS" -
--sync-first Синхронизировать по первому кадру Флаг (без значения) False
--timezone Временная зона для синхронизации Например: "Europe/Moscow", "UTC" UTC
--batch-size Размер батча для многопоточной обработки Целое число (1-100) 10

Совет: Для определения оптимального значения --sharpness сначала запустите программу с параметром --sharpness auto, а затем используйте значение, которое программа выведет в консоли.

7. Ограничения

8. Исходный код

Первые строки скрипта:

#!/usr/bin/env python3
import argparse
import cv2
import gpxpy
import piexif
import numpy as np
import os
import pytz
from datetime import datetime, timedelta
from concurrent.futures import ThreadPoolExecutor
from tqdm import tqdm

class FrameProcessor:
    def __init__(self, video_path, gpx_points, output_dir, sharpness_thresh, time_offset):
        self.video_path = video_path
        self.gpx_points = gpx_points
        self.output_dir = output_dir
        self.sharpness_thresh = sharpness_thresh
        self.time_offset = time_offset
        self.executor = ThreadPoolExecutor(max_workers=4)
        
    def process_frame_batch(self, frame_batch):
        results = []
        for frame_info in frame_batch:
            frame, frame_count, current_time = frame_info
            sharpness = self.calculate_sharpness(frame)
            
            if sharpness >= self.sharpness_thresh:
                gps_data = self.get_gps_data(current_time)
                if gps_data:
                    results.append((frame, frame_count, gps_data))
        return results
    
    def get_gps_data(self, current_time):
        utc_time = current_time.astimezone(pytz.UTC)
        for i in range(len(self.gpx_points) - 1):
            if self.gpx_points[i].time <= utc_time <= self.gpx_points[i+1].time:
                ratio = (utc_time - self.gpx_points[i].time).total_seconds() / \
                       (self.gpx_points[i+1].time - self.gpx_points[i].time).total_seconds()
                
                _, lat, lon, ele = self.interpolate_coords(self.gpx_points[i], self.gpx_points[i+1], ratio)
                bearing = self.calculate_bearing(
                    self.gpx_points[i].latitude, self.gpx_points[i].longitude,
                    self.gpx_points[i+1].latitude, self.gpx_points[i+1].longitude)
                
                return {
                    'lat': lat,
                    'lon': lon,
                    'ele': ele,
                    'bearing': bearing,
                    'timestamp': current_time
                }
        return None
    
    @staticmethod
    def calculate_sharpness(image):
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        return cv2.Laplacian(gray, cv2.CV_64F).var()
    
    @staticmethod
    def interpolate_coords(point1, point2, ratio):
        time = point1.time + (point2.time - point1.time) * ratio
        lat = point1.latitude + (point2.latitude - point1.latitude) * ratio
        lon = point1.longitude + (point2.longitude - point1.longitude) * ratio
        ele = point1.elevation + (point2.elevation - point1.elevation) * ratio
        return time, lat, lon, ele
    
    @staticmethod
    def calculate_bearing(lat1, lon1, lat2, lon2):
        dlon = np.radians(lon2 - lon1)
        lat1, lat2 = np.radians(lat1), np.radians(lat2)
        y = np.sin(dlon) * np.cos(lat2)
        x = np.cos(lat1) * np.sin(lat2) - np.sin(lat1) * np.cos(lat2) * np.cos(dlon)
        bearing = np.degrees(np.arctan2(y, x))
        return (bearing + 360) % 360

def degrees_to_exif_format(decimal_degrees):
    """Convert decimal degrees to EXIF-friendly format"""
    d = int(decimal_degrees)
    m = int((decimal_degrees - d) * 60)
    s = (decimal_degrees - d - m/60) * 3600
    return ((d, 1), (m, 1), (int(s * 100), 100))

def save_image_with_exif(output_path, image, gps_data):
    """Save image with GPS and timestamp EXIF data"""
    exif_dict = {
        "GPS": {
            piexif.GPSIFD.GPSLatitudeRef: "N" if gps_data['lat'] >= 0 else "S",
            piexif.GPSIFD.GPSLatitude: degrees_to_exif_format(abs(gps_data['lat'])),
            piexif.GPSIFD.GPSLongitudeRef: "E" if gps_data['lon'] >= 0 else "W",
            piexif.GPSIFD.GPSLongitude: degrees_to_exif_format(abs(gps_data['lon'])),
            piexif.GPSIFD.GPSAltitude: (int(abs(gps_data['ele']) * 100), 100),
            piexif.GPSIFD.GPSImgDirection: (int(gps_data['bearing'] * 100), 100),
            piexif.GPSIFD.GPSImgDirectionRef: "T",
            piexif.GPSIFD.GPSDateStamp: gps_data['timestamp'].strftime("%Y:%m:%d"),
            piexif.GPSIFD.GPSTimeStamp: (
                (gps_data['timestamp'].hour, 1),
                (gps_data['timestamp'].minute, 1),
                (gps_data['timestamp'].second, 1),
            ),
        },
        "0th": {
            piexif.ImageIFD.DateTime: gps_data['timestamp'].strftime("%Y:%m:%d %H:%M:%S"),
        },
    }
    exif_bytes = piexif.dump(exif_dict)
    cv2.imwrite(output_path, image, [int(cv2.IMWRITE_JPEG_QUALITY), 95])
    piexif.insert(exif_bytes, output_path)

def calculate_auto_threshold(video_path, sample_frames=100):
    """Calculate automatic sharpness threshold"""
    cap = cv2.VideoCapture(video_path)
    sharpness_values = []
    
    for _ in range(sample_frames):
        ret, frame = cap.read()
        if not ret:
            break
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        sharpness_values.append(cv2.Laplacian(gray, cv2.CV_64F).var())
    
    cap.release()
    
    if not sharpness_values:
        raise ValueError("Could not calculate sharpness - video may be corrupted")
    
    return np.percentile(sharpness_values, 25)  # 25th percentile

def optimized_process_video(video_path, gpx_path, output_dir, frame_interval, 
                          sharpness_thresh, sync_time, is_first_frame, 
                          timezone_str='UTC', batch_size=10):
    """Optimized video processing function"""
    
    # Handle auto sharpness threshold
    if sharpness_thresh == 'auto':
        print("Calculating automatic sharpness threshold...")
        sharpness_thresh = calculate_auto_threshold(video_path)
        print(f"Using automatic threshold: {sharpness_thresh:.1f}")
    else:
        sharpness_thresh = float(sharpness_thresh)
    
    # Load GPX
    with open(gpx_path) as gpx_file:
        gpx = gpxpy.parse(gpx_file)
    points = []
    for track in gpx.tracks:
        for segment in track.segments:
            points.extend(segment.points)
    
    # Video setup
    cap = cv2.VideoCapture(video_path)
    fps = cap.get(cv2.CAP_PROP_FPS)
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    duration = total_frames / fps
    
    # Time synchronization
    video_start_time = pytz.timezone(timezone_str).localize(
        datetime.strptime(sync_time, "%Y-%m-%d %H:%M:%S"))
    if not is_first_frame:
        video_start_time -= timedelta(seconds=duration)
    
    # Create processor
    processor = FrameProcessor(
        video_path=video_path,
        gpx_points=points,
        output_dir=output_dir,
        sharpness_thresh=sharpness_thresh,
        time_offset=video_start_time
    )
    
    # Main processing loop
    os.makedirs(output_dir, exist_ok=True)
    frame_count = 0
    saved_count = 0
    batch = []
    
    with tqdm(total=total_frames, desc="Processing video") as pbar:
        while cap.isOpened():
            ret, frame = cap.read()
            if not ret:
                break
            
            current_time = video_start_time + timedelta(seconds=frame_count / fps)
            
            if frame_count % int(fps * frame_interval) == 0:
                batch.append((frame.copy(), frame_count, current_time))
                
                if len(batch) >= batch_size:
                    results = processor.process_frame_batch(batch)
                    for frame, frame_count, gps_data in results:
                        output_path = os.path.join(output_dir, f"frame_{frame_count:06d}.jpg")
                        save_image_with_exif(output_path, frame, gps_data)
                        saved_count += 1
                    batch = []
            
            frame_count += 1
            pbar.update(1)
    
    # Process remaining frames
    if batch:
        results = processor.process_frame_batch(batch)
        for frame, frame_count, gps_data in results:
            output_path = os.path.join(output_dir, f"frame_{frame_count:06d}.jpg")
            save_image_with_exif(output_path, frame, gps_data)
            saved_count += 1
    
    cap.release()
    print(f"\nProcessing complete. Saved {saved_count} frames out of {frame_count}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Optimized video frame extractor with GPS")
    parser.add_argument("--video", required=True, help="Input video file path")
    parser.add_argument("--gpx", required=True, help="GPX track file path")
    parser.add_argument("--output", default="output_frames", help="Output directory")
    parser.add_argument("--interval", type=float, default=1.0, help="Frame interval in seconds")
    parser.add_argument("--sharpness", default="100", help="Sharpness threshold or 'auto'")
    parser.add_argument("--sync-time", required=True, help="Sync time (YYYY-MM-DD HH:MM:SS)")
    parser.add_argument("--sync-first", action="store_true", help="Sync to first frame")
    parser.add_argument("--timezone", default="UTC", help="Timezone for sync time")
    parser.add_argument("--batch-size", type=int, default=10, help="Processing batch size")
    
    args = parser.parse_args()
    
    optimized_process_video(
        video_path=args.video,
        gpx_path=args.gpx,
        output_dir=args.output,
        frame_interval=args.interval,
        sharpness_thresh=args.sharpness,
        sync_time=args.sync_time,
        is_first_frame=args.sync_first,
        timezone_str=args.timezone,
        batch_size=args.batch_size
    )