forked from TheScienceElf/Video-to-Text
-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.py
272 lines (196 loc) · 6.52 KB
/
convert.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
import cv2
import numpy as np
import time
import multiprocessing
from joblib import Parallel, delayed
aspect_ratio = 16 / 9
#Dimensions of the output in terminal characters
width = 80
height = int(width / (2 * aspect_ratio))
# Framerate of the source and output video
src_FPS = 30
dest_FPS = 15
num_cores = multiprocessing.cpu_count()
cap = cv2.VideoCapture('vid.mp4')
frames = []
#Our characters, and their approximate brightness values
charSet = " ,(S#g@"
levels = [0.000, 1.060, 2.167, 3.036, 3.977, 4.730, 6.000]
numChrs = len(charSet)
# Converts a greyscale video frame into a dithered 7-color frame
def processFrame(scaled):
reduced = scaled * 6. / 255
out = np.zeros((height, width), dtype= np.int8)
line = ''
for y in range(height):
for x in range(width):
level = min(6, max(0, int(reduced[y, x])))
error = reduced[y, x] - levels[level]
err16 = error / 16
if (x + 1) < width:
reduced[y , x + 1] += 7 * err16
if (y + 1) < height:
reduced[y + 1, x ] += 5 * err16
if (x + 1) < width:
reduced[y + 1, x + 1] += 1 * err16
if (x - 1) > 0:
reduced[y + 1, x - 1] += 3 * err16
out[y, x] = level
return out
# Prints out a frame in ASCII
def toStr(frame):
line = ''
for y in range(height):
for x in range(width):
line += charSet[frame[y, x]]
line += '\n'
return line
# Compute the prediction matrix for each character combination
# Each row in this matrix corresponds with a character, and lists
# in decreasing order, the next most likely character to follow this one
#
# We also convert the provided frame to this new markov encoding, and provide
# the count of each prediction rank to be passed to the huffman encoding
def computeMarkov(frame):
mat = np.zeros((numChrs, numChrs)).astype(np.uint16)
h, w = frame.shape
prevChar = 0
for y in range(h):
for x in range(w):
char = frame[y, x]
mat[prevChar, char] += 1
prevChar = char
ranks = np.zeros((numChrs, numChrs)).astype(np.uint16)
for i in range(numChrs):
ranks[i][mat[i].argsort()] = 6 - np.arange(numChrs)
cnt = np.zeros(numChrs).astype(np.uint16)
out = np.zeros_like(frame)
prevChar = 0
for y in range(h):
for x in range(w):
char = frame[y, x]
out[y, x] = ranks[prevChar, char]
cnt[out[y, x]] += 1
prevChar = char
return out, ranks, cnt
# Computes Huffman encodings based on the counts of each number in the frame
def computeHuffman(cnts):
codes = []
sizes = []
tree = []
for i in range(len(cnts)):
codes.append('')
sizes.append((cnts[i], [i], i))
tree.append((i, i))
sizes = sorted(sizes, reverse = True)
while(len(sizes) > 1):
# Take the two least frequent entries
right = sizes.pop()
left = sizes.pop()
(lnum, lchars, ltree) = left
(rnum, rchars, rtree) = right
# Add a new tree node
tree.append((ltree, rtree))
# Update the encodings
for char in lchars:
codes[char] = '0' + codes[char]
for char in rchars:
codes[char] = '1' + codes[char]
# Merge these entries
new = (lnum + rnum, lchars + rchars, len(tree) - 1)
# Find the position in the list to inser these entries
for insertPos in range(len(sizes) + 1):
# Append if we hit the end of the list
if(insertPos == len(sizes)):
sizes.append(new)
break
cnt, _, _ = sizes[insertPos]
if(cnt <= lnum + rnum):
sizes.insert(insertPos, new)
break
return codes, tree
# Take a markov frame and an array of huffman encodings, and create an array of
# bytes corresponding to the compressed frame
def convertHuffman(markovFrame, codes):
out = ''
h, w = frame.shape
for y in range(h):
for x in range(w):
out = out + codes[markovFrame[y, x]]
# Pad this bit-string to be byte-aligned
padding = (8 - (len(out) % 8)) % 8
out += ("0" * padding)
# Convert each octet to a char
compressed = []
for i in range(0, len(out), 8):
byte = out[i:i+8]
char = 0
for bit in range(8):
char *= 2
if byte[bit] == "1":
char += 1
compressed.append(char)
return compressed
# Converts a rank matrix into a binary format to be stored in the output file
def encodeMatrix(ranks):
out = []
for row in ranks:
encoding = 0
fact = 1
idxs = list(range(len(charSet)))
for rank in range(len(charSet)):
rank = list(row).index(rank)
encoding += idxs.index(rank) * fact
fact *= len(idxs)
idxs.remove(rank)
low_byte = int(encoding) % 256
high_byte = (encoding - low_byte) // 256
out.append(high_byte)
out.append(low_byte)
return out
# Converts the huffman tree into a binary format to be stored in the output file
def encodeTree(tree):
tree = tree[len(charSet):]
out = []
for (l, r) in tree:
out.append(l * 16 + r)
return out
# Load all frames into memory, then convert them to greyscale and resize them to
# our terminal dimensions
vidFrames = []
while(cap.isOpened()):
if (len(vidFrames) % 500) == 0:
print('Loading frame %i' % len(vidFrames))
# Skip frames to reach target framerate
for i in range(int(src_FPS / dest_FPS)):
ret, frame = cap.read()
if frame is None:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
scaled = cv2.resize(gray, (width, height))
vidFrames.append(scaled)
# Compute dithering for all frames in parallel
print('Dithering Frames')
frames = Parallel(n_jobs=num_cores)(delayed(processFrame)(i) for i in vidFrames)
# Compute markov and huffman encoding for all frames
print('Encoding Frames')
out = ''
size = 0
with open('data', 'wb') as filehandle:
for frame in frames:
markovFrame, ranks, cnts = computeMarkov(frame)
codes, tree = computeHuffman(cnts)
chars = convertHuffman(markovFrame, codes)
matrixData = encodeMatrix(ranks)
treeData = encodeTree(tree)
filehandle.write(bytearray(matrixData))
filehandle.write(bytearray(treeData))
filehandle.write(bytearray(chars))
size += len(matrixData) + len(treeData) + len(chars)
# Print the size of the output file in human-readable form
if size > 1048576:
print('%.1f MB' % (size / 1048576))
elif size > 1024:
print('%.1f KB' % (size / 1024))
else:
print('%i B' % (size))