var arguments = $"-i "{inputFile}" -vf "scale={width}:{height}:force_original_aspect_ratio=decrease,pad={width}:{height}:(ow-iw)/2:(oh-ih)/2" -c:a copy "{outputFile}"";
как сделать чтобы он растягивал а не вставлял черные края
Assistant
В данном случае вы используете опцию pad в фильтре -vf, которая добавляет черные полосы, чтобы сохранить пропорции видео при изменении его размеров.
Чтобы вместо этого растянуть видео до новых размеров (соотношение сторон видео будет изменено), вы можете использовать только фильтр scale без сохранения аспектного соотношения.
Пример:
csharp
var arguments = $"-i \"{inputFile}\" -vf \"scale={width}:{height}\" -c:a copy \"{outputFile}\"";
Здесь:
Фильтр scale={width}:{height} сам по себе просто растянет или сожмет видео до указанных вами размеров width и height, вместо того чтобы сохранять оригинальное соотношение сторон.
Однако имейте в виду, что этот подход может исказить изображение, потому что оригинальное соотношение сторон игнорируется.
User
get video frame count without downloadingac just by url
Assistant
User
var arguments = $"-i "{inputFile}" -vf "fps=1" "{Path.Combine(outputFolder, "frame_%03d.png")}"";
why is not saving all frames
Assistant
The issue lies in the command itself: you're using the filter in the (video filter) argument. When you specify , it tells to extract from the video, rather than extracting all frames.
User
Assistant
User
make it order frames by its index all frame files are like this : frame_040.png
Assistant
To get the frame count of a video using only its URL, without downloading the entire video, you typically need to use video file metadata. This can often be achieved by accessing just the file headers via tools such as ffprobe or media-specific APIs. Here's how you can do it:
Using ffprobe (Part of FFmpeg)
With ffprobe, you can fetch video metadata without downloading the entire video file. Instead, it fetches the necessary parts of the file (e.g., headers) to extract information:
If you're working with videos hosted on platforms like YouTube, Vimeo, or cloud storage, APIs provided by those platforms can often provide detailed metadata (including frame count).
Example: YouTube Data API
For YouTube videos, you could use the YouTube Data API to get the duration of the video, and then calculate the frame count if you know the frame rate:
Fetch the video duration from the YouTube API.
Estimate frame count:
code
Frame Count = Duration (in seconds) * Frame Rate
Caveats
Range Requests Support: The server hosting the video should support partial content delivery (HTTP range requests). If the server doesn't support range requests, the entire video might be downloaded.
Accuracy: Without downloading the full video, the frame count might not be 100% accurate in some edge cases (e.g., variable frame rate videos).
Large Videos: For very large videos, ensure your approach accounts for memory and processing limitations.
If you're dealing with many videos, consider combining these approaches for efficiency.
fps=1
-vf
fps=1
ffmpeg
one frame per second
If you want to save all frames of the video as sequential image files, you should avoid limiting the frame extraction rate, and instead just let ffmpeg output every frame by default. Here's how you can fix it:
Update Your Command for Extracting All Frames
Update your command to the following:
csharp
var arguments = $"-i \"{inputFile}\" \"{Path.Combine(outputFolder, "frame_%03d.png")}\"";
Key changes:
Removed -vf "fps=1": By default, ffmpeg will process all frames if no frame rate filter is applied.
Ensured the output file name uses a sequential pattern like frame_%03d.png, where %03d ensures zero-padded frame numbers (e.g., frame_001.png, frame_002.png).
Now, ffmpeg will extract all frames from the input video and save them as PNG images in the specified output folder.
Explanation of frame_%03d.png
frame_%03d.png: This specifies the name pattern for the output image files. %03d inserts an incrementing frame index, padded to 3 digits (e.g., 001, 002, etc.).
Example output: frame_001.png, frame_002.png, frame_003.png, ...
Additional Notes
To Specify a Format: If the output format isn't determined from the file extension, you can explicitly specify the format using -f image2. For example:
csharp
var arguments = $"-i \"{inputFile}\" -f image2 \"{Path.Combine(outputFolder, "frame_%03d.png")}\"";
Frame Rate is Too High?: If the video has a very high frame rate and you don't need every frame, you can use -vf "fps={desired_frame_rate}" (e.g., fps=30 for 30 frames per second) to control the output. Example:
csharp
var arguments = $"-i \"{inputFile}\" -vf \"fps=30\" \"{Path.Combine(outputFolder, "frame_%03d.png")}\"";
Variable Frame Rates: If the video uses a variable frame rate (VFR), ffmpeg will process all available frames regardless of frame rate unless a filter (like fps=X) is explicitly applied.
Performance Note: Extracting all frames can be I/O-intensive, especially for long videos or high frame rates. Make sure your output folder has enough storage space.
By removing or adjusting the fps filter, you can ensure all frames are extracted and saved.
import json
import math
import os
import os.path as osp
from itertools import chain
import pyrallis
import torch
import torchvision.transforms as T
from PIL import Image
from torch.utils.data import DataLoader
from torchvision.transforms import InterpolationMode
from tqdm import tqdm
from diffusion.model.builder import get_vae, vae_encode
from diffusion.utils.config import SanaConfig
min_size = config.model.image_size // 2
max_size = config.model.image_size * 2
step = 32
ratios_array = []
while min_size != max_size:
width = int(preferred_pixel_count / min_size)
if width % step != 0:
mod = width % step
if mod < step // 2:
width -= mod
else:
width += step - mod
ratio = min_size / width
ratios_array.append((ratio, (int(min_size), width)))
min_size += step
def get_closest_ratio(height: float, width: float):
aspect_ratio = height / width
closest_ratio = min(ratios_array, key=lambda ratio: abs(ratio[0] - aspect_ratio))
return closest_ratio
def get_preffered_size(height: float, width: float):
pixel_count = height * width
scale = math.sqrt(pixel_count / preferred_pixel_count)
return height / scale, width / scale
class BucketsDataset(torch.utils.data.Dataset):
def __init__(self, data_dir, skip_files):
valid_extensions = {".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".webp"}
self.files = [
osp.join(data_dir, f)
for f in os.listdir(data_dir)
if osp.isfile(osp.join(data_dir, f))
and osp.splitext(f)[1].lower() in valid_extensions
and osp.join(data_dir, f) not in skip_files
]
self.transform = T.Compose(
[
T.ToTensor(),
T.Normalize([0.5], [0.5]),
]
)
def __len__(self):
return len(self.files)
def __getitem__(self, idx):
path = self.files[idx]
img = Image.open(path).convert("RGB")
ratio = get_closest_ratio(img.height, img.width)
prefsize = get_preffered_size(img.height, img.width)
crop = T.Resize(ratio[1], interpolation=InterpolationMode.BICUBIC)
return {
"img": self.transform(crop(img)),
"size": torch.tensor([ratio[1][0], ratio[1][1]]),
"prefsize": torch.tensor([prefsize[0], prefsize[1]]),
"ratio": ratio[0],
"path": path,
}
vae = get_vae(config.vae.vae_type, config.vae.vae_pretrained, "cuda").to(torch.float16)
def encode_images(batch, vae):
with torch.no_grad():
z = vae_encode(
config.vae.vae_type,
vae,
batch,
sample_posterior=config.vae.sample_posterior, # Adjust as necessary
device="cuda",
)
return z
if os.path.exists(config.data.buckets_file):
with open(config.data.buckets_file) as json_file:
buckets = json.load(json_file)
existings_images = set(chain.from_iterable(buckets.values()))
else:
buckets = {}
existings_images = set()
def add_to_list(key, item):
if key in buckets:
buckets[key].append(item)
else:
buckets[key] = [item]
for path in config.data.data_dir:
print(f"Processing {path}")
dataset = BucketsDataset(path, existings_images)
dataloader = DataLoader(dataset, batch_size=1)
for batch in tqdm(dataloader):
img = batch["img"]
size = batch["size"]
ratio = batch["ratio"]
image_path = batch["path"]
prefsize = batch["prefsize"]
encoded = encode_images(img.to(torch.half), vae)
for i in range(0, len(encoded)):
filename_wo_ext = os.path.splitext(os.path.basename(image_path[i]))[0]
add_to_list(str(ratio[i].item()), image_path[i])
torch.save(
{"img": encoded[i].detach().clone(), "size": size[i], "prefsize": prefsize[i], "ratio": ratio[i]},
f"{path}/{filename_wo_ext}_img.npz",
)
with open(config.data.buckets_file, "w") as json_file:
json.dump(buckets, json_file, indent=4)
for ratio in buckets.keys():
print(f"{float(ratio):.2f}: {len(buckets[ratio])}")
if name == "main":
main()
change it so it processes folder that contains folders with video frames, it should load frames (all frames are 512x512), pass them though vae and concat into single tensor and save it to root dir with subfolder.npz name
Here is the modified script to process a folder that contains subfolders of video frames. The script will:
Load all frames (512x512 resolution) from each subfolder.
Pass the frames through the VAE model.
Concatenate the processed frames into a single tensor.
Save this tensor into the root directory under the name <subfolder_name>.npz.
python
import json
import math
import os
import os.path as osp
from itertools import chain
import pyrallis
import torch
import torchvision.transforms as T
from PIL import Image
from torch.utils.data import DataLoader
from torchvision.transforms import InterpolationMode
from tqdm import tqdm
from diffusion.model.builder import get_vae, vae_encode
from diffusion.utils.config import SanaConfig
@pyrallis.wrap()
def main(config: SanaConfig) -> None:
# Define the dataset for frames
class FramesDataset(torch.utils.data.Dataset):
def __init__(self, frames_dir):
valid_extensions = {".png", ".jpg", ".jpeg"}
self.files = sorted(
[
osp.join(frames_dir, f)
for f in os.listdir(frames_dir)
if osp.isfile(osp.join(frames_dir, f))
and osp.splitext(f)[1].lower() in valid_extensions
]
)
self.transform = T.Compose(
[
T.ToTensor(),
T.Normalize([0.5], [0.5]),
]
)
def __len__(self):
return len(self.files)
def __getitem__(self, idx):
path = self.files[idx]
img = Image.open(path).convert("RGB")
return self.transform(img), path # Return the transformed image and its path
# Load the VAE model
vae = get_vae(config.vae.vae_type, config.vae.vae_pretrained, "cuda").to(torch.float16)
def encode_images(batch, vae):
with torch.no_grad():
z = vae_encode(
config.vae.vae_type,
vae,
batch,
sample_posterior=config.vae.sample_posterior, # Adjust as necessary
device="cuda",
)
return z
root_dir = config.data.data_dir
output_dir = config.data.output_dir
os.makedirs(output_dir, exist_ok=True)
# Process each subfolder of frames
for subfolder in os.listdir(root_dir):
subfolder_path = osp.join(root_dir, subfolder)
if not osp.isdir(subfolder_path):
continue # Skip non-directory files
print(f"Processing folder: {subfolder}")
dataset = FramesDataset(subfolder_path)
dataloader = DataLoader(dataset, batch_size=16) # Use a reasonable batch size
all_encoded_frames = []
for batch in tqdm(dataloader, desc=f"Encoding frames in {subfolder}"):
imgs, paths = batch
# Pass the batch through the VAE
encoded = encode_images(imgs.to(torch.half).cuda(), vae)
# Collect the encoded frames
all_encoded_frames.append(encoded.cpu())
# Concatenate all encoded frames into a single tensor
all_encoded_frames = torch.cat(all_encoded_frames, dim=0)
# Save the tensor to a .npz file in the root directory
output_path = osp.join(output_dir, f"{subfolder}.npz")
torch.save({"encoded_frames": all_encoded_frames}, output_path)
print(f"Saved encoded frames for {subfolder} to {output_path}")
if __name__ == "__main__":
main()
Key Updates
FramesDataset Class:
Modified to take a directory of video frames (all assumed to be 512x512).
Filters valid image files and loads them.
Batch Processing Subfolders:
Iterates over subdirectories in the root folder.
Processes frames from each subfolder separately.
Concatenation:
Encoded frames for each subfolder are gathered as a list (all_encoded_frames).
They are concatenated into a single tensor using torch.cat().
Save Output:
The output for each subfolder is saved as <subfolder_name>.npz in the specified output_dir.
The output_dir is created if it doesn’t already exist.
Batch Size:
A default batch size of 16 is used when loading frames into the VAE to improve performance (configurable as needed).
Configuration Example
Here’s how your config file (e.g., SanaConfig) should look:
yaml
data:
data_dir: "/path/to/root/folder" # Root folder containing subfolders of frames.
output_dir: "/path/to/output/folder" # Directory where .npz files will be saved.
vae:
vae_type: "your_vae_type"
vae_pretrained: "/path/to/vae_pretrained/model.pt"
sample_posterior: False # Modify as needed
model:
image_size: 512 # Assumes frames are 512x512
Expected Output
For each subfolder in /path/to/root/folder, an .npz file named <subfolder_name>.npz will be saved in /path/to/output/folder. These files will contain the concatenated encoded tensors of all frames in the respective subfolder.
To ensure that the frames are ordered by their index (e.g., frame_001.png, frame_040.png), you'll need to sort the file paths based on the numerical index extracted from the file names. Below is the updated script:
Updated Script with Frame Index Sorting
python
import json
import os
import os.path as osp
import re
import pyrallis
import torch
import torchvision.transforms as T
from PIL import Image
from torch.utils.data import DataLoader
from tqdm import tqdm
from diffusion.model.builder import get_vae, vae_encode
from diffusion.utils.config import SanaConfig
@pyrallis.wrap()
def main(config: SanaConfig) -> None:
# Define the dataset for frames
class FramesDataset(torch.utils.data.Dataset):
def __init__(self, frames_dir):
valid_extensions = {".png", ".jpg", ".jpeg"}
self.files = sorted(
[
osp.join(frames_dir, f)
for f in os.listdir(frames_dir)
if osp.isfile(osp.join(frames_dir, f))
and osp.splitext(f)[1].lower() in valid_extensions
],
key=lambda x: int(re.search(r"frame_(\d+)", osp.basename(x)).group(1)),
)
self.transform = T.Compose(
[
T.ToTensor(),
T.Normalize([0.5], [0.5]),
]
)
def __len__(self):
return len(self.files)
def __getitem__(self, idx):
path = self.files[idx]
img = Image.open(path).convert("RGB")
return self.transform(img), path # Return the transformed image and its path
# Load the VAE model
vae = get_vae(config.vae.vae_type, config.vae.vae_pretrained, "cuda").to(torch.float16)
def encode_images(batch, vae):
with torch.no_grad():
z = vae_encode(
config.vae.vae_type,
vae,
batch,
sample_posterior=config.vae.sample_posterior, # Adjust as necessary
device="cuda",
)
return z
root_dir = config.data.data_dir
output_dir = config.data.output_dir
os.makedirs(output_dir, exist_ok=True)
# Process each subfolder of frames
for subfolder in os.listdir(root_dir):
subfolder_path = osp.join(root_dir, subfolder)
if not osp.isdir(subfolder_path):
continue # Skip non-directory files
print(f"Processing folder: {subfolder}")
dataset = FramesDataset(subfolder_path)
dataloader = DataLoader(dataset, batch_size=16) # Use a reasonable batch size
all_encoded_frames = []
for batch in tqdm(dataloader, desc=f"Encoding frames in {subfolder}"):
imgs, paths = batch
# Pass the batch through the VAE
encoded = encode_images(imgs.to(torch.half).cuda(), vae)
# Collect the encoded frames
all_encoded_frames.append(encoded.cpu())
# Concatenate all encoded frames into a single tensor
all_encoded_frames = torch.cat(all_encoded_frames, dim=0)
# Save the tensor to a .npz file in the root directory
output_path = osp.join(output_dir, f"{subfolder}.npz")
torch.save({"encoded_frames": all_encoded_frames}, output_path)
print(f"Saved encoded frames for {subfolder} to {output_path}")
if __name__ == "__main__":
main()
Key Changes
Frame Index Sorting:
The FramesDataset class sorts the image files based on their numerical index extracted from the filename.
The sorted() function uses a key that extracts the index with a regular expression (re.search(r"frame_(\d+)", ...)).
For example:
frame_001.png → index 1
frame_040.png → index 40
Ensures files are sorted in ascending order based on the frame number.
Regular Expression for Index Extraction:
The re.search(r"frame_(\d+)", osp.basename(x)) pattern matches the number part of filenames like frame_001.png or frame_040.png.
It extracts the number in the filename (e.g., 001, 040) as an integer to avoid problems with lexicographic sorting (e.g., 10 coming before 2).
Concatenation:
The encoded frames are concatenated into a single tensor after processing all frames in the folder.