首页 > 解决方案 > 在 matplotlib 中使用 ffmpeg 制作动画时“系统找不到指定的文件”

问题描述

我正在尝试使用我在家用计算机(Windows 10)上的另一台计算机(Mac)上使用过的函数从一堆 numpy 数组生成电影。这是我正在使用的功能:

def make_animation(frames,name): 

    plt.rcParams['animation.ffmpeg_path'] = u'C:\ffmpeg-20190320-0739d5c-win64-static\bin\ffmpeg.exe' 
    n_images=frames.shape[2] 
    assert (n_images>1)   
    figsize=(10,10)
    fig, ax = plt.subplots(figsize=figsize)
    fig.tight_layout()
    fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None)
    #lineR, = ax.plot(xaxis_data[0],R_data[0],'c-',label="resources")
    img = ax.imshow(frames[:,:,0], animated = True)   


    def updatefig(img_num): 

        #lineR.set_data(xaxis_data[img_num],R_data[img_num],'r-')

        img.set_data(frames[:,:,img_num])

        return [img]


    ani = animation.FuncAnimation(fig, updatefig, np.arange(1, n_images), interval=50, blit=True)
    mywriter = animation.FFMpegWriter(fps = 20)
    #ani.save('mymovie.mp4',writer=mywriter)

    ani.save(f"D:\{name}.mp4",writer=mywriter)

    plt.close(fig)

这是我得到的错误:

Traceback (most recent call last):

  File "<ipython-input-48-8861d4da3f36>", line 1, in <module>
    make_animation(stack,'full_test')

  File "<ipython-input-47-0e3683911f60>", line 27, in make_animation
    ani.save(f"D:\{name}.mp4",writer=mywriter)

  File "C:\Users\~snip~\Anaconda3\lib\site-packages\matplotlib\animation.py", line 1136, in save
    with writer.saving(self._fig, filename, dpi):

  File "C:\Users\~snip~\Anaconda3\lib\contextlib.py", line 112, in __enter__
    return next(self.gen)

  File "C:\Users\~snip~\Anaconda3\lib\site-packages\matplotlib\animation.py", line 228, in saving
    self.setup(fig, outfile, dpi, *args, **kwargs)

  File "C:\Users\~snip~\Anaconda3\lib\site-packages\matplotlib\animation.py", line 352, in setup
    self._run()

  File "C:\Users\~snip~\Anaconda3\lib\site-packages\matplotlib\animation.py", line 363, in _run
    creationflags=subprocess_creation_flags)

  File "C:\Users\~snip~\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 143, in __init__
    super(SubprocessPopen, self).__init__(*args, **kwargs)

  File "C:\Users\~snip~\Anaconda3\lib\subprocess.py", line 775, in __init__
    restore_signals, start_new_session)

  File "C:\Users\~snip~\Anaconda3\lib\subprocess.py", line 1178, in _execute_child
    startupinfo)

FileNotFoundError: [WinError 2] The system cannot find the file specified

我知道这段代码基本上可以工作,因为我之前在另一台计算机上使用过它。我的猜测是有关 ffmpeg 的某些东西搞砸了,或者有关输出路径的某些东西是错误的。我不确定 ffmpeg 可能有什么问题,因为我肯定已经安装了它(通过 conda),而且路径非常简单。另一方面,我不确定输出路径可能有什么问题。

标签: pythonwindowsmatplotlibffmpeg

解决方案


我相信在这种情况下是因为文件路径错误。

使用我在另一台计算机(Mac)上使用过的功能

所以我相信以前的文件路径是用/. 现在您将其更改为,\因为 Windows 使用不同的分隔符。好像没问题?

不。

因为在 python 和大多数编程语言中,\是字符串的保留标志指示符。例如\n表示新行。因此,您应该使用\\代替,例如"D:\\{name}.mp4"代替""D:\{name}.mp4.

您可以使用的另一件事是os.path.join,示例可以在

https://www.geeksforgeeks.org/python-os-path-join-method/

但在这种情况下,您会希望您的文件位于相同的路径中,至少是相同的相对路径。


推荐阅读