Código de Python - Generador de gifs a partir de video, en línea de comandos.

Imágen de perfil
Val: 712
Bronce
Ha aumentado 1 puesto en Python (en relación al último mes)
Gráfica de Python

Generador de gifs a partir de video, en línea de comandos.gráfica de visualizaciones


Python

Actualizado el 3 de Abril del 2024 por Antonio (75 códigos) (Publicado el 9 de Diciembre del 2022)
8.191 visualizaciones desde el 9 de Diciembre del 2022
Programa para generar gifs animados a partir de vídeos, que se ejecuta en la línea de comandos.
ARGUMENTOS:
-src/--source: Nombre del vídeo original (obligatorio).
-dest/--destination: Nombre del archivo a generar (opcional).
-sz/--size: Tamaño en porcentaje del gif respecto al vídeo original (opcional).
-shw/--show: Muestra resultado en ventana emergente al finalizar el proceso de generado (opcional).
-st/--start: Segundo inicial para gif (opcional).
-e/--end: Segundo final (opcional).
-spd/--speed: Velocidad relativa de la animación (opcional)

PARA CUALQUIER DUDA U OBSERVACIÓN, USEN LA SECCIÓN DE COMENTARIOS.

mk

Requerimientos

Lenguaje: Python
Librerías y recursos: moviepy, pyfiglet, ffmpeg, pathlib, pyglet, argparse y os

1.0

Actualizado el 20 de Enero del 2023 (Publicado el 9 de Diciembre del 2022)gráfica de visualizaciones de la versión: 1.0
1.639 visualizaciones desde el 9 de Diciembre del 2022
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
from moviepy.editor import *
#import sys
import pyfiglet
import ffmpeg
import pyglet
import pathlib
from pyglet.window import key
import argparse
import os
 
def main():
 
    parser = argparse.ArgumentParser(prog="MKGIF",conflict_handler='resolve',description="Create gifs from videos in command line.",
                                     epilog = "REPO: https://github.com/antonioam82/MKGIF")
    parser.add_argument('-src','--source',required=True,type=str,help='Archivo fuente')
    parser.add_argument('-dest','--destination',default='my_gif.gif',type=str,help='Archivo destino')
    parser.add_argument('-st','--start',default=0.0,type=float,help='Segundo inicial del gif')
    parser.add_argument('-e','--end',default=None,type=str,help='Segundo final del gif')
    parser.add_argument('-shw','--show',help='Mostrar resultado',action='store_true')
    parser.add_argument('-sz','--size',default=100,type=int,help='Tamaño en porcentaje')
    parser.add_argument('-spd','--speed',default=100,type=int,help='Velocidad de animación en porcentaje')
 
    args=parser.parse_args()
    gm(args)
 
def show(f):
    animation = pyglet.image.load_animation(f)
    bin = pyglet.image.atlas.TextureBin()
    animation.add_to_texture_bin(bin)
    sprite = pyglet.sprite.Sprite(animation)
    w = sprite.width
    h = sprite.height
    window = pyglet.window.Window(width=w, height=h)
 
    @window.event
    def on_draw():
        sprite.draw()
    pyglet.app.run()
 
def get_size_format(b, factor=1024, suffix="B"):
	for unit in ["","K","M","G","T","P","E","Z"]:
	    if b < factor:
	        return f"{b:.4f}{unit}{suffix}"
	    b /= factor
	return f"{b:.4f}Y{suffix}"
 
def gm(args):
    print(pyfiglet.figlet_format('MKGIF',font='graffiti'))
    file_extension = pathlib.Path(args.source).suffix
    result_extension = pathlib.Path(args.destination).suffix
 
    if file_extension == '.mp4' and result_extension == '.gif':
        if args.source in os.listdir():
            try:
                probe = ffmpeg.probe(args.source)
                video_streams = [stream for stream in probe["streams"] if stream["codec_type"] == "video"]
 
                if args.end:
                    duration = float(args.end)
                else:
                    duration = float(video_streams[0]['duration'])
 
                if args.start < duration:
                    clip = (VideoFileClip(args.source)
                    .subclip((0,args.start),
                         (0,duration))
                    .resize(args.size/100)
                    .speedx(args.speed/100))
                    print('CREATING GIF...')
                    clip.write_gif(args.destination)
                    clip.close()
                    size = get_size_format(os.stat(args.destination).st_size)
                    print(f"Created gif '{args.destination}' with size {size}.")
                    if args.show:
                        show(args.destination)
                else:
                    print("ERROR: Start value should be smaller than end value.")
            except Exception as e:
                print("ERROR: ",str(e))
        else:
            print(f"ERROR: File '{args.source}' not found.")
    else:
        print("ERROR: Source file must be '.mp4' and result file must be '.gif'.")
 
if __name__=='__main__':
    main()



Comentarios sobre la versión: 1.0 (0)


No hay comentarios
 

Comentar la versión: 1.0

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

2.0
estrellaestrellaestrellaestrellaestrella(1)

Actualizado el 15 de Abril del 2023 (Publicado el 13 de Febrero del 2023)gráfica de visualizaciones de la versión: 2.0
1.768 visualizaciones desde el 13 de Febrero del 2023

2.1
estrellaestrellaestrellaestrellaestrella(1)

Actualizado el 27 de Septiembre del 2023 (Publicado el 16 de Abril del 2023)gráfica de visualizaciones de la versión: 2.1
2.418 visualizaciones desde el 16 de Abril del 2023

2.2
estrellaestrellaestrellaestrellaestrella(2)

Actualizado el 3 de Abril del 2024 (Publicado el 28 de Septiembre del 2023)gráfica de visualizaciones de la versión: 2.2
2.367 visualizaciones desde el 28 de Septiembre del 2023
http://lwp-l.com/s7318