Newest 'ffmpeg' Questions - Stack Overflow

http://stackoverflow.com/questions/tagged/ffmpeg

Les articles publiés sur le site

  • ffmpeg convert RTSP MPEG4 to h.264 RTSP

    24 août 2017, par martyn

    I'm trying to convert a MPEG4 RTSP stream to a H.265 stream using ffmpeg on windows 7.

    When I run ffprobe on the native stream I get the follow result:

    Input #0, rtsp, from 'rtsp://192.168.2.207/VideoInput/1/mpeg4/1': Metadata: title : MC153906N015_Camera_1 Duration: N/A, start: 0.040000, bitrate: N/A Stream #0:0: Video: mpeg4 (Simple Profile), yuv420p, 1920x1080 [SAR 1:1 DAR 16:9], 25 fps, 25 tbr, 90k tbn, 1k tbc

    When I run the following command string I cant connect to it using VLC player or any other application:

    C:\Users\Martyn>ffmpeg -re -i rtsp://192.168.2.207/VideoInput/1/mpeg4/1 -pix_fmt yuv420p -c:v libx264 -preset ultrafast -profile baseline -crf 18 -f h264 udp://192.168.0.2:8000

    Is there anything I'm doing wrong here?

  • Encoding with FFMPEG stretches frames

    24 août 2017, par micropro.cz

    I am trying to encode video with FFMPEG into H.265, but I have a problem with a weird stretching. Input video is 1920x1080 and output has the same resolution, but when I compare both images on same timestamp, encoded video seems to be stretched by few pixels (it is visibly wider on both sizes despite the fact resolution is same). It seems that this stretching introduces ugly bluriness in whole video. It seems like FFMPEG crop few pixels from left and right (probably black pixels at the edge of video) and stretches content to fill those missing pixels and preserve same resolution.

    I did not find any way how to disable this behavior. I tried to change encoder from x265 to x264 to see if that is the problem, but result was still stretched.

    I used this command line parameters:

    ffmpeg -i input.mkv -c:v libx265 -preset medium -crf 23 -t 30 output.mp4
    

    -t 30 is there to test result visual quality on small sample of length 30 seconds.

    Does anyone have any idea why this happens and how to fix it? Most visual quality is lost because of this deformation and not because of recompression, which I proved by encoding with -crf 0, which is basically lossless and result was still blurred.

    EDIT: Link to full console output: https://pastebin.com/gpMD5Qec

  • Exception in Tkinter callback while saving animation with matplotlib

    24 août 2017, par paul

    I'm a little hesitant about asking this, since there seem to be many "Exception in Tkinter callback" questions, but I cannot find one that fits the problem I have here.

    I am trying to save an MP4 animation (of a percolation simulation) using matplotlib with ffmpeg. The code works fine on my home laptop, but not on my work PC. It also works fine if I replace the anim.save line with plt.show(), but I do want to save the animation. I'm using Python 3.5.2 on Ubuntu 17.04 (and I have ffmpeg installed).

    Here is the error:

    >>> Exception in Tkinter callback
    Traceback (most recent call last):
      File "/usr/lib/python3.5/tkinter/__init__.py", line 1558, in __call__
        return self.func(*args)
      File "/usr/lib/python3.5/tkinter/__init__.py", line 604, in callit
        func(*args)
      File "/usr/lib/python3/dist-packages/matplotlib/backends/backend_tkagg.py", line 373, in idle_draw
        self.draw()
      File "/usr/lib/python3/dist-packages/matplotlib/backends/backend_tkagg.py", line 354, in draw
        FigureCanvasAgg.draw(self)
      File "/usr/lib/python3/dist-packages/matplotlib/backends/backend_agg.py", line 474, in draw
        self.figure.draw(self.renderer)
      File "/usr/lib/python3/dist-packages/matplotlib/artist.py", line 62, in draw_wrapper
        draw(artist, renderer, *args, **kwargs)
      File "/usr/lib/python3/dist-packages/matplotlib/figure.py", line 1165, in draw
        self.canvas.draw_event(renderer)
      File "/usr/lib/python3/dist-packages/matplotlib/backend_bases.py", line 1809, in draw_event
        self.callbacks.process(s, event)
      File "/usr/lib/python3/dist-packages/matplotlib/cbook.py", line 563, in process
        proxy(*args, **kwargs)
      File "/usr/lib/python3/dist-packages/matplotlib/cbook.py", line 430, in __call__
        return mtd(*args, **kwargs)
      File "/usr/lib/python3/dist-packages/matplotlib/animation.py", line 661, in _start
        self._init_draw()
      File "/usr/lib/python3/dist-packages/matplotlib/animation.py", line 1221, in _init_draw
        self._draw_frame(next(self.new_frame_seq()))
    StopIteration
    

    The code producing the error is:

    def percolate():
    
        # initialize an instance of the Percolator class
        perc = Percolator(1, 100, 0.1)
    
        # initialize the image
        fig, ax = plt.subplots()
        im = plt.imshow(perc.states)
    
        anim = animation.FuncAnimation(fig, perc.update, perc.update_iter, repeat=False, fargs=(im, ), save_count=perc.n**2)
        anim.save("perc.mp4")
    

    I can reproduce the code for the Percolator class if necessary, but that part is working fine. It has two functions: update_iter, a generator function that yields True as long as the animation should continue, and update, which takes (the result of the iterator and) im as inputs, and its last two lines are

    im.set_array(self.states)
    return im,
    

    UPDATE:

    Here's an MWE.

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import animation
    
    
    class Percolator:
    
        def __init__(self):
            self.i = 0
            self.states = np.zeros((10, 10))
            self.end = False
    
        def update(self, garbage=None, im=None):
            self.i += 1
            if self.i == 10:
                self.end = True
            im.set_array(self.states)
            return im,
    
        def update_iter(self):
            while self.end == False:
                yield True
    
    def percolate():
    
        perc = Percolator()
        fig, ax = plt.subplots()
        im = plt.imshow(perc.states)
    
        anim = animation.FuncAnimation(fig, perc.update, perc.update_iter, repeat=False, \
                                       fargs=(im, ), save_count=100)
    
        anim.save("perc.gif", writer="imagemagick")
    

    In this example, the Percolator class doesn't do anything interesting - it sets up a 10x10 grid of 0s, and each call to its update function sets the image to the same 10x10 grid.

    If the frames attribute of FuncAnimation is set to 50 (say), rather than to perc.update_iter, then there is no error and the image is saved correctly. So the problem seems to be with my generator function. I want to use the generator function because I want to keep creating new frames until some condition on perc.states is met - here, boringly, I've just asked it to keep going for 10 iterations.

    System details: Python 3.5.3, matplotlib 2.0.0, Ubuntu 17.04.

    UPDATE 2:

    Same problem after upgrading to matplotlib 2.0.2. Also, printing some output along the way reveals that the error occurs at the end of the iterations. In fact, if update_iter is changed to:

    def update_iter(self):
        print(self.end)
        while self.end == False:
            yield True
    

    ... then the output is:

    False
    False
    False
    False
    False
    False
    False
    False
    False
    False
    False
    True
    >>> True
    Exception in Tkinter callback
    Traceback (most recent call last):
    etc.
    
  • ffmpeg export video from png sequence is not correct

    24 août 2017, par chris young

    I have a PNG sequence with transparent background.

    When I use Adobe Media encoder to export to an MP4 file, the result is correct.

    But when I use FFmpeg to export the MP4 file, this result is very strange.

    This is the command I used:

    ffmpeg -i test/frame_%04d.png -pix_fmt yuv444p -c:v libx264 -y ffmpeg_test.mp4
    

    Media Encoder: http://test.rto.im/ffmpeg/media_encoder_test.mp4

    FFMPEG: http://test.rto.im/ffmpeg/ffmpeg_test.mp4

    All images file: test.rto.im/ffmpeg/test.zip

    test.rto.im/ffmpeg/test/frame_0001.png

    test.rto.im/ffmpeg/test/frame_0002.png

    test.rto.im/ffmpeg/test/frame_0003.png ....

  • Python ImageIO : Too many open files

    24 août 2017, par orbv12

    I am using imageio in python in order to open all video files in a directory and convert them to numpy arrays.

    Here is the script I am using:

      1 from __future__ import print_function
      2 from avi_to_numpy import *
      3 from os import listdir
      4 import numpy as np
      5 import imageio 
      6       
      7 class_path = '../Diving/'
      8 max_frames = 16
      9 stride = 8
     10 videos = [vid for vid in listdir(class_path)]
     11 train = []
     12 
     13 for vid in videos:
     14     print(str.format('Loading {}...', vid), end="")
     15     filename = class_path + vid
     16     reader = imageio.get_reader(filename, 'ffmpeg')
     17     frames = []
     18     
     19     for i, im in enumerate(reader):
     20         if len(frames) == max_frames:
     21             break
     22         
     23         if i % stride == 0:
     24             frames.append(im)
     25     
     26     reader.close()
     27     train.append(np.array(frames))
     28     print('done')        
     29 
     30 
     31 print(len(train))
    

    Eventually this script crashes with the following error output:

    Traceback (most recent call last):
      File "load_class_test.py", line 16, in 
        reader = imageio.get_reader(filename, 'ffmpeg')
      File "/usr/local/lib/python2.7/site-packages/imageio/core/functions.py", line 111, in get_reader
        return format.get_reader(request)
      File "/usr/local/lib/python2.7/site-packages/imageio/core/format.py", line 158, in get_reader
        return self.Reader(self, request)
      File "/usr/local/lib/python2.7/site-packages/imageio/core/format.py", line 207, in __init__
        self._open(**self.request.kwargs.copy())
      File "/usr/local/lib/python2.7/site-packages/imageio/plugins/ffmpeg.py", line 260, in _open
        self._initialize()
      File "/usr/local/lib/python2.7/site-packages/imageio/plugins/ffmpeg.py", line 326, in _initialize
        stdout=sp.PIPE, stderr=sp.PIPE)
      File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
        errread, errwrite)
      File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1223, in _execute_child
        errpipe_read, errpipe_write = self.pipe_cloexec()
      File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1175, in pipe_cloexec
        r, w = os.pipe()
    OSError: [Errno 24] Too many open files
    

    I am closing the Reader object from imageio. It seems as if the files opened by ffmpeg are not being closed properly.

    Is there an obvious step I am missing here? Am I closing the files properly?

    EDIT: Found temporary solution. Opened a new issue on github.

    I was able to resolve the issue by uncommenting the following lines of code from 'imageio/plugins/ffmpeg.py':

    381         def _close_streams(self):
    382             for std in (self._proc.stdin,
    383                         self._proc.stdout,
    384                         self._proc.stderr):
    385                 try:
    386                     std.close()
    387                 except Exception:  # pragma: no cover
    388                     pass
    

    I then added a call to the above function in _close(self):

    271         def _close(self):
    272             self._terminate(0.05)  # Short timeout
    273             self._close_streams()
    274             self._proc = None
    

    I am not sure what the side effects of doing this are, but it provides a solution for me.

    Here is the link to the issue: https://github.com/imageio/imageio/issues/145