[英]How do I convert a numpy array to a gif?
Suppose I have a 4D numpy
array where the 3D subarrays are RGB images.假设我有一个 4D
numpy
阵列,其中 3D 子阵列是 RGB 图像。 How do I convert this to a gif?如何将其转换为 gif? I would prefer to only depend on well-known Python image processing libraries.
我宁愿只依赖著名的 Python 图像处理库。
Sample data:样本数据:
import numpy as np
imgs = np.random.randint(0, 255, (100, 50, 50, 3), dtype=np.uint8)
This is straightforward using PIL
:使用
PIL
很简单:
import numpy as np
from PIL import Image
imgs = np.random.randint(0, 255, (100, 50, 50, 3), dtype=np.uint8)
imgs = [Image.fromarray(img) for img in imgs]
# duration is the number of milliseconds between frames; this is 40 frames per second
imgs[0].save("array.gif", save_all=True, append_images=imgs[1:], duration=50, loop=0)
You can also use ImageMagick and OpenCV to make a GIF from a set of images.您还可以使用 ImageMagick 和 OpenCV 从一组图像中制作 GIF。
def create_gif(inputPath, outputPath, delay, finalDelay, loop):
# grab all image paths in the input directory
imagePaths = sorted(list(paths.list_images(inputPath)))
# remove the last image path in the list
lastPath = imagePaths[-1]
imagePaths = imagePaths[:-1]
# construct the image magick 'convert' command that will be used
# generate our output GIF, giving a larger delay to the final
# frame (if so desired)
cmd = "convert -delay {} {} -delay {} {} -loop {} {}".format(
delay, " ".join(imagePaths), finalDelay, lastPath, loop,
outputPath)
os.system(cmd)
You can refer to this tutorial of pyimagesearch for more clarity.您可以参考pyimagesearch的本教程以获得更清晰的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.