MCPcopy Create free account
hub / github.com/apple/ml-pointersect / create_gif

Function create_gif

plib/render.py:467–520  ·  view source on GitHub ↗

Create a gif from the images Args: images: (n, h, w, 3) or list of (h, w, 3), float, range = 0-1 filename: filename of the output gif

(
        images: T.Union[torch.Tensor, np.ndarray, T.List[torch.Tensor], T.List[np.ndarray]],
        filename: str,
        fps: float,
        loop: bool = True,
)

Source from the content-addressed store, hash-verified

465
466
467def create_gif(
468 images: T.Union[torch.Tensor, np.ndarray, T.List[torch.Tensor], T.List[np.ndarray]],
469 filename: str,
470 fps: float,
471 loop: bool = True,
472):
473 """
474 Create a gif from the images
475
476 Args:
477 images:
478 (n, h, w, 3) or list of (h, w, 3), float, range = 0-1
479 filename:
480 filename of the output gif
481 """
482
483 assert filename.lower().endswith('gif'), f'{filename}'
484 if isinstance(images, torch.Tensor):
485 images = images.detach().cpu().numpy()
486
487 if isinstance(images, (list, tuple)):
488 images = [
489 img.detach().cpu().numpy() if isinstance(img, torch.Tensor) else img
490 for img in images]
491
492 if isinstance(images, np.ndarray):
493 images = [images[i] for i in range(images.shape[0])]
494
495 # make sure the range is 0-255
496 images = [(np.clip(img, a_min=0, a_max=1) * 255).astype(np.uint8) for img in images]
497
498 # numpy to pil image
499 images = [Image.fromarray(img) for img in images]
500
501 # avoid dithering
502 try:
503 images = [img.quantize(method=Image.Quantize.MEDIANCUT) for img in images]
504 except:
505 images = [img.quantize(method=Image.MEDIANCUT) for img in images]
506
507 # save gif
508 images[0].save(
509 filename,
510 save_all=True,
511 append_images=images[1:],
512 optimize=False,
513 duration=int((1000 + fps - 1) / fps),
514 loop=loop,
515 )
516
517 # save png for first image as a reference
518 images[0].save(
519 filename[:-4] + '_oneimg.png'
520 )
521
522
523def gif_to_nparray(

Callers

nothing calls this directly

Calls 2

detachMethod · 0.45
saveMethod · 0.45

Tested by

no test coverage detected