Skip to content

Instantly share code, notes, and snippets.

@austinbhale
Created July 16, 2024 19:27
Show Gist options
  • Save austinbhale/370b69891c651376a14113597c3ad717 to your computer and use it in GitHub Desktop.
Save austinbhale/370b69891c651376a14113597c3ad717 to your computer and use it in GitHub Desktop.
FFMPEG: Detect and save the frame with the minimum blur value within a time range
import os
import re
import subprocess
def get_blur_values(video_path, start_time, duration):
command = [
"ffmpeg",
"-i", video_path,
"-vf", f"blurdetect=block_width=32:block_height=32,metadata=print:file=-",
"-ss", str(start_time),
"-t", str(duration),
"-f", "null", "-"
]
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
return result.stdout
def parse_blur_values(blur_data):
blur_values = []
pattern = re.compile(r'frame:\d+\s+pts:\d+\s+pts_time:(\d+\.\d+)\n.*?lavfi.blur=(\d+\.\d+)')
matches = pattern.findall(blur_data)
for match in matches:
time_in_seconds = float(match[0])
blur_value = float(match[1])
blur_values.append((time_in_seconds, blur_value))
return blur_values
def find_minimum_blur_frame(blur_values):
return min(blur_values, key=lambda x: x[1])
def save_frame_as_png(video_path, time, output_path):
command = [
"ffmpeg",
"-i", video_path,
"-vf", f"select='eq(n\\,{int(time * 30)})'",
"-vsync", "vfr",
output_path
]
subprocess.run(command)
def main(video_path, start_time, duration, output_path):
blur_data = get_blur_values(video_path, start_time, duration)
blur_values = parse_blur_values(blur_data)
if blur_values:
min_blur_time, min_blur_value = find_minimum_blur_frame(blur_values)
save_frame_as_png(video_path, min_blur_time, output_path)
print(f"Saved frame with lowest blur value at time {min_blur_time}s to {output_path}")
else:
print("No blur values found in the specified time range.")
if __name__ == "__main__":
video_path = "test.mp4"
start_time = 0 # Start time in seconds
duration = 3 # Duration in seconds
output_path = "nonblurred/output.png"
if not os.path.exists("nonblurred"):
os.makedirs("nonblurred")
main(video_path, start_time, duration, output_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment