Last active
November 22, 2023 04:59
-
-
Save aredden/e4b098e0939e87d5f924998113a4bb95 to your computer and use it in GitHub Desktop.
Rotate an image and save as a gif using pytorch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import torch | |
from torchvision.transforms import functional as F | |
from PIL import Image | |
image_path = "./117.webp" | |
num_images = 32 | |
total_rot = 360 | |
rot_step = total_rot / num_images | |
im = torch.as_tensor(np.asarray(Image.open(image_path)))[None].float() | |
if im.shape[-1] == 4: | |
mask = im[:, :, :, -1] | |
mask = (mask / 255).clamp(0, 1).unsqueeze(-1) | |
im = (im[:, :, :, :3] * mask).div(255).clamp(0, 1).permute(0, 3, 1, 2) | |
else: | |
im = im.div(255).clamp(0, 1).permute(0, 3, 1, 2) | |
shp = min(im.shape[-2:]) | |
ims = [] | |
for i in range(num_images): | |
im_rot = F.rotate(im.clone(), rot_step * i) | |
ims.append(im_rot) | |
pils = [] | |
for i in range(num_images): | |
im_pil = F.to_pil_image((F.center_crop(ims[i][0], shp) * 255).clamp(0, 255).byte()) | |
pils.append(im_pil) | |
pils[0].save("rot.gif", save_all=True, append_images=pils[1:], duration=2, loop=0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment