Código de Python - Generador de gifs a partir de video (nueva version)

Filtrado por el tag: video-to-gif
<<>>
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 (nueva version)gráfica de visualizaciones


Python

Actualizado el 10 de Julio del 2026 por Antonio (77 códigos) (Publicado el 29 de Enero del 2024)
26.578 visualizaciones desde el 29 de Enero del 2024
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.

imagge

Requerimientos

Lenguaje: Python 3.12.1
Librerias: Pillow 10.2.0, Pyfiglet 1.0.2, ffmpeg-python 0.2.0, pyglet 2.0.10, colorama 0.4.6, moviepy 1.0.3

2.2.1

Actualizado el 20 de Febrero del 2024 (Publicado el 29 de Enero del 2024)gráfica de visualizaciones de la versión: 2.2.1
2.023 visualizaciones desde el 29 de Enero del 2024

3.0

Actualizado el 5 de Mayo del 2024 (Publicado el 6 de Abril del 2024)gráfica de visualizaciones de la versión: 3.0
2.585 visualizaciones desde el 6 de Abril del 2024

3.1

Actualizado el 20 de Diciembre del 2025 (Publicado el 10 de Agosto del 2024)gráfica de visualizaciones de la versión: 3.1
3.040 visualizaciones desde el 10 de Agosto del 2024

3.2
estrellaestrellaestrellaestrellaestrella(1)

Actualizado el 1 de Mayo del 2026 (Publicado el 19 de Diciembre del 2024)gráfica de visualizaciones de la versión: 3.2
18.035 visualizaciones desde el 19 de Diciembre del 2024

3.3

Actualizado el 6 de Junio del 2026 (Publicado el 4 de Mayo del 2026)gráfica de visualizaciones de la versión: 3.3
858 visualizaciones desde el 4 de Mayo del 2026
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

mkgif116
mkgif115
mkgif114

mkgif112

En esta versión las mejoras funcionales clave son tres: el soporte completo de opciones (tamaño, velocidad, frames de inicio/fin) para archivos `.webp`, que en la versión anterior estaban bloqueadas; la adición del argumento `--optimize` para reducir el peso del GIF resultante; y una gestión de memoria más eficiente mediante un generador de frames que evita cargar el vídeo completo en RAM de una sola vez, lo que permite trabajar con archivos más largos sin problemas.
mkgif117
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pyfiglet
import pyglet
import argparse
from PIL import Image
import random
from colorama import Fore, init, Style
import os
import cv2
from tqdm import tqdm
import hashlib
from pynput import keyboard
#from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from typing import Optional, Generator
import numpy as np
 
init()
 
color = {0: Fore.RED, 1: Fore.GREEN, 2: Fore.YELLOW,
         3: Fore.BLUE, 4: Fore.CYAN, 5: Fore.MAGENTA, 6: Fore.WHITE}
 
bright = {0: Style.BRIGHT, 1: Style.NORMAL}
 
c_index = color[random.randint(0, 6)]
b_index = bright[random.randint(0, 1)]
 
@dataclass
class AppState:
    stop: bool = False
    done: bool = True
    frame_list: list = field(default_factory=list)
    width: int = 0
    height: int = 0
    num_frames: int = 0
    video_fps: float = 0.0
    total_frames: int = 0
 
 
def check_result_ext(file):
    name, ex = os.path.splitext(file)
    if ex != '.gif':
        raise argparse.ArgumentTypeError(
            Fore.RED + Style.BRIGHT +
            f"result file must be '.gif' ('{ex}' is not valid)." +
            Fore.RESET + Style.RESET_ALL
        )
    return file
 
 
def check_source_ext(file):
    supported_formats = ['.mp4', '.avi', '.mov', '.wmv', '.rm', '.webp', '.gif']
    name, ex = os.path.splitext(file)
    if os.path.exists(file):
        if ex not in supported_formats:
            raise argparse.ArgumentTypeError(
                Fore.RED + Style.BRIGHT +
                f"Source file must be '.mp4', '.avi', '.mov', '.wmv', '.rm', '.gif' or '.webp' ('{ex}' is not valid)." +
                Fore.RESET + Style.RESET_ALL
            )
    else:
        raise argparse.ArgumentTypeError(
            Fore.RED + Style.BRIGHT +
            f"FILE NOT FOUND: File '{file}' not found." +
            Fore.RESET + Style.RESET_ALL
        )
    return file
 
 
