70 lines
2.5 KiB
Python
70 lines
2.5 KiB
Python
import os
|
|
import random
|
|
import cv2
|
|
|
|
def extract_random_frames(video_path, output_dir, num_frames=500):
|
|
# Ensure output directory exists
|
|
os.makedirs(output_dir, exist_ok=True)
|
|
|
|
# Open the video file
|
|
cap = cv2.VideoCapture(video_path)
|
|
if not cap.isOpened():
|
|
print(f"Error: Gagal membuka video '{video_path}'")
|
|
return
|
|
|
|
# Get total number of frames
|
|
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
|
fps = cap.get(cv2.CAP_PROP_FPS)
|
|
duration_sec = total_frames / fps if fps > 0 else 0
|
|
|
|
print(f"Video Info:")
|
|
print(f" - Path: {video_path}")
|
|
print(f" - Total Frame: {total_frames}")
|
|
print(f" - FPS: {fps:.2f}")
|
|
print(f" - Durasi: {duration_sec:.2f} detik (~{duration_sec/60:.2f} menit)")
|
|
print(f" - Mengambil {num_frames} frame secara acak...\n")
|
|
|
|
if total_frames < num_frames:
|
|
print(f"Warning: Total frame pada video ({total_frames}) lebih kecil dari jumlah frame yang diminta ({num_frames}).")
|
|
print("Akan mengekstrak semua frame yang tersedia.")
|
|
selected_frames = list(range(total_frames))
|
|
else:
|
|
# Select 500 unique random frames
|
|
selected_frames = random.sample(range(total_frames), num_frames)
|
|
|
|
# Sort the indices so we seek sequentially (faster and more stable)
|
|
selected_frames.sort()
|
|
|
|
count = 0
|
|
for idx, frame_id in enumerate(selected_frames):
|
|
# Set the frame position
|
|
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_id)
|
|
ret, frame = cap.read()
|
|
|
|
if not ret:
|
|
print(f"Warning: Gagal membaca frame ke-{frame_id}. Mencoba membaca frame selanjutnya...")
|
|
# Try reading the next frame sequentially
|
|
ret, frame = cap.read()
|
|
if not ret:
|
|
print(f"Error: Tetap gagal membaca frame setelah frame ke-{frame_id}. Melewati...")
|
|
continue
|
|
|
|
# Save frame as image
|
|
output_filename = os.path.join(output_dir, f"frame_{frame_id:06d}.jpg")
|
|
cv2.imwrite(output_filename, frame)
|
|
count += 1
|
|
|
|
# Print progress every 50 frames or at the end
|
|
if count % 50 == 0 or count == len(selected_frames):
|
|
print(f"Progress: [{count}/{len(selected_frames)}] Berhasil mengekstrak {output_filename}")
|
|
|
|
cap.release()
|
|
print(f"\nSelesai! Berhasil mengekstrak {count} frame acak ke folder '{output_dir}'.")
|
|
|
|
if __name__ == "__main__":
|
|
video_file = "0727.mp4"
|
|
output_directory = "extracted_frames"
|
|
number_of_frames = 500
|
|
|
|
extract_random_frames(video_file, output_directory, number_of_frames)
|