-
Notifications
You must be signed in to change notification settings - Fork 0
/
emovi.py
305 lines (249 loc) · 9.49 KB
/
emovi.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
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
import os, subprocess
import indicoio
import numpy
from math import sqrt
from PIL import Image
import easygui
import requests
# Dependencies: numpy, easygui, ffmpeg
happy = Image.open('emojis/happy.png')
happyPlus = Image.open('emojis/happyPlus.png')
sad = Image.open('emojis/sad.png')
sadPlus = Image.open('emojis/sadPlus.png')
angry = Image.open('emojis/angry.png')
angryPlus = Image.open('emojis/angryPlus.png')
fear = Image.open('emojis/fear.png')
fearPlus = Image.open('emojis/fearPlus.png')
surprise = Image.open('emojis/suprise.png')
surprisePlus = Image.open('emojis/suprisePlus.png')
neutral = Image.open('emojis/neutral.png')
neutralPlus = Image.open('emojis/neutralPlus.png')
happyFear = Image.open('emojis/happy+fear.png')
happySurprise = Image.open('emojis/happy+suprised.png')
happyNeutral = Image.open('emojis/happy+neutral.png')
sadAngry = Image.open('emojis/sad+angry.png')
sadFear = Image.open('emojis/sad+fear.png')
sadSurprise = Image.open('emojis/sad+suprised.png')
sadNeutral = Image.open('emojis/sad+neutral.png')
angryFear = Image.open('emojis/angry+fear.png')
angrySurprise = Image.open('emojis/angry+suprised.png')
angryNeutral = Image.open('emojis/angry+neutral.png')
fearSurprise = Image.open('emojis/fear+suprised.png')
fearNeutral = Image.open('emojis/neutral+fear.png')
neutralSurprise = Image.open('emojis/neutral+suprised.png')
# Image IndicoData -> None
# Effect: modifies image to include emojis
def pasteEmojis_effectful(img, faceInfo):
(x1, y1) = faceInfo['location']['top_left_corner']
(x2, y2) = faceInfo['location']['bottom_right_corner']
emotions = sorted(faceInfo['emotions'].items(), key=lambda kv: -kv[1])
first, second = emotions[0], emotions[1]
if (first[1] + second[1]) / sum(faceInfo['emotions'].values()) >= .5 and second[1] / first[1] > .65: # 2 emotions
if first[0] in ('Happy','Fear') and second[0] in ('Happy','Fear'):
emoji = happyFear
elif first[0] in ('Happy','Surprise') and second[0] in ('Happy','Surprise'):
emoji = happySurprise
elif first[0] in ('Happy','Neutral') and second[0] in ('Happy','Neutral'):
emoji = happyNeutral
elif first[0] in ('Sad','Angry') and second[0] in ('Sad','Angry'):
emoji = sadAngry
elif first[0] in ('Sad','Fear') and second[0] in ('Sad','Fear'):
emoji = sadFear
elif first[0] in ('Sad','Surprise') and second[0] in ('Sad','Surprise'):
emoji = sadSurprise
elif first[0] in ('Sad','Neutral') and second[0] in ('Sad','Neutral'):
emoji = sadNeutral
elif first[0] in ('Angry','Fear') and second[0] in ('Angry','Fear'):
emoji = angryFear
elif first[0] in ('Angry','Surprise') and second[0] in ('Angry','Surprise'):
emoji = angrySurprise
elif first[0] in ('Angry','Neutral') and second[0] in ('Angry','Neutral'):
emoji = angryNeutral
elif first[0] in ('Fear','Surprise') and second[0] in ('Fear','Surprise'):
emoji = fearSurprise
elif first[0] in ('Fear','Neutral') and second[0] in ('Fear','Neutral'):
emoji = fearNeutral
elif first[0] in ('Neutral','Surprise') and second[0] in ('Neutral','Surprise'):
emoji = neutralSurprise
else:
emoji = neutral
elif first[1] > 0.60: # strong emotion
if first[0] == 'Happy':
emoji = happyPlus
elif first[0] == 'Sad':
emoji = sadPlus
elif first[0] == 'Angry':
emoji = angryPlus
elif first[0] == 'Fear':
emoji = fearPlus
elif first[0] == 'Surprise':
emoji = surprisePlus
else:
emoji = neutralPlus
else: # weak emotion
if first[0] == 'Happy':
emoji = happy
elif first[0] == 'Sad':
emoji = sad
elif first[0] == 'Angry':
emoji = angry
elif first[0] == 'Fear':
emoji = fear
elif first[0] == 'Surprise':
emoji = surprise
else:
emoji = neutral
emoji = emoji.resize((x2-x1, y2-y1))
img.paste(emoji, (x1,y1), emoji)
# [ImgInfo] Int Int -> None
def smoothenFaces(imgInfos, w, h):
if not imgInfos:
return None
for i in range(1, len(imgInfos) - 1):
for faceInfo in imgInfos[i]:
x1, y1 = faceInfo['location']['top_left_corner']
x2, y2 = faceInfo['location']['bottom_right_corner']
prevIndex = getNearbyFace((x1 + x2)/2, (y1 + y2)/2, w, h, imgInfos[i-1])
nextIndex = getNearbyFace((x1 + x2)/2, (y1 + y2)/2, w, h, imgInfos[i+1])
adjs = []
if prevIndex is not None: adjs.append(imgInfos[i-1][prevIndex])
adjs.append(faceInfo)
if nextIndex is not None: adjs.append(imgInfos[i+1][nextIndex])
def x1(fInfo): return fInfo['location']['top_left_corner'][0]
def y1(fInfo): return fInfo['location']['top_left_corner'][1]
def x2(fInfo): return fInfo['location']['bottom_right_corner'][0]
def y2(fInfo): return fInfo['location']['bottom_right_corner'][1]
length = len(adjs)
xAvg = sum((x1(fInfo) + x2(fInfo)) / 2 for fInfo in adjs) / length
yAvg = sum((y1(fInfo) + y2(fInfo)) / 2 for fInfo in adjs) / length
wAvg = sum(x2(fInfo) - x1(fInfo) for fInfo in adjs) / length
hAvg = sum(y2(fInfo) - y1(fInfo) for fInfo in adjs) / length
x1, y1 = xAvg - wAvg/2, yAvg - hAvg/2
x2, y2 = xAvg + wAvg/2, yAvg + hAvg/2
faceInfo['location']['top_left_corner'] = int(x1), int(y1)
faceInfo['location']['bottom_right_corner'] = int(x2), int(y2)
for emotion in ('Happy', 'Sad', 'Angry', 'Fear', 'Surprise', 'Neutral'):
avg = sum(fInfo['emotions'][emotion] for fInfo in adjs) / length
faceInfo[emotion] = avg
# Int Int Int Int ImgInfo -> Int
# returns index of nearby face, or None if none exists
def getNearbyFace(x, y, w, h, imgInfo):
if not imgInfo:
return None
for i, faceInfo in enumerate(imgInfo):
if not faceInfo:
continue
(x1,y1) = faceInfo['location']['top_left_corner']
(x2,y2) = faceInfo['location']['bottom_right_corner']
dx = abs(x - (x1+x2)/2)
dy = abs(y - (y1+y2)/2)
if dx < w/10 and dy < h/10:
return i
# [String] -> [Image]
# Effect: Calls the Indico API
def urlsToImages(imgUrls):
denom = str(len(imgUrls))
imgInfos = []
i = 0
for i, url in enumerate(imgUrls):
try:
imgInfo = indicoio.fer(url, detect=True)
imgInfos.append(imgInfo)
i += 1
print(str(i) + '/' + denom)
except indicoio.utils.errors.IndicoError:
imgInfos.append({})
i += 1
print(str(i) + '/' + denom)
except requests.exceptions.ConnectionError:
pass
print('Smoothening...')
imgs = [ Image.open(url) for url in imgUrls ]
smoothenFaces(imgInfos, imgs[0].size[0], imgs[0].size[1])
print('Adding emojis...')
for img, imgInfo in zip(imgs, imgInfos):
for faceInfo in imgInfo:
pasteEmojis_effectful(img, faceInfo)
return imgs
# GifURL -> [Image]
# Effect: Calls the Indico API
def gifUrlToFrames(url):
gif = Image.open(url)
imgs = []
i = 0
try:
while 1:
gif.seek(i)
frame = gif.copy()
w, h = frame.size
if w % 2: w -= 1
if h % 2: h -= 1
frame = frame.crop((0, 0, w, h)).convert('RGB')
try:
imgInfo = indicoio.fer(numpy.array(frame), detect=True)
[ pasteEmojis_effectful(frame, faceInfo) for faceInfo in imgInfo ]
imgs.append(frame)
i += 1
except indicoio.utils.errors.IndicoError:
imgs.append(frame)
i += 1
except requests.exceptions.ConnectionError:
pass
except EOFError:
return imgs
# String -> None
# Effect: saves gif frames to /output
# Effect: creates an mp4 of a gif and saves it in /output
def processGifUrl_effectful(url):
framerate = Image.open(url).info['duration'] / 1000.0
gifName = url.split('/')[-1].split('\\')[-1].split('.')[0]
frames = gifUrlToFrames(url)
if not os.path.exists('Output/' + gifName):
os.makedirs('Output/' + gifName)
[ frame.save('Output/' + gifName + ('/%003d.png' % i)) for i, frame in enumerate(frames) ]
subprocess.Popen('ffmpeg -framerate ' + str(1/framerate) + ' -i Output/' + gifName + '/%003d.png '
+ '-c:v libx264 -r 30 -pix_fmt yuv420p Output/' + gifName + '.mp4')
def processMovieUrl_effectful(url):
def call_command(command):
subprocess.call(command.split(' '))
movieName = url.split('/')[-1].split('\\')[-1].split('.')[0]
if not os.path.exists('Input/' + movieName):
os.makedirs('Input/' + movieName)
if not os.path.exists('Output/' + movieName):
os.makedirs('Output/' + movieName)
# movie to frames
call_command('ffmpeg -i ' + url + ' -vf fps=10 Input/' + movieName + '/%09d.png')
# movie to audio
call_command('ffmpeg -ss 0 -i ' + url + ' Output/' + movieName + '/audio.mp3')
i = 1
urls = []
while os.path.isfile('Input/' + movieName + ('/%09d.png' % i)):
urls.append('Input/' + movieName + ('/%09d.png' % i))
i += 1
frames = urlsToImages(urls)
for url, frame in zip(urls, frames):
url = url.split('/')[-1].split('\\')[-1]
frame.save('Output/' + movieName + '/' + url)
# frames to movie
call_command('ffmpeg -framerate 10 -i Output/' + movieName + '/%09d.png -c:v libx264 -r 30 -pix_fmt yuv420p Output/' + movieName + '/_' + movieName + '_.mp4')
# merge video and audio
call_command('ffmpeg -i Output/' + movieName + '/_' + movieName + '_.mp4 -i Output/' + movieName + '/audio.mp3 -codec copy -shortest Output/' + movieName + '.mp4')
requests.packages.urllib3.disable_warnings()
indicoio.config.api_key =
'********************************'
fileNameAndPath = easygui.fileopenbox(title='Choose your file:',
filetypes=('*.mp4', '*.mkv', '*.png', '*.jpeg', '*.jpg', '*.bmp', '*.gif'))
videoTypes = ['mp4', 'mkv']
picTypes = ['png', 'jpeg', 'jpg', 'bmp']
fileTypeCheck = fileNameAndPath.split('.')[-1]
if fileTypeCheck == 'gif':
processGifUrl_effectful(fileNameAndPath)
elif fileTypeCheck in videoTypes:
processMovieUrl_effectful(fileNameAndPath)
elif fileTypeCheck in picTypes:
img = urlsToImages([fileNameAndPath])[0]
img.save('Output/' + fileNameAndPath.split('/')[-1].split('\\')[-1])
'''
cd c:/users/dan/documents/python/emovi
python emovi.py
'''