def frame_generator(cap: cv2.VideoCapture, final_frame: int, state: AppState) -> Generator:
    """Yield frames one by one instead of loading all into memory."""
    while True:
        ret, frame = cap.read()
        if not ret:
            break
        current = int(cap.get(cv2.CAP_PROP_POS_FRAMES))
        yield cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        if current >= final_frame or state.stop:
            break
 
 
def create_gif(args, state: AppState) -> None:
    """Create GIF from frames stored in state, using parallel resizing."""
    listener = None
    pbar = None
 
    try:
        listener = keyboard.Listener(on_press=lambda key: on_press(key, state))
        listener.start()
 
        print("\nCREATING YOUR GIF...(PRESS SPACE BAR TO CANCEL)")
 
        factor = args.size / 100
        new_w = int(state.width * factor)
        new_h = int(state.height * factor)
 
        resample = Image.LANCZOS if factor > 0.5 else Image.BILINEAR
 
        def resize_frame(frame: np.ndarray) -> Image.Image:
            if state.stop:
                return None
            return Image.fromarray(frame).resize((new_w, new_h), resample)
 
        pbar = tqdm(total=state.total_frames, unit='frames', ncols=100)
        output_frames = []
 
        #with ThreadPoolExecutor() as executor:
            #futures = executor.map(resize_frame, state.frame_list)
            #for img in futures:
        for img in state.frame_list:
            resized_frame = resize_frame(img)
            if state.stop or img is None:
                print(Fore.YELLOW + Style.NORMAL + "\nGif creation interrupted by user." + Fore.RESET + Style.RESET_ALL)
                pbar.disable = True
                state.done = False
                break
            #output_frames.append(img)
            output_frames.append(resized_frame)
            pbar.update(1)
 
        pbar.close()
        listener.stop()
 
        if state.done:
            print("\nSAVING YOUR GIF (PLEASE, WAIT)...")
            duration = 1000 / (state.video_fps * (args.speed / 100))
 
            output_frames[0].save(
                args.destination,
                save_all=True,
                append_images=output_frames[1:],
                optimize=args.optimize,
                duration=duration,
                loop=0
            )
 
            size = get_size_format(os.stat(args.destination).st_size)
            print(f"Created gif '{args.destination}' with size '{size}' from '{args.source}'.")
 
    except Exception as e:
        if pbar:
            pbar.close()
        if listener and listener.is_alive():
            listener.stop()
        state.done = False
        print(Fore.RED + Style.BRIGHT + f"\nUNEXPECTED ERROR: {e}" + Fore.RESET + Style.RESET_ALL)
 
 
def read_video(args, state: AppState) -> None:
    """Read video frames into state using a memory-efficient generator."""
    pbar = None
    listener = None
 
    try:
        listener = keyboard.Listener(on_press=lambda key: on_press(key, state))
        listener.start()
 
        print(c_index + b_index + pyfiglet.figlet_format('MKGIF', font='graffiti') + Fore.RESET + Style.RESET_ALL)
 
        cap = cv2.VideoCapture(args.source)
        state.num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        state.width      = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        state.height     = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        state.video_fps  = cap.get(cv2.CAP_PROP_FPS)
        duration         = state.num_frames / state.video_fps
 
        initial_frame = args.from_frame
        final_frame   = int(args.to_frame) if args.to_frame else int(state.num_frames)
 
        valid_range = (
            0 <= initial_frame <= state.num_frames and
            0 < final_frame <= state.num_frames and
            initial_frame < final_frame
        )
 
        if not valid_range:
            print(Fore.RED + Style.BRIGHT + "Invalid index for initial or final frame." + Fore.RESET + Style.RESET_ALL)
            state.done = False
            cap.release()
            return
 
        cap.set(cv2.CAP_PROP_POS_FRAMES, initial_frame)
        state.total_frames = abs(state.num_frames - initial_frame) - abs(final_frame - state.num_frames)
 
        print("SOURCE VIDEO DATA:")
        print(
            f'NUMBER OF FRAMES: {state.num_frames} | '
            f'WIDTH: {state.width} | HEIGHT: {state.height} | '
            f'FRAME RATE: {state.video_fps:.2f} | DURATION: {duration:.2f}s\n'
        )
        print("PROCESSING...(PRESS SPACE BAR TO CANCEL)")
 
        pbar = tqdm(total=int(state.total_frames), unit='frames', ncols=100)
 
        for frame in frame_generator(cap, final_frame, state):
            state.frame_list.append(frame)
            pbar.update(1)
            if state.stop:
                print(
                    Fore.YELLOW + Style.NORMAL +
                    "\nFrame processing interrupted by user." +
                    Fore.RESET + Style.RESET_ALL
                )
                pbar.disable = True
                state.done = False
                break
 
        cap.release()
        pbar.close()
        listener.stop()
 
    except Exception as e:
        if pbar:
            pbar.close()
        if listener:
            listener.stop()
        state.done = False
        print(Fore.RED + Style.DIM + f"\nUNEXPECTED ERROR: {e}" + Fore.RESET + Style.RESET_ALL)
 
 
def on_press(key, state: AppState) -> Optional[bool]:
    """Handle spacebar to cancel processing."""
    if key == keyboard.Key.space:
        state.stop = True
        return False
 
 
def calculate_sha1(file_path: str) -> str:
    sha1_hash = hashlib.sha1()
    with open(file_path, "rb") as f:
        for byte_block in iter(lambda: f.read(4096), b""):
            sha1_hash.update(byte_block)
    return sha1_hash.hexdigest()
 
 
def convert_to_gif(args, state: AppState) -> None:
    """
    Extract all frames from a .webp animation into state.frame_list so they
    can be processed by the shared create_gif() pipeline (resize, speed, optimize…).
    Falls back to a direct save when the webp has only one frame.
    """
    listener = None
    pbar = None
    try:
        print(c_index + b_index + pyfiglet.figlet_format('MKGIF', font='graffiti') + Fore.RESET + Style.RESET_ALL)
 
        listener = keyboard.Listener(on_press=lambda key: on_press(key, state))
        listener.start()
 
        webp = Image.open(args.source)
 
        n_frames = getattr(webp, 'n_frames', 1)
 
        initial_frame = args.from_frame
        final_frame   = int(args.to_frame) if args.to_frame else n_frames
 
        valid_range = (
            0 <= initial_frame < n_frames and
            0 < final_frame <= n_frames and
            initial_frame < final_frame
        )
        if not valid_range:
            print(Fore.RED + Style.BRIGHT + "Invalid index for initial or final frame." + Fore.RESET + Style.RESET_ALL)
            state.done = False
            webp.close()
            return
 
        state.width       = webp.width
        state.height      = webp.height
        state.num_frames  = n_frames
        state.total_frames = final_frame - initial_frame
 
        frame_duration_ms = webp.info.get('duration', 100)   # ms por frame
        state.video_fps   = 1000 / frame_duration_ms if frame_duration_ms > 0 else 10.0
 
        duration_s = state.total_frames / state.video_fps
        print("SOURCE WEBP DATA:")
        print(
            f'NUMBER OF FRAMES: {n_frames} | '
            f'WIDTH: {state.width} | HEIGHT: {state.height} | '
            f'FRAME RATE: {state.video_fps:.2f} | DURATION: {duration_s:.2f}s\n'
        )
        print("READING WEBP FRAMES...(PRESS SPACE BAR TO CANCEL)")
 
        pbar = tqdm(total=state.total_frames, unit='frames', ncols=100)
 
        for i in range(initial_frame, final_frame):
            if state.stop:
                print(Fore.YELLOW + Style.NORMAL + "\nFrame processing interrupted by user." + Fore.RESET + Style.RESET_ALL)
                pbar.disable = True
                state.done = False
                break
            webp.seek(i)
            frame_rgba = webp.convert('RGBA')
            state.frame_list.append(np.array(frame_rgba.convert('RGB')))
            pbar.update(1)
 
        pbar.close()
        listener.stop()
        webp.close()
 
    except Exception as e:
        if pbar:
            pbar.close()
        if listener and listener.is_alive():
            listener.stop()
        state.done = False
        print(Fore.RED + Style.DIM + f"\nUNEXPECTED ERROR: {e}" + Fore.RESET + Style.RESET_ALL)
 
 
def show(f: str) -> None:
    print("GENERATING VIEW -PRESS 'ESC' TO CLOSE THE WINDOW-")
    try:
        from pyglet.window import key
        with Image.open(f) as img:
            w, h = img.size
 
        animation = pyglet.image.load_animation(f)
        binm = pyglet.image.atlas.TextureBin()
        animation.add_to_texture_bin(binm)
        window = pyglet.window.Window(w, h, 'GIF VIEW')
        sprite = pyglet.sprite.Sprite(animation)
 
        @window.event
        def on_draw():
            sprite.draw()
 
        @window.event
        def on_key_press(symbol, modifiers):
            if symbol == key.ESCAPE:
                window.close()
 
        pyglet.app.run()
        print(f"Successfully generated view from '{f}'.")
    except Exception as e:
        print(Fore.RED + Style.BRIGHT + f"UNEXPECTED ERROR: {e}" + Fore.RESET + Style.RESET_ALL)
 
 
def check_positive(v):
    ivalue = float(v)
    if ivalue <= 0:
        raise argparse.ArgumentTypeError(
            Fore.RED + Style.BRIGHT +
            f"speed and size values must be positive ('{v}' is not valid)." +
            Fore.RESET + Style.RESET_ALL
        )
    return ivalue
 
 
def check_initial(v):
    ivalue = int(v)
    if ivalue < 0:
        raise argparse.ArgumentTypeError(
            Fore.RED + Style.BRIGHT +
            f"initial frame position must be greater or equal to 0 ('{v}' is not valid)." +
            Fore.RESET + Style.RESET_ALL
        )
    return ivalue
 
 
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 main():
    parser = argparse.ArgumentParser(
        prog="mkgif11.py",
        conflict_handler='resolve',
        description="Create gifs from various formats in command line.",
        epilog="REPO: https://github.com/antonioam82/MKGIF",
        allow_abbrev=False
    )
 
    parser.add_argument('-src','--source',required=True,type=check_source_ext,help='Source file name')
    parser.add_argument('-dest','--destination',default=None,type=check_result_ext,help='Destination file name')
    parser.add_argument('-sz','--size',default=100,type=check_positive,help='Relative size of the gif (100 by default)')
    parser.add_argument('-delsrc','--delete_source',action='store_true',help='Generate gif and remove source file')
    parser.add_argument('-fps','--frames_per_second',default=None,type=check_positive,help='Duration of the gif')
    parser.add_argument('-spd','--speed',default=100,type=check_positive,help='Speed of the gif as a percentage of the original (100 by default)')
    parser.add_argument('-shw','--show',action='store_true',help='Show result file')
    parser.add_argument('-from','--from_frame',default=0,type=check_initial,help='Starting frame')
    parser.add_argument('-to','--to_frame',default=None,type=check_positive,   help='Ending frame')
    parser.add_argument('-opt','--optimize',action='store_true',help='Optimize gif file size (slower save)')
 
    args = parser.parse_args()
 
    state = AppState()
 
    name, file_extension = os.path.splitext(args.source)
 
    if args.destination is None:
        hash_name = calculate_sha1(args.source)
        if file_extension == '.webp':
            args.destination = f"{hash_name}.gif"
        else:
            speed = int(args.speed)
            size  = int(args.size)
            args.destination = f"{hash_name}{speed}{size}.gif"
 
    if file_extension == '.webp':
        convert_to_gif(args, state)
    else:
        read_video(args, state)
 
    if not state.stop and state.done:
        create_gif(args, state)
 
    if args.delete_source:
        os.remove(args.source)
        print(f"Removed file '{args.source}'.")
 
    if args.show and state.done:
        show(args.destination)
 
 
if __name__ == '__main__':
    main()



Comentarios sobre la versión: 3.3 (0)


No hay comentarios
 

Comentar la versión: 3.3

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

3.3.1

Publicado el 10 de Julio del 2026gráfica de visualizaciones de la versión: 3.3.1
39 visualizaciones desde el 10 de Julio del 2026
http://lwp-l.com/s7491