我正在尝试在GUI中实现一个选项,以保存使用matplotlib显示的图像序列。代码看起来像这样:
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import \
FigureCanvasQTAgg as FigureCanvas
from matplotlib.animation import FuncAnimation
from PIL import Image
plt.rcParams['savefig.bbox'] = 'tight'
class Printer:
def __init__(self,data):
self.fig,self.ax = plt.subplots()
self.canvas = FigureCanvas(self.fig)
# some irrelevant color adjustment here
#self.ax.spines['bottom'].set_color('#f9f2d7')
#self.ax.spines['top'].set_color('#f9f2d7')
#self.ax.spines['right'].set_color('#f9f2d7')
#self.ax.spines['left'].set_color('#f9f2d7')
#self.ax.tick_params(axis='both',colors='#f9f2d7')
#self.ax.yaxis.label.set_color('#f9f2d7')
#self.ax.xaxis.label.set_color('#f9f2d7')
#self.fig.subplots_adjust(left=0.1,right=0.975,bottom=0.09,top=0.98)
self.fig.patch.set_alpha(0)
self.fig.patch.set_visible(False)
self.canvas.setStyleSheet("background-color:transparent;")
self.fig.set_size_inches(10,10,True)
self.fig.tight_layout()
self.data = data
self.image_artist = self.ax.imshow(data[0])
def animate(self,i):
self.image_artist.set_data(self.data[i])
self.canvas.draw()
def save_animation():
data = [
Image.open("test000.png"),Image.open("test001.png"),]
file = 'test.gif'
printer = Printer(data)
ani = FuncAnimation(
printer.fig,printer.animate,interval=100,frames=len(data),)
# writer = animation.writers['pillow'](bitrate=1000)
ani.save(
file,writer='pillow',savefig_kwargs={'transparent': True,'bbox_inches': 'tight'}
)
save_animation()
透明度:
如您所见,我已经尝试了其他地方(1,2)中建议的几种不同方法,但是没有找到解决方案。所有设置和参数patch.set_alpha(0)
,patch.set_visible(False)
,canvas.setStyleSheet("background-color:transparent;")
,savefig_kwargs={'transparent': True}
似乎对透明度完全没有影响。我找到了this个帖子,但没有使代码正常工作(我不得不注释掉此%matplotlib inline
,但是后来在MovieWriter.cleanup {{1} }。 Here,有人建议这实际上是一个错误,但是建议的workaroud对我不起作用,因为我不得不依靠第三方软件。还存在this bug report,据说该问题已解决,因此也许无关。
紧凑的布局
我实际上并没有找到太多,但是我尝试过的所有事情(out = TextIOWrapper(BytesIO(out)).read() TypeError: a bytes-like object is required,not 'str'
,plt.rcParams['savefig.bbox'] = 'tight'
,fig.tight_layout()
)都没有效果,甚至被主动丢弃了对于savefig_kwargs={'bbox_inches': 'tight'}
。如何运作?
高质量
由于我无法使用bbox_inches argument
并且无法使ImageMagick
正常工作(请参见下文),因此我依靠pillow保存动画。但是我可以传递的关于质量的唯一论点似乎是ffmpeg
,它没有任何作用。文件仍然具有相同的大小,动画看起来仍然像糊糊。我发现提高分辨率的only way是使用bitrate
,但这仍然不能改善动画的整体品质。看起来还是不好。我看到您可以传递fig.set_size_inches(10,True)
和codec
,所以也许这可能有所帮助,但是我不知道如何使用它们,因为我找不到带有允许参数的列表。
ffmpeg
我无法使ffmpeg正常工作。我从here安装了python程序包,并将其导入到python会话中,但我不知道如何使matplotlib可以使用它。我还从here(Windows 64位版本)中获取了ffmpeg,并将extra_args
设置为保存文件的位置(没有运行intaller,不确定我是否正确执行了该操作)。但这也无济于事。当然,这也是第三方软件,因此,如果其他人使用我的代码/程序,它将无法正常工作。