用python从imges按任意顺序生成GIF

2024-04-29 13:51:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在ubuntu12.04中用python语言将png格式的图片序列做成gif。我有一个文件,里面有我的照片。它们被命名为,lip_shapes1.png到lip_shapes11.png。另外,我有一个列表,里面有图像的名称,我想在这个序列中生成gif。列表如下:

list = [lip_shapes1.png, lip_shapes4.png , lip_shapes11.png, lip_shapes3.png]

但我的问题是我发现了这个代码:

^{pr2}$

但它只按照gnp的名称顺序来制作gif,但我希望它能按我想要的任何顺序排列。有可能吗?在

如果有人能帮我,我真的很感激。在

提前谢谢

附言:我也想把它拍成电影。我尝试了以下代码(shapes是我的图像名称列表):

    s = Popen(['ffmpeg', '-f', 'image2', '-r', '24', '-i'] + shapes + ['-vcodec', 'mpeg4', '-y', 'movie.mp4'])
s.communicate()

但它在终端给了我这个但不起作用:

The ffmpeg program is only provided for script compatibility and will be removed in a future release. It has been deprecated in the Libav project to allow for incompatible command line syntax improvements in its replacement called avconv (see Changelog for details). Please use avconv instead.

Input #0, image2, from 'shz8.jpeg': Duration: 00:00:00.04, start: 0.000000, bitrate: N/A Stream #0.0: Video: mjpeg, yuvj420p, 266x212 [PAR 1:1 DAR 133:106], 24 tbr, 24 tbn, 24 tbc

shz8.jpeg是列表中的第一个名称。在

谢谢


Tags: 代码in图像名称列表forpng序列
3条回答

因此,您得到了一个图像列表,您想将其转换为gif格式的python列表。你可以按你想要的顺序来排序或排列。e、 g

img_list = ['lip_shapes1.png', 'lip_shapes4.png' , 'lip_shapes11.png', 'lip_shapes3.png'] img_list.sort()

请注意,list不应用作变量名,因为它是列表类型的名称。在

然后您可以在调用os.system(convert ...)时使用此列表,例如

os.system('convert -loop 0 %s anime.gif' % ' '.join(img_list))

你应该确保在这里处理一些事情,如果你想从一个文件夹中读取一系列png,我建议使用for循环来检查文件的结尾,例如.png、.jpg等。我写了一篇关于如何轻松做到这一点的博文(请阅读here):

image_file_names = [],[]
for file_name in os.listdir(png_dir):
    if file_name.endswith('.png'):
        image_file_names.append(file_name)
        sorted_files = sorted(image_file_names, key=lambda y: int(y.split('_')[1]))

这将把所有的“.png”文件放入一个文件名向量中。在那里,您可以循环使用以下文件来自定义gif:

^{pr2}$

下面是用上述方法生成的一个示例:

GIF Example

https://engineersportal.com/blog/2018/7/27/how-to-make-a-gif-using-python-an-application-with-the-united-states-wind-turbine-database

如果使用subprocess.call,则可以将文件名作为字符串列表传递。这将避免在文件名包含引号或空格时可能出现的shell quotation issues。在

import subprocess
shapes = ['lip_shapes1.png', 'lip_shapes4.png' , 'lip_shapes11.png', 'lip_shapes3.png']
cmd = ['convert', '-loop0'] + shapes + ['anime.gif']
retcode = subprocess.call(cmd)
if not retval == 0:
    raise ValueError('Error {} executing command: {}'.format(retcode, cmd))    

相关问题 更多 >