-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrabalho_final_algebra_linear.py
168 lines (125 loc) · 4.74 KB
/
trabalho_final_algebra_linear.py
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
# -*- coding: utf-8 -*-
"""Trabalho Final - Algebra Linear.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1sIAmw0SzXdhPXB8pVGIm2pLdSdVUxRhq
"""
!pip install face_recognition
!pip install ffmpeg
!pip install ffmpeg-python
#Para a IA funcionar no colab corretamente é necessário uma GPU! Isto irá confirmar que uma GPU está ativa!
from tensorflow.python.client import device_lib
device_lib.list_local_devices()
import face_recognition
from moviepy.editor import *
import moviepy.editor
import ffmpeg
import glob
import cv2
import numpy as np
import os
import shutil
from tqdm.notebook import tqdm
def borra_quadrilatero(filename, top, right, bottom, left):
#Lendo a imagem
image = cv2.imread(filename)
#Extraindo a região da imagem
face_image = image[top:bottom, left:right]
#Borrando apenas a regiao especificada usando o filtro gaussiano
face_image = cv2.GaussianBlur(face_image, (153, 153), 0)
#Colocando a parte extraida de volta na imagem
image[top:bottom, left:right] = face_image
#Gravando a imagem alterada
cv2.imwrite(filename,image)
def censura_foto(filename, number_of_times_to_upsample = 2):
#Encontrando a posição dos rostos na imagem
img = face_recognition.load_image_file(filename)
face_locations = face_recognition.face_locations(img, number_of_times_to_upsample)
#Lendo a imagem
image = cv2.imread(filename)
for (top, right, bottom, left) in face_locations:
#Extraindo a região da imagem com o rosto
face_image = image[top:bottom, left:right]
#Borrando apenas o rosto usando o filtro gaussiano
face_image = cv2.GaussianBlur(face_image, (153, 153), 0)
#Colocando a parte extraida de volta na imagem
image[top:bottom, left:right] = face_image
#Gravando a imagem com os rostos borrados
cv2.imwrite(filename,image)
def extrai_video(filename):
#criando pasta para os frames
os.makedirs(os.path.join("./", "video"))
#extraindo o audio
clip = moviepy.editor.VideoFileClip(filename)
clip.audio.write_audiofile("./video/" +"audio.mp3")
#extraindo os frames
vidcap = cv2.VideoCapture(filename)
success,image = vidcap.read()
count = 0
while success:
cv2.imwrite("./video/" + "frame%s.png" % str(count).zfill(8), image)
success,image = vidcap.read()
count += 1
print("Frames extraidos!")
vidcap.release()
cv2.destroyAllWindows()
def censura_video(filename, number_of_times_to_upsample = 1):
#Atenção: Talvez seja possível fazer usando Batch para ser mais rápido na GPU, porém sempre falta memória!
extrai_video(filename)
files = glob.glob(f"/content/video/*.png")
files.sort()
for frames in tqdm(files, desc="Censurando os Frames... " ):
censura_foto(frames, number_of_times_to_upsample)
frame = cv2.imread(os.path.join("/content/video/", files[0]))
height, width, layers = frame.shape
video = cv2.VideoWriter("output.mp4", cv2.VideoWriter_fourcc(*'mp4v'), 30, (width,height))
for frame in tqdm(files, desc="Criando o vídeo... "):
video.write(cv2.imread(os.path.join("./", frame)))
cv2.destroyAllWindows()
video.release()
#juntando o audio do vídeo
print("Criando o Audio... ")
input_video = ffmpeg.input('./output.mp4')
input_audio = ffmpeg.input('./video/audio.mp3')
ffmpeg.concat(input_video, input_audio, v=1, a=1).output('./finished_video.mp4').run()
#Apagando a pasta "./video/" e o "output.mp4" para evitar mesclagem de frames
shutil.rmtree(os.path.join("./", "video"))
os.remove("./output.mp4")
print("Concluido com Sucesso!")
"""Testando uma imagem normal, com 5 rostos:"""
from google.colab.patches import cv2_imshow
original = cv2.imread("test.png")
print("Foto Original: ")
cv2_imshow(original)
censura_foto("test.png")
print("Resultado: ")
result = cv2.imread("test.png")
cv2_imshow(result)
"""Testando uma pintura, sem rostos reais:"""
from google.colab.patches import cv2_imshow
original = cv2.imread("operarios.png")
print("Foto Original: ")
cv2_imshow(original)
censura_foto("operarios.png")
print("Resultado: ")
result = cv2.imread("operarios.png")
cv2_imshow(result)
from google.colab.patches import cv2_imshow
original = cv2.imread("largest_selfie.png")
print("Foto Original: ")
cv2_imshow(original)
censura_foto("largest_selfie.png")
print("Resultado: ")
result = cv2.imread("largest_selfie.png")
cv2_imshow(result)
"""Aumentando o upsample de 2 para 4 para ver a diferença no tempo e na precisão:"""
from google.colab.patches import cv2_imshow
original = cv2.imread("largest_selfie.png")
print("Foto Original: ")
cv2_imshow(original)
censura_foto("largest_selfie.png",4)
print("Resultado: ")
result = cv2.imread("largest_selfie.png")
cv2_imshow(result)
"""Testando em um vídeo 720p de 30 seg:"""
censura_video("test.mp4", 1)