Código de Python - Programa para aplicación de filtros, en archivos de vídeo.

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

Programa para aplicación de filtros, en archivos de vídeo.gráfica de visualizaciones


Python

Actualizado el 20 de Noviembre del 2023 por Antonio (76 códigos) (Publicado el 24 de Mayo del 2021)
12.125 visualizaciones desde el 24 de Mayo del 2021
El presente programa se encarga de aplicar filtros sobre los fotogramas de un archivo de video empleando diferentes funciones. El programa realiza el filtrado frame a frame para a continuación generar un nuevo video con la secuencia de frames procesados (aplicando el frame rate del vídeo original). También usa el software "ffmpeg" para copiar el audio del vídeo original y añadirlo al vídeo resultante.

USO: Primeramente seleccionaremos el vídeo a filtrar mediante el botón "SEARCH". Una vez seleccionado iniciaremos el proceso con "START FILTERING" con el que empezaremos seleccionando la ubicación del nuevo vídeo, para a continuación iniciar el proceso (NOTA: La ruta del directorio de destino no deberá contener espacios en blanco). El proceso de filtrado podrá ser cancelado medinate el botón "CANCEL".
PARA CUALQUIER DUDA U OBSERVACIÓN USEN LA SECCIÓN DE COMENTARIOS.

vf

Requerimientos

LENGUAJE: Python
LIBRERÍAS Y RECURSOS: tkinter, os, opencv, ffmpeg, numpy, pydub, mhmovie, threading.

2.1

Actualizado el 9 de Junio del 2021 (Publicado el 24 de Mayo del 2021)gráfica de visualizaciones de la versión: 2.1
925 visualizaciones desde el 24 de Mayo del 2021
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
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
#IMPORTAR RECURSOS.
from tkinter import *
from tkinter import ttk
from tkinter import filedialog, messagebox
import cv2 as cv
import ffmpeg
import numpy as np
import threading
from mhmovie.code import *
from pydub import AudioSegment
import os
 
class app:
    def __init__(self):
        self.root = Tk()
        self.root.title("Video Filter")
        self.root.geometry("905x236")
        self.root.configure(bg="lavender")
 
        self.currentDir = StringVar()
        self.currentDir.set(os.getcwd())
        self.filename = StringVar()
        self.file = None
        self.frame_list = []
        self.vid_name = None
 
        Entry(self.root,textvariable=self.currentDir,width=158).place(x=0,y=0)
        Entry(self.root,textvariable=self.filename,font=('arial',23,'bold'),width=40).place(x=10,y=25)
        self.btnSearch = Button(self.root,text="SEARCH",height=2,width=25,bg="light blue1",command=self.open_file)
        self.btnSearch.place(x=709,y=25)
        self.btnStart = Button(self.root,text="START FILTERING",width=97,height=2,bg="light green",command=self.init_task)
        self.btnStart.place(x=8,y=77)
        self.btnCancel = Button(self.root,text="CANCEL",height=2,width=25,bg="light blue1",command=self.cancel)
        self.btnCancel.place(x=709,y=77)
        Label(self.root,text="FRAME RATE:",bg="lavender").place(x=709,y=150)
        self.frLabel = Label(self.root,bg='black',width=14,fg="light green")
        self.frLabel.place(x=790,y=150)
        Label(self.root,text="N FRAMES:",bg="lavender").place(x=721,y=190)
        self.nframesLabel = Label(self.root,bg='black',width=14,fg="light green")
        self.nframesLabel.place(x=790,y=190)
        self.prog_bar = ttk.Progressbar(self.root)
        self.prog_bar.place(x=10,y=170,width=687)
        self.processLabel = Label(self.root,text="PROCESS",bg="lavender",width=97)
        self.processLabel.place(x=10,y=148)
 
        self.root.mainloop()
 
    def open_file(self):
        self.dir = filedialog.askopenfilename(initialdir="/",title="SELECT FILE",
                        filetypes=(("mp4 files","*.mp4"),("avi files","*.avi"),("gif files","*.gif")))
        if self.dir:
            self.file = self.dir
 
            probe = ffmpeg.probe(self.file)
            self.video_streams = [stream for stream in probe["streams"] if stream["codec_type"] == "video"]
            self.nframes = (self.video_streams[0]['nb_frames'])
            self.fr = (self.video_streams[0]['avg_frame_rate'])
            self.vidName = (self.file).split("/")[-1]
            self.filename.set(self.vidName)
            self.frLabel.configure(text=self.fr)
            self.nframesLabel.configure(text=self.nframes)
 
    #CANCELAR PROCESO.
    def cancel(self):
        self.canceled = True
        self.processLabel.configure(text="CANCELLED")
        self.btnStart.configure(state='normal')
        self.btnSearch.configure(state='normal')
        self.prog_bar.stop()
        self.frame_list = []
 
    def check_path(self,p):
        if " " in p:
            messagebox.showwarning("INVALID PATH","No valid path provided (avoid white spaces in path).")
            return None
        else:
            return p
 
    def create_new_video(self):
        #VARIABLES.
        frame_array = []
        self.counter = 0
        dif = 0
        self.question = "yes"
        if len(self.frame_list) > 0:
            #CONCATENAR 'FRAMES'
            for img in self.frame_list:
                if self.canceled == False:
                    self.counter+=1
                    height, width, layers = img.shape
                    size = (width,height)
 
                    for k in range(1):
                        frame_array.append(img)
 
                    #AVANCE BARRA DE PROGRESO.
                    percent = self.counter*100/int(self.nframes)
                    self.prog_bar.step(percent-dif)
                    self.processLabel.configure(text="CREATING VIDEO: {}%".format(int(percent)))
                    dif=percent
 
            name,ex = os.path.splitext(self.vidName)
            self.vid_name = (name+'(filtered)'+'.mp4').replace(" ","_")
            if self.vid_name in os.listdir() and self.canceled == False:
                self.question = messagebox.askquestion("OVERWRITE?","{} already exists. Overwrite? [y/N].".format(self.vid_name))
 
            if self.question == "yes" and self.canceled == False:
                if self.vid_name in os.listdir():
                    os.remove(self.vid_name)
                frame_rate = eval(self.fr)
                out = cv.VideoWriter('filteredVideo.mp4',cv.VideoWriter_fourcc(*'XVID'), frame_rate, size)
                print("CREATING VIDEO...")
                print('FA:',len(frame_array))
 
                #FINALIZAR VIDEO.
                self.processLabel.configure(text="FINALIZING VIDEO...")
                for i in range(len(frame_array)):
                    out.write(frame_array[i])
 
                out.release()
 
                #AÑADIR AUDIO.
                self.processLabel.configure(text="ADDING AUDIO...")
                if 'VidAudioInfo.mp3' in os.listdir():
                    final_video = movie('filteredVideo.mp4') + music('VidAudioInfo.mp3')
                    print('BOTH')
                else:
                    final_video = movie('filteredVideo.mp4')
                final_video.save(self.vid_name)
 
            self.frame_list = []
 
    def filtering(self):
        self.prog_bar.stop()
        if self.file:
            #SELECCION DIRECTORIO DESTINO.
            directory = self.check_path(filedialog.askdirectory())
            if directory:
                try:
                    #CAMBIO DIRECTORIO/DESABILITA BOTONES "SEARCH" "START FILTERING".
                    os.chdir(directory)
                    self.btnStart.configure(state='disabled')
                    self.btnSearch.configure(state='disabled')
                    #EXTRAER AUDIO.
                    try:
                        self.processLabel.configure(text="GETTING AUDIO DATA...")
                        audio = AudioSegment.from_file(self.file)#
                        audio.export("VidAudioInfo.mp3",format="mp3")
                    except:
                        pass
                    self.currentDir.set(os.getcwd())
                    #VARIBLES PARA BARRA DE PROGRESO.
                    dif = 0
                    self.counter = 0
                    self.canceled = False
                    #INICIO CAPTURA DE VIDEO.
                    self.cam = cv.VideoCapture(self.file)
                    ret = True
 
                    while self.canceled == False and ret:
                        #LECTURA Y PROCESADO DE CADA 'FRAME'.
                        ret,frame = self.cam.read()
                        if ret:
                            self.counter+=1
                            name = 'frame'+str(self.counter)+'.png'
                            edited_frame = cv.bilateralFilter(frame,9,75,75)#APLICACIÓN DE FILTRO AL 'FRAME'.
                            self.frame_list.append(edited_frame)#AÑADIR INFORMACIÓN DE 'FRAME' FILTRADO
 
                            #AVANCE BARRA DE PROGRESO,
                            percent = self.counter*100/int(self.nframes)
                            self.prog_bar.step(percent-dif)
                            self.processLabel.configure(text="PROCESSING FRAMES: {} ({}%)".format((self.counter),int(percent)))
                            dif=percent
 
                    self.create_new_video()
                    self.processLabel.configure(text="PROCESS: ENDED")
                    if self.vid_name and self.canceled == False and self.question == "yes":
                        messagebox.showinfo("TASK COMPLETED","Created video \'{}\'.".format(self.vid_name))
                    if 'VidAudioInfo.mp3' in os.listdir():
                        os.remove('VidAudioInfo.mp3')
                    if 'filteredVideo.mp4' in os.listdir():
                        if not self.vid_name in os.listdir() and not 'VidAudioInfo.mp3' in os.listdir():
                            os.rename('filteredVideo.mp4',self.vid_name)
                        else:
                            os.remove('filteredVideo.mp4')
                except Exception as e:
                    messagebox.showwarning("UNEXPECTED ERROR",str(e))
                self.btnStart.configure(state='normal')
                self.btnSearch.configure(state='normal')
 
    def init_task(self):
        t = threading.Thread(target=self.filtering)
        t.start()
 
if __name__=="__main__":
    app()



Comentarios sobre la versión: 2.1 (0)


No hay comentarios
 

Comentar la versión: 2.1

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.1.1

Publicado el 9 de Junio del 2021gráfica de visualizaciones de la versión: 2.1.1
1.352 visualizaciones desde el 9 de Junio del 2021

2.1.2
estrellaestrellaestrellaestrellaestrella(4)

Actualizado el 24 de Diciembre del 2021 (Publicado el 9 de Septiembre del 2021)gráfica de visualizaciones de la versión: 2.1.2
2.777 visualizaciones desde el 9 de Septiembre del 2021

2.2

Actualizado el 8 de Febrero del 2023 (Publicado el 23 de Febrero del 2022)gráfica de visualizaciones de la versión: 2.2
5.434 visualizaciones desde el 23 de Febrero del 2022

2.3

Actualizado el 2 de Abril del 2023 (Publicado el 27 de Marzo del 2023)gráfica de visualizaciones de la versión: 2.3
747 visualizaciones desde el 27 de Marzo del 2023

2.3.1

Actualizado el 20 de Noviembre del 2023 (Publicado el 8 de Junio del 2023)gráfica de visualizaciones de la versión: 2.3.1
891 visualizaciones desde el 8 de Junio del 2023
http://lwp-l.com/s7069