Upload folder using huggingface_hub
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546# SV3D-diffusers

This repo provides scripts about:
1. Spatio-temporal UNet (`SV3DUNetSpatioTemporalConditionModel`) and pipeline (`StableVideo3DDiffusionPipeline`) modified from [SVD](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py) for [SV3D](https://sv3d.github.io) in the [diffusers](https://github.com/huggingface/diffusers) convention.
2. Converting the [Stability-AI](https://github.com/Stability-AI/generative-models)'s [SV3D-p UNet checkpoint](https://huggingface.co/stabilityai/sv3d) to the [diffusers](https://github.com/huggingface/diffusers) convention.
3. Infering the `SV3D-p` model with the [diffusers](https://github.com/huggingface/diffusers) library to synthesize a 21-frame orbital video around a 3D object from a single-view image (preprocessed by removing background and centering first).
Converted SV3D-p checkpoints have been uploaded to HuggingFace🤗 [chenguolin/sv3d-diffusers](https://huggingface.co/chenguolin/sv3d-diffusers).
## 🚀 Usage
```bash
git clone https://github.com/chenguolin/sv3d-diffusers.git
# Please install PyTorch first according to your CUDA version
pip3 install -r requirements.txt
# If you can't access to HuggingFace🤗, try:
# export HF_ENDPOINT=https://hf-mirror.com
python3 infer.py --output_dir out/ --image_path assets/images/sculpture.png --elevation 10 --half_precision --seed -1
```
The synthesized video will save at `out/` as a `.gif` file.
## 📸 Results
> Image preprocessing and random seed for different implementations are different, so the results are presented only for reference.
| Implementation | sculpture | bag | kunkun |
| :------------- | :------: | :----: | :----: |
| **SV3D-diffusers (Ours)** |  |  |  |
| **Official SV3D** |  |  |  |
## 📚 Citation
If you find this repo helpful, please consider giving this repository a star 🌟 and citing the original SV3D paper.
```
@inproceedings{voleti2024sv3d,
author={Voleti, Vikram and Yao, Chun-Han and Boss, Mark and Letts, Adam and Pankratz, David and Tochilkin, Dmitrii and Laforte, Christian and Rombach, Robin and Jampani, Varun},
title={{SV3D}: Novel Multi-view Synthesis and {3D} Generation from a Single Image using Latent Video Diffusion},
booktitle={European Conference on Computer Vision (ECCV)},
year={2024},
}
```1234567891011121314151617181912345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273import gradio as grfrom infer import generate_video
def gradio_generate_video(image, elevation=10): image_path = image.name # Save the image to a temporary file image.save(image_path) # Save uploaded image to disk output_gif = generate_video(image_path=image_path, output_dir="out/", elevation=elevation) return output_gif # Return the generated video path
iface = gr.Interface( fn=gradio_generate_video, inputs=[ gr.inputs.Image(type="filepath"), gr.inputs.Slider(minimum=0, maximum=90, default=10, label="Camera Elevation"), ], outputs=gr.outputs.Video(),)
iface.launch()import os
import argparse
from PIL import Image
import numpy as np
import torch
from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
from diffusers import AutoencoderKL, EulerDiscreteScheduler
from diffusers.utils import export_to_gif
from diffusers_sv3d import SV3DUNetSpatioTemporalConditionModel, StableVideo3DDiffusionPipeline
SV3D_DIFFUSERS = "chenguolin/sv3d-diffusers"
# os.environ["HF_ENDPOINT"] = "https://hf-mirror.com"
os.environ["HF_HOME"] = "~/.cache/huggingface"
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--output_dir", default="out/", type=str, help="Output filepath")
parser.add_argument("--image_path", default="assets/img1.jpg", type=str, help="Image filepath")
parser.add_argument("--elevation", default=10, type=float, help="Camera elevation of the input image")
parser.add_argument("--half_precision", action="store_true", help="Use fp16 half precision")
parser.add_argument("--seed", default=-1, type=int, help="Random seed")
args = parser.parse_args()
unet = SV3DUNetSpatioTemporalConditionModel.from_pretrained(SV3D_DIFFUSERS, subfolder="unet")
vae = AutoencoderKL.from_pretrained(SV3D_DIFFUSERS, subfolder="vae")
scheduler = EulerDiscreteScheduler.from_pretrained(SV3D_DIFFUSERS, subfolder="scheduler")
image_encoder = CLIPVisionModelWithProjection.from_pretrained(SV3D_DIFFUSERS, subfolder="image_encoder")
feature_extractor = CLIPImageProcessor.from_pretrained(SV3D_DIFFUSERS, subfolder="feature_extractor")
pipeline = StableVideo3DDiffusionPipeline(
image_encoder=image_encoder, feature_extractor=feature_extractor,
unet=unet, vae=vae,
scheduler=scheduler,
)
num_frames, sv3d_res = 21, 576
elevations_deg = [args.elevation] * num_frames
polars_rad = [np.deg2rad(90 - e) for e in elevations_deg]
azimuths_deg = np.linspace(0, 360, num_frames + 1)[1:] % 360
azimuths_rad = [np.deg2rad((a - azimuths_deg[-1]) % 360) for a in azimuths_deg]
azimuths_rad[:-1].sort()
pipeline = pipeline.to("cuda")
with torch.no_grad():
with torch.autocast("cuda", dtype=torch.float16 if args.half_precision else torch.float32, enabled=True):
image = Image.open(args.image_path)
image.load() # required for `.split()`
if len(image.split()) == 4: # RGBA
input_image = Image.new("RGB", image.size, (255, 255, 255)) # pure white bg
input_image.paste(image, mask=image.split()[3]) # 3rd is the alpha channel
else:
input_image = image
video_frames = pipeline(
input_image.resize((sv3d_res, sv3d_res)),
height=sv3d_res,
width=sv3d_res,
num_frames=num_frames,
decode_chunk_size=8, # smaller to save memory
polars_rad=polars_rad,
azimuths_rad=azimuths_rad,
generator=torch.manual_seed(args.seed) if args.seed >= 0 else None,
).frames[0]
os.makedirs(args.output_dir, exist_ok=True)
name = os.path.basename(args.image_path).split(".")[0]
export_to_gif(video_frames, f"{args.output_dir}/{name}.gif", fps=7)
if __name__ == "__main__":
main()README.mdAdded+46
app.py+73-19