-
Notifications
You must be signed in to change notification settings - Fork 0
/
converter.py
236 lines (200 loc) · 9.1 KB
/
converter.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
# checkout html2image, htmlwebshot
import cv2, os, shutil, sys, imgkit
from PIL import Image, ImageOps
def vid_to_img(video_path, vid_name, generation):
video = cv2.VideoCapture(video_path)
fps = video.get(cv2.CAP_PROP_FPS)
frame_count = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
duration = frame_count/fps
minutes = int(duration/60)
seconds = duration%60
print('FPS = ' + str(fps))
print('Total frames = ' + str(frame_count))
print('Duration (S) = ' + str(duration))
print('duration (M:S) = ' + str(minutes) + ':' + str(seconds))
success, image = video.read()
counter = 1
if generation:
os.mkdir(vid_name+'_Images')
while success:
cv2.imwrite(vid_name+"_Images/Image{0}.png".format(str(counter)), image)
success, image = video.read()
print(f"Frame number: {counter}/{frame_count}")
counter+=1
if not generation:
file_count = len(next(os.walk(vid_name+"_Images"))[2])
counter += file_count
return fps, (counter-1)
def get_image_info(image_path):
initial_image = Image.open(image_path)
width,height = initial_image.size
initial_image = initial_image.resize((round(width*1.05),height))
return initial_image
def correctSize(image, final_width = 200):
width, height = image.size
final_height = int((height*final_width)/width)
image = image.resize((final_width,final_height))
return image
def grayscale_image(image):
image_bw = ImageOps.grayscale(image)
return image_bw
def ascii_conversion(bw_image,ascii_string = [" ",".",":","-","=","+","`","'","*","#","%","@","&"]):
pixels = bw_image.getdata()
ascii_image_list = []
for pixel in pixels:
ascii_converted = int((pixel*len(ascii_string))/256)
ascii_image_list.append(ascii_string[ascii_converted])
return ascii_image_list
def get_color(image):
pixels = image.getdata()
return pixels
def rgb_ascii(ascii_list, image, color,image_pos,vid_name):
file = open(vid_name+'_HtmlImages/Html{0}.html'.format(str(image_pos)),"w")
file.write("""
<!DOCTYPE html>
<html>
<body style='background-color:black'>
<pre style='display: inline-block; border-width: 4px 6px; border-color: black; border-style: solid; background-color:black; font-size: 32px ;font-face: Montserrat;font-weight: bold;line-height:60%'>""")
width, height = image.size
counter = 0
for j in ascii_list:
color_hex = '%02x%02x%02x' % color[counter]
counter+=1
if (counter % width) != 0:
file.write("<span style=\"color: #{0}\">{1}</span>".format(color_hex,j))
else:
file.write("<br />")
file.write("""</pre></body>
</html>""")
file.close()
def bw_ascii(ascii_list, image, image_pos,vid_name):
file = open(vid_name+'_bwHtmlImages/bwHtml{0}.html'.format(str(image_pos)),"w")
file.write("""
<!DOCTYPE html>
<html>
<body style='background-color:black'>
<pre style='display: inline-block; border-width: 4px 6px; border-color: black; border-style: solid; background-color:black; font-size: 32px ;font-face: Montserrat;font-weight: bold;line-height:60%'>""")
width, height = image.size
counter = 0
for j in ascii_list:
counter+=1
if (counter % width) != 0:
file.write("<span style= color:#ffffff>{0}</span>".format(j))
else:
file.write("<br />")
file.write("""</pre></body>
</html>""")
file.close()
def export_video(vid_name, fps, number_images):
print("Generating RGB ASCII video...")
res = Image.open(vid_name+'_TextImages/Image1.png').size
video = cv2.VideoWriter(vid_name+'_rgb_ascii.mp4',cv2.VideoWriter_fourcc('m', 'p', '4', 'v'),int(fps),res)
for j in range(1,number_images+1):
print("Writing frames... [{0}/{1}]".format(j,number_images+1))
video.write(cv2.imread(vid_name+'_TextImages/Image{0}.png'.format(str(j))))
video.release()
print("RGB ASCII Video Exported...")
print("Generating BW ASCII video...")
res = Image.open(vid_name+'_bwTextImages/bwImage1.png').size
video = cv2.VideoWriter(vid_name+'_bw_ascii.mp4',cv2.VideoWriter_fourcc('m', 'p', '4', 'v'),int(fps),res)
for j in range(1,number_images+1):
print("Writing frames... [{0}/{1}]".format(j,number_images+1))
video.write(cv2.imread(vid_name+'_bwTextImages/bwImage{0}.png'.format(str(j))))
video.release()
print("BW ASCII Video Exported...")
def main(video_path):
video_path=str(video_path)
vid_name=video_path.split(sep="/")
vid_name=str(vid_name[len(vid_name)-1])
vid_name=vid_name.removesuffix(".mp4")
generate_img = generate_html = generate_txt = generate_bwhtml = generate_bwtxt = True
img_exist = os.path.isdir(vid_name+"_Images/")
bwhtml_exist = os.path.isdir(vid_name+'_bwHtmlImages/')
html_exist = os.path.isdir(vid_name+'_HtmlImages/')
bwtxt_exist = os.path.isdir(vid_name+'_bwTextImages/')
txt_exist = os.path.isdir(vid_name+'_TextImages/')
print("Default Charset:")
print("[' ','.',':','-','=','+','`',''','*','#','%','@','&']")
func=input("Use Default Charset? [y/n]: ")
if func == "y":
print("Using Default Charset...")
elif func == "n":
charset_foobar=str(input("Enter Charset [seperated by commas]: "))
charset=[" "]
for i in charset_foobar.split(','):
charset.append(i.strip())
print("Using Custom Charset:")
print(charset)
if img_exist:
func=input("Use cached PNG? [y/n]: ")
if func == "y":
generate_img=False
elif func == "n":
shutil.rmtree(vid_name+"_Images", ignore_errors=True)
generate_img=True
img_exist=True
if html_exist:
func=input("Use cached HTML? [y/n]: ")
if func == "y":
generate_html=False
elif func == "n":
shutil.rmtree(vid_name+"_HtmlImages", ignore_errors=True)
os.mkdir(vid_name+'_HtmlImages')
generate_html=True
if txt_exist:
func=input("Use cached TXT JPG? [y/n]: ")
if func == "y":
generate_txt=False
elif func == "n":
shutil.rmtree(vid_name+"_TextImages", ignore_errors=True)
os.mkdir(vid_name+'_TextImages')
generate_txt=True
if bwhtml_exist:
func=input("Use cached BW HTML? [y/n]: ")
if func == "y":
generate_bwhtml=False
elif func == "n":
shutil.rmtree(vid_name+"_bwHtmlImages", ignore_errors=True)
os.mkdir(vid_name+'_bwHtmlImages')
generate_bwhtml=True
if bwtxt_exist:
func=input("Use cached BW TXT JPG? [y/n]: ")
if func == "y":
generate_bwtxt=False
elif func == "n":
shutil.rmtree(vid_name+"_bwTextImages", ignore_errors=True)
os.mkdir(vid_name+'_bwTextImages')
generate_bwtxt=True
if bwhtml_exist==False:
print(html_exist)
os.mkdir(vid_name+'_bwHtmlImages')
if html_exist==False:
os.mkdir(vid_name+'_HtmlImages')
if bwtxt_exist==False:
os.mkdir(vid_name+'_bwTextImages')
if txt_exist==False:
os.mkdir(vid_name+'_TextImages')
fps,number_images = vid_to_img(video_path,vid_name,generate_img)
for i in range(1,number_images+1):
print("Rendering... [{0}/{1}]".format(i,number_images+1))
image = get_image_info(vid_name+'_Images/Image{0}.png'.format(str(i)))
correctedImage = correctSize(image)
bw_image = grayscale_image(correctedImage)
converted_list = ascii_conversion(bw_image)
color_list = get_color(correctedImage)
if generate_bwhtml:
bw_ascii(converted_list, correctedImage,i,vid_name)
if generate_html:
rgb_ascii(converted_list, correctedImage,color_list,i,vid_name)
if generate_bwtxt:
imgkit.from_file(vid_name+'_bwHtmlImages/bwHtml{0}.html'.format(str(i)), vid_name+'_bwTextImages/bwImage{0}.png'.format(str(i)))
if generate_txt:
imgkit.from_file(vid_name+'_HtmlImages/Html{0}.html'.format(str(i)), vid_name+'_TextImages/Image{0}.png'.format(str(i)))
print("Rendering complete!")
export_video(vid_name, fps, number_images)
if len(sys.argv) != 2:
print("Usage: ./converter.py <video_path>")
sys.exit()
video_path = str(sys.argv[1])
if __name__ == '__main__':
main(video_path)