Make a GIF animation with folder monitoring

Why GIF animation

If you are developing smartphone apps or front-ends, you may want to post a video on Issues or Pull requests on Github. However, it does not support uploading video files such as mp4. I get an error like this when I try to upload an mp4 file.

However, it does support uploading GIF files, and GIF has an animation function. There are some compromises in image quality, such as up to 256 colors, but you can use them to post videos.

Why folder monitoring

I usually develop Android apps, but I felt inefficient in the current GIF animation creation process. (The process is based on Mac)

** Process 1 ** Record the screen of the Android device

  1. Click the tab under Logcat in Android Studio
  2. Check if Logcat of the terminal to record is displayed
  3. Click the Screen Record button at the bottom left of Logcat
  4. Click the Start Recording button

image.png

For command line people, see the supplement.

** Step 2 ** Save the mp4 format file

  1. Select a save folder
  2. Set the file name as needed
  3. Click the Save button

** Step 3 ** Encode to GIF animation format.

Convert mp4 file to gif file with ffmepg command. Since Github has a 10MB limit for uploaded images, the width is 320px and 10fps to reduce the capacity.

ffmpeg -i input.mp4 -vf scale=320:-1 -r 10 output.gif

** Process 4 ** Upload to Github

You can upload a GIF animation by dragging and dropping it into the comment input field on Github.

github.gif

Efficiency

If you monitor the folder, the process-File saving can be used as a trigger to automatically encode to GIF animation format, which makes your work more efficient.

Monitor folders

I created a Python program like this.

watch.py


import os
import time
from watchdog.events import FileSystemEventHandler
from watchdog.events import FileCreatedEvent
from watchdog.observers import Observer
from pathlib import PurePath
import subprocess
import signal


class MovieFileSystemEventHandler(FileSystemEventHandler):

    def on_any_event(self, event):
        if(type(event) == FileCreatedEvent):
            src_path = event.src_path
            pp = PurePath(src_path)
            if pp.suffix != '.gif':
                output_path = "%s/%s.gif" % (os.path.dirname(src_path), pp.stem)
                subprocess.run(['ffmpeg', '-i', event.src_path, '-vf',
                                'scale=320:-1', '-r', '10', output_path])


exit_flag = False


def handle_exit(sig, frame):
    global exit_flag
    exit_flag = True


signal.signal(signal.SIGINT, handle_exit)
signal.signal(signal.SIGTERM, handle_exit)


path = "%s/movie" % os.environ['HOME']
event_handler = MovieFileSystemEventHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
while exit_flag == False:
    time.sleep(1)

observer.stop()
observer.join()

This program uses a library called Watchdog, so install it with the pip command.

pip install watchdog

This program also monitors ~ / movie and saves the encoded gif animation in the same location, but if you prefer a different folder, rewrite this part if you like.

path = "%s/movie" % os.environ['HOME']

Create a monitoring folder.

mkdir ~/movie

Run a Python program. It will be a resident program.

python watchdog.py

This will monitor the folder. If the video file is saved in the watch folder, a gif animation file with the same name will be automatically generated.

watch.gif

To end the resident, press Ctrl + C on the console.

Supplement

Install ffmpeg

You can install it using brew.

brew install ffmpeg

Record Android screen from command line

adb shell
adb /mnt/sdcard
#Start recording
screenrecord output.mp4
# Ctrl +End recording with C
exit
adb pull /mnt/sdcard/output.mp4

Precautions when converting to Docker

Docker conversion is also possible. However, there are cases where it does not work properly. Saving directly from Android Studio to the monitoring directory is fine, but moving from another folder did not work properly.

FROM python:3.7-alpine
WORKDIR /root/
RUN apk add --update --no-cache ffmpeg
RUN pip install watchdog
COPY watch.py .
CMD python watch.py

docker-compose.yml


version: '3'
services:
    main:
        build: .
        volumes:
            - ~/movie:/root/movie

Build and run.

docker-compose build
docker-compose up

Details of cases that do not work properly

class MovieFileSystemEventHandler(FileSystemEventHandler):

    def on_any_event(self, event):
        # type(event)To confirm

When I moved a file from another folder to a watch folder, I got a FileModifiedEvent instead of a FileCreatedEvent. I also wanted to convert the video to GIF animation with FileModifiedEvent, but when copying from another folder, FileModifiedEvent occurs after FileCreatedEvent, and I thought it would be difficult to create an appropriate trigger.

Recommended Posts

Make a GIF animation with folder monitoring
Make a gif animation from a serial number file with matplotlib
Make a monitoring device with an infrared sensor
[Python] Folder monitoring with watchdog
Make a fortune with Python
Make a fire with kdeplot
Let's make a GUI with python.
[IOS] Disassemble GIF animation with Pythonista3.
Make a recommender system with python
Make a filter with a django template
Let's make a graph with python! !!
Let's make a supercomputer with xCAT
Make a model iterator with PySide
Make a nice graph with plotly
Easy animation with matplotlib (mp4, gif)
Let's make a shiritori game with Python
Make a video player with PySimpleGUI + OpenCV
Make ASCII art GIF animation in Python
Make a rare gacha simulator with Flask
Make a Notebook Pipeline with Kedro + Papermill
Make a partially zoomed figure with matplotlib
Make a cascade classifier with google colaboratory
Let's make a simple language with PLY 1
Make a logic circuit with a perceptron (multilayer perceptron)
Make a Yes No Popup with Kivy
Make a wash-drying timer with a Raspberry Pi
Let's make a web framework with Python! (1)
Let's make a tic-tac-toe AI with Pylearn 2
Make a desktop app with Python with Electron
Let's make a Twitter Bot with Python!
Let's make a web framework with Python! (2)
A memorandum to make WebDAV only with nginx
Investment quest: Make a system trade with pyhton (2)
Make a Twitter trend bot with heroku + Python
[Python] Make a game with Pyxel-Use an editor-
Make a simple pixel art generator with Flask
How to make a dictionary with a hierarchical structure.
I want to make a game with Python
Try to make a "cryptanalysis" cipher with Python
[Python] Make a simple maze game with Pyxel
Animation with matplotlib
Let's replace UWSC with Python (5) Let's make a Robot
Try to make a dihedral group with Python
Animation with matplotlib
Winning with Monitoring
Make holiday data into a data frame with pandas
Make a LINE WORKS bot with Amazon Lex
(Memorandum) Make a 3D scatter plot with matplodlib
Make one repeating string with a Python regular expression.
Make a morphological analysis bot loosely with LINE + Flask
Try to make a command standby tool with python
[Practice] Make a Watson app with Python! # 2 [Translation function]
[Practice] Make a Watson app with Python! # 1 [Language discrimination]
Make a simple Slackbot with interactive button in python
[Let's play with Python] Make a household account book
How to make a shooting game with toio (Part 1)
Let's make a simple game with Python 3 and iPhone
Make a breakpoint on the c layer with python
Make a function to describe Japanese fonts with OpenCV
Let's make dependency management with pip a little easier
Make a CSV formatting tool with Python Pandas PyInstaller