Matplotlib.animation:如何删除空白边距

问题描述 投票:7回答:4

我尝试使用matplotlib电影编写器来生成电影。如果这样做,我总是在视频周围出现空白。有谁知道如何删除该保证金?

http://matplotlib.org/examples/animation/moviewriter.html中的调整示例

# This example uses a MovieWriter directly to grab individual frames and
# write them to a file. This avoids any event loop integration, but has
# the advantage of working with even the Agg backend. This is not recommended
# for use in an interactive setting.
# -*- noplot -*-

import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as manimation

FFMpegWriter = manimation.writers['ffmpeg']
metadata = dict(title='Movie Test', artist='Matplotlib',
        comment='Movie support!')
writer = FFMpegWriter(fps=15, metadata=metadata, extra_args=['-vcodec', 'libx264'])

fig = plt.figure()
ax = plt.subplot(111)
plt.axis('off')
fig.subplots_adjust(left=None, bottom=None, right=None, wspace=None, hspace=None)
ax.set_frame_on(False)
ax.set_xticks([])
ax.set_yticks([])
plt.axis('off')

with writer.saving(fig, "writer_test.mp4", 100):
    for i in range(100):
        mat = np.random.random((100,100))
        ax.imshow(mat,interpolation='nearest')
        writer.grab_frame()
python animation video matplotlib
4个回答
11
投票

None作为争论传递给subplots_adjust并不会像您认为的那样(doc)。这意味着“使用默认值”。要执行您想要的操作,请使用以下代码:

fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None)

如果您重新使用ImageAxes对象,还可以使代码效率更高

mat = np.random.random((100,100))
im = ax.imshow(mat,interpolation='nearest')
with writer.saving(fig, "writer_test.mp4", 100):
    for i in range(100):
        mat = np.random.random((100,100))
        im.set_data(mat)
        writer.grab_frame()

默认情况下,imshow将纵横比固定为相等,即像素为正方形。您要么需要调整图形的大小以使其与图像的纵横比相同:

fig.set_size_inches(w, h, forward=True)

或告诉imshow使用任意宽高比

im = ax.imshow(..., aspect='auto')

1
投票

在最近的build of matplotlib中,您似乎可以将参数传递给编写器:

def grab_frame(self, **savefig_kwargs):
        '''
        Grab the image information from the figure and save as a movie frame.
        All keyword arguments in savefig_kwargs are passed on to the 'savefig'
        command that saves the figure.
        '''
        verbose.report('MovieWriter.grab_frame: Grabbing frame.',
                       level='debug')
        try:
            # Tell the figure to save its data to the sink, using the
            # frame format and dpi.
            self.fig.savefig(self._frame_sink(), format=self.frame_format,
                dpi=self.dpi, **savefig_kwargs)
        except RuntimeError:
            out, err = self._proc.communicate()
            verbose.report('MovieWriter -- Error running proc:\n%s\n%s' % (out,
                err), level='helpful')
            raise

如果是这种情况,您可以将bbox_inches="tight"pad_inches=0传递给grab_frame-> savefig,这将删除大部分边框。但是,Ubuntu上的最新版本仍然具有以下代码:

def grab_frame(self):
    '''
    Grab the image information from the figure and save as a movie frame.
    '''
    verbose.report('MovieWriter.grab_frame: Grabbing frame.',
                   level='debug')
    try:
        # Tell the figure to save its data to the sink, using the
        # frame format and dpi.
        self.fig.savefig(self._frame_sink(), format=self.frame_format,
            dpi=self.dpi)
    except RuntimeError:
        out, err = self._proc.communicate()
        verbose.report('MovieWriter -- Error running proc:\n%s\n%s' % (out,
            err), level='helpful')
        raise

所以它看起来像是要插入该功能。抓住这个版本,然后试一试!


0
投票

[如果您只是想保存不带轴注释的矩阵的matshow / imshow渲染,那么scikit-video(skvideo)的最新开发人员版本也可能有用-如果已安装avconv。分发中的一个示例显示了一个由numpy函数构造的动态图像:https://github.com/aizvorski/scikit-video/blob/master/skvideo/examples/test_writer.py

这是我对示例的修改:

# Based on https://github.com/aizvorski/scikit-video/blob/master/skvideo/examples/test_writer.py
from __future__ import print_function

from skvideo.io import VideoWriter
import numpy as np

w, h = 640, 480

checkerboard = np.tile(np.kron(np.array([[0, 1], [1, 0]]), np.ones((30, 30))), (30, 30))
checkerboard = checkerboard[:h, :w]

filename = 'checkerboard.mp4'
wr = VideoWriter(filename, frameSize=(w, h), fps=8)

wr.open()
for frame_num in range(300):
    checkerboard = 1 - checkerboard
    image = np.tile(checkerboard[:, :, np.newaxis] * 255, (1, 1, 3))
    wr.write(image)
    print("frame %d" % (frame_num))

wr.release()
print("done")

0
投票

我整天都在搜索此内容,并在创建每个图像时最终使用@matehat的此解决方案。

import matplotlib.pyplot as plt
import matplotlib.animation as animation

要制作没有边框的图形:

fig = plt.figure(frameon=False)
fig.set_size_inches(w,h)

使内容填满整个图形

ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)

绘制第一帧,假设电影存储在'imageStack'中:

movieImage = ax.imshow(imageStack[0], aspect='auto')

然后我写了一个动画功能:

def animate(i):
    movieImage.set_array(imageStack[i])
    return movieImage

anim = animation.FuncAnimation(fig,animate,frames=len(imageStack),interval=100)
anim.save('myMovie.mp4',fps=20,extra_args=['-vcodec','libx264']

效果很好!

这里是空白删除解决方案的链接:

[1remove whitespace from image

© www.soinside.com 2019 - 2024. All rights reserved.