2016-07-16 79 views
2

我寫了一個kivy應用程序來在Linux服務器上渲染一些動畫。 是否有直接將動畫轉換爲視頻文件的好方法?如何將kivy轉換爲視頻文件

目前我嘗試了Xvfb + ffmpeg方法。然而它有一些我想避免的問題,比如:

  • ffmpeg還會在動畫開始之前記錄空的x-windows桌面。

回答

3

可以以微件保存到一個圖像文件每幀後,然後使用工具建立像ffmpegcv2庫中的影片使用kivy.uix.widget.Widget.export_to_png,但會因爲數據保存到磁盤tooks時間減慢動畫速度。因此,這裏的另一種方法:

from functools import partial 

from kivy.app import App 
from kivy.uix.floatlayout import FloatLayout 
from kivy.lang import Builder 
from kivy.animation import Animation 
from kivy.graphics import Fbo, ClearColor, ClearBuffers, Scale, Translate 

Builder.load_string(''' 
<MyWidget>: 
    Button: 
     size_hint: 0.4, 0.2 
     pos_hint: {'center_x' : 0.5, 'center_y' : 0.5} 
     text: 'click me' 
     on_press: root.click_me(args[0]) 
''') 

class MyWidget(FloatLayout): 
    def click_me(self, button, *args):  
     anim = Animation(
      size_hint = (0.8, 0.4) 
     ) 

     textures = [] 
     anim.bind(on_complete=partial(self.save_video, textures)) 
     anim.bind(on_progress=partial(self.save_frame, textures))    

     anim.start(button) 

    # modified https://github.com/kivy/kivy/blob/master/kivy/uix/widget.py#L607 
    def save_frame(self, textures, *args): 
     if self.parent is not None: 
      canvas_parent_index = self.parent.canvas.indexof(self.canvas) 
      if canvas_parent_index > -1: 
       self.parent.canvas.remove(self.canvas) 

     fbo = Fbo(size=self.size, with_stencilbuffer=True) 

     with fbo: 
      ClearColor(0, 0, 0, 1) 
      ClearBuffers() 
      Scale(1, -1, 1) 
      Translate(-self.x, -self.y - self.height, 0) 

     fbo.add(self.canvas) 
     fbo.draw() 
     textures.append(fbo.texture) # append to array instead of saving to file 
     fbo.remove(self.canvas) 

     if self.parent is not None and canvas_parent_index > -1: 
      self.parent.canvas.insert(canvas_parent_index, self.canvas) 

     return True   

    def save_video(self, textures, *args): 
     for i, texture in enumerate(textures): 
      texture.save("frame{:03}.png".format(i), flipped=False)  

class MyApp(App): 
    def build(self):   
     return MyWidget() 

if __name__ == '__main__': 
    MyApp().run() 

我修改export_to_png方法,所以它不會試圖挽救紋理到文件,而是它它附加到一個列表。然後當動畫結束時,我將所有數據保存到單獨的圖像中。添加某種「動畫節省...」模式會很好,因爲在此期間應用程序的響應速度較慢。

相關問題