这个答案结合了关于读取视频文件并将其在内存中转换为gif以及如何在Jupyter环境中显示此bytes对象的多个答案。很抱歉,我无法再次找到我使用的所有资源。
import imageio
import skimage
import cv2
from IPython.display import Image
from io import BytesIO
file = "video.mkv"
capture = cv2.VideoCapture(file)
frames = list()
for frame_no in range(10):
capture.set(1, frame_no)
ret, frame = capture.read()
assert ret
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frames.append(frame)
gif_file = BytesIO()
imageio.mimsave(gif_file, [skimage.img_as_ubyte(frame) for frame in frames], 'GIF', fps=2)
Image(data=gif_file.getvalue())