OpenFakeDemo / app /video.py
vicliv's picture
added gifs support
fce55e7
import io
import cv2
import numpy as np
from PIL import Image, ImageSequence
def sample_gif_frames(data: bytes, n_frames: int = 5) -> list[Image.Image]:
"""Sample n_frames uniformly from a GIF. Returns RGB PIL images."""
gif = Image.open(io.BytesIO(data))
frames = list(ImageSequence.Iterator(gif))
total = len(frames)
if total == 0:
raise ValueError("GIF has no frames")
n = min(n_frames, total)
indices = np.linspace(0, total - 1, n, dtype=int)
return [frames[int(i)].convert("RGB") for i in indices]
def sample_frames(video_path: str, n_frames: int = 5) -> list[Image.Image]:
"""Sample n_frames uniformly across the video. Returns RGB PIL images."""
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise ValueError("Could not open video file")
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if total <= 0:
cap.release()
raise ValueError("Video has no readable frames")
n = min(n_frames, total)
indices = np.linspace(0, total - 1, n, dtype=int)
frames = []
for idx in indices:
cap.set(cv2.CAP_PROP_POS_FRAMES, int(idx))
ok, frame = cap.read()
if not ok:
continue
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frames.append(Image.fromarray(frame))
cap.release()
if not frames:
raise ValueError("No frames could be decoded from video")
return frames