-
Notifications
You must be signed in to change notification settings - Fork 43
/
touhou_bad_apple_v4.5.py
181 lines (139 loc) · 5.95 KB
/
touhou_bad_apple_v4.5.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
import cv2
import time
import sys
from PIL import Image
from multiprocessing import Process
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame
import fpstimer
import moviepy.editor as mp
ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", " "]
frame_size = 150
frame_interval = 1.0 / 30.75
ASCII_LIST = []
def play_audio(path):
pygame.init()
pygame.mixer.pre_init(44100, -16, 2, 2048)
pygame.mixer.init()
pygame.mixer.music.load(path)
pygame.mixer.music.play()
def play_video(total_frames):
# os.system('color F0')
os.system('mode 150, 500')
timer = fpstimer.FPSTimer(30)
start_frame = 0
for frame_number in range(start_frame, total_frames):
sys.stdout.write("\r" + ASCII_LIST[frame_number])
timer.sleep()
# os.system('color 07')
# Extract frames from video
def extract_transform_generate(video_path, start_frame, number_of_frames=1000):
capture = cv2.VideoCapture(video_path)
capture.set(1, start_frame) # Points cap to target frame
current_frame = start_frame
frame_count = 1
ret, image_frame = capture.read()
while ret and frame_count <= number_of_frames:
ret, image_frame = capture.read()
try:
image = Image.fromarray(image_frame)
ascii_characters = pixels_to_ascii(greyscale(resize_image(image))) # get ascii characters
pixel_count = len(ascii_characters)
ascii_image = "\n".join(
[ascii_characters[index:(index + frame_size)] for index in range(0, pixel_count, frame_size)])
ASCII_LIST.append(ascii_image)
except Exception as error:
continue
progress_bar(frame_count, number_of_frames)
frame_count += 1 # increases internal frame counter
current_frame += 1 # increases global frame counter
capture.release()
# Progress bar code is courtesy of StackOverflow user: Aravind Voggu.
# Link to thread: https://stackoverflow.com/questions/6169217/replace-console-output-in-python
def progress_bar(current, total, barLength=25):
progress = float(current) * 100 / total
arrow = '#' * int(progress / 100 * barLength - 1)
spaces = ' ' * (barLength - len(arrow))
sys.stdout.write('\rProgress: [%s%s] %d%% Frame %d of %d frames' % (arrow, spaces, progress, current, total))
# Resize image
def resize_image(image_frame):
width, height = image_frame.size
aspect_ratio = (height / float(width * 2.5)) # 2.5 modifier to offset vertical scaling on console
new_height = int(aspect_ratio * frame_size)
resized_image = image_frame.resize((frame_size, new_height))
# print('Aspect ratio: %f' % aspect_ratio)
# print('New dimensions %d %d' % resized_image.size)
return resized_image
# Greyscale
def greyscale(image_frame):
return image_frame.convert("L")
# Convert pixels to ascii
def pixels_to_ascii(image_frame):
pixels = image_frame.getdata()
characters = "".join([ASCII_CHARS[pixel // 25] for pixel in pixels])
return characters
# Open image => Resize => Greyscale => Convert to ASCII => Store in text file
def ascii_generator(image_path, start_frame, number_of_frames):
current_frame = start_frame
while current_frame <= number_of_frames:
path_to_image = image_path + '/BadApple_' + str(current_frame) + '.jpg'
image = Image.open(path_to_image)
ascii_characters = pixels_to_ascii(greyscale(resize_image(image))) # get ascii characters
pixel_count = len(ascii_characters)
ascii_image = "\n".join(
[ascii_characters[index:(index + frame_size)] for index in range(0, pixel_count, frame_size)])
file_name = r"TextFiles/" + "bad_apple" + str(current_frame) + ".txt"
try:
with open(file_name, "w") as f:
f.write(ascii_image)
except FileNotFoundError:
continue
current_frame += 1
def preflight_operations(path):
if os.path.exists(path):
path_to_video = path.strip()
cap = cv2.VideoCapture(path_to_video)
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
cap.release()
video = mp.VideoFileClip(path_to_video)
path_to_audio = 'audio.mp3'
video.audio.write_audiofile(path_to_audio)
frames_per_process = int(total_frames / 4)
process1_end_frame = frames_per_process
process2_start_frame = process1_end_frame + 1
process2_end_frame = process2_start_frame + frames_per_process
process3_start_frame = process2_end_frame + 1
process3_end_frame = process3_start_frame + frames_per_process
process4_start_frame = process3_end_frame + 1
process4_end_frame = total_frames - 1
start_time = time.time()
sys.stdout.write('Beginning ASCII generation...\n')
extract_transform_generate(path_to_video, 1, process4_end_frame)
execution_time = time.time() - start_time
sys.stdout.write('ASCII generation completed! ASCII generation time: ' + str(execution_time))
return total_frames
else:
sys.stdout.write('Warning file not found!\n')
def main():
while True:
sys.stdout.write('==============================================================\n')
sys.stdout.write('Select option: \n')
sys.stdout.write('1) Play\n')
sys.stdout.write('2) Exit\n')
sys.stdout.write('==============================================================\n')
user_input = str(input("Your option: "))
user_input.strip() # removes trailing whitespaces
if user_input == '1':
user_input = str(input("Please enter the video file name (file must be in root!): "))
total_frames = preflight_operations(user_input)
play_audio('audio.mp3')
play_video(total_frames=total_frames)
elif user_input == '2':
exit()
continue
else:
sys.stdout.write('Unknown input!\n')
continue
if __name__ == '__main__':
main()