假設我使用以下方法創建了三個影像。然后我想將這三個影像組合成一個 GIF 并顯示 GIF(jupyter notebook,python 3)。我在網上和 stackoverflow 看到的所有創建 GIF 的方法都包括將影像保存為檔案然后匯入它們。例如,這個執行緒。但是有沒有辦法只生成一個 gif 而不必保存/匯入影像檔案?那么,在下面的代碼中,使用三個版本的im=Image.fromarray(arr.astype('uint8'))生成圖片來現場創建gif呢?
import numpy as np
from PIL import Image
arr = np.random.randint(low = 0, high = 255, size = (300, 300, 3))
im = Image.fromarray(arr.astype('uint8'))
im.show()
uj5u.com熱心網友回復:
我猜你需要這樣的東西。GIF 是一種影像檔案型別,因此您必須保存它才能擁有它。
#! /usr/bin/env python3
import numpy as np
from PIL import Image
im = []
for n in range(20):
arr = np.random.randint(low = 0, high = 255, size = (300, 300, 3))
im.append(Image.fromarray(arr.astype('uint8')))
im[0].save('im.gif', save_all=True, append_images=im[1:], optimize=False, duration=200, loop=0)
#im[0].show()
然后im.gif使用瀏覽器或一些可以顯示影片 GIF 的應用程式打開。
如果你真的不想保存 GIF 而只是顯示它,你可以這樣做
#! /usr/bin/env python3
import base64
import io
import numpy as np
from PIL import Image
from viaduc import Viaduc
im = []
for n in range(20):
arr = np.random.randint(low = 0, high = 255, size = (300, 300, 3))
im.append(Image.fromarray(arr.astype('uint8')))
buffer = io.BytesIO()
im[0].save(buffer, format='GIF', save_all=True, append_images=im[1:], optimize=False, duration=200, loop=0)
buffer.seek(0)
data_uri = base64.b64encode(buffer.read()).decode('ascii')
class Presentation(Viaduc.Presentation):
width = 300
height = 300
title = 'gif'
html = '''
<!DOCTYPE html>
<head>
{{bootstrap_meta}} {{bootstrap_css}}
<title>{{title}}</title>
</head>
<body>
<img src="data:image/gif;base64,''' data_uri '''">
{{bootstrap_js}}
</body>
</html>
'''
if __name__ == '__main__':
Viaduc(presentation=Presentation())
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/493988.html
標籤:Python 图片 麻木的 jupyter-笔记本 gif
