-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmp4_to_ascii.py
66 lines (55 loc) · 1.91 KB
/
mp4_to_ascii.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
import curses
import time
import cv2
from PIL import Image
import numpy as np
import os
ASCII_CHARS = np.array(list(" .,-~:;=!*#$@"))
IMG_WIDTH = 50
def extract_frame(video_path: str, frame_rate: int):
output_dir = 'output_frames'
os.makedirs(output_dir, exist_ok=True)
cap = cv2.VideoCapture(video_path)
frame_count = 0
while True:
ret, frame = cap.read()
if not ret:
break
if frame_count % frame_rate == 0:
frame_path = os.path.join(output_dir, f'{frame_count:04d}.png')
cv2.imwrite(frame_path, frame)
frame_count += 1
cap.release()
return frame_count
def main():
global ASCII_CHARS
print("please input the path of the video")
video_path = input()
print("please input the fps you want")
fps = min(int(input()), 60)
print("color reverse? (y/n)")
color_reverse = input() == 'y'
if color_reverse:
ASCII_CHARS = ASCII_CHARS[::-1]
frame_rate = int(60 / fps)
frame_count = extract_frame(video_path, frame_rate)
ascii_arts: list[str] = []
for i in range(0, int(frame_count/frame_rate)):
frame_path = os.path.join('output_frames', f'{i*frame_rate:04d}.png')
ascii_art = ascii_generator(frame_path)
ascii_arts.append(ascii_art)
curses.wrapper(display_ascii_arts, ascii_arts, fps)
def ascii_generator(img_path: str):
img = Image.open(img_path).convert("L")
img = img.resize((IMG_WIDTH * 2, int(IMG_WIDTH * img.height / img.width)))
ascii_art = ASCII_CHARS[(np.array(img) / 255 * (len(ASCII_CHARS) - 1)).astype(int)]
return "\n".join("".join(row) for row in ascii_art)
def display_ascii_arts(stdscr: curses.window, ascii_arts: list[str], fps: int):
stdscr.clear()
for ascii_art in ascii_arts:
stdscr.clear()
stdscr.addstr(0, 0, ascii_art)
stdscr.refresh()
time.sleep(1 / fps)
if __name__ == "__main__":
main()