This repository was archived by the owner on Feb 6, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimencode.py
More file actions
executable file
·209 lines (171 loc) · 6.35 KB
/
Copy pathsimencode.py
File metadata and controls
executable file
·209 lines (171 loc) · 6.35 KB
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
#!/usr/bin/env python3
#
# simtv - an Arduino TV Simulator
#
# Copyright (C) 2018 Richard "Shred" Körber
# https://github.com/shred/simtv
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import argparse
import colorsys
import cv2
import math
import numpy
def streamVideo(cap, targetFps, maxFrames):
"""Streams the capture as one pixel (r,g,b) tuple per frame."""
frameCount = 0
targetFrameCount = 0
while maxFrames is None or frameCount < maxFrames:
ret, frame = cap.read()
if not ret:
break
frameCount = cap.get(cv2.CAP_PROP_POS_FRAMES)
position = cap.get(cv2.CAP_PROP_POS_MSEC)
print('Frame: %7d %3d:%02d -> %7d\r' % (
frameCount,
(int) (position / 1000 / 60),
(int) (position / 1000 % 60),
targetFrameCount), end='', flush=True)
if position >= targetFrameCount * 1000 / targetFps:
pixel = numpy.average(numpy.average(frame, axis=0), axis=0)
targetFrameCount += 1
yield (pixel[2] / 256, pixel[1] / 256, pixel[0] / 256)
print()
def streamPixels(file, targetFps, maxFrames):
"""Streams a video file as pixel stream with the given target FPS."""
cap = cv2.VideoCapture(file)
try:
if cap.isOpened():
for color in streamVideo(cap, targetFps, maxFrames):
yield color
finally:
cap.release()
def streamColorData(stream, harddiff, softdiff, brightness):
"""Converts a pixel stream to a data stream that is readable for the Arduino sketch."""
previousColor = None
writtenColor = None
count = 0
for color in stream:
if writtenColor is None:
yield convertColor(0, color, brightness)
writtenColor = color
elif isColorCut(color, previousColor, harddiff / 3, harddiff):
if count > 0:
yield convertColor(count - 1, color, brightness)
yield convertColor(0, color, brightness)
writtenColor = color
count = 0
elif count > 2 and isColorCut(color, writtenColor, softdiff / 2, softdiff):
yield convertColor(count, color, brightness)
writtenColor = color
count = 0
elif count == 15:
yield convertColor(count, color, brightness)
writtenColor = color
count = 0
else:
count += 1
previousColor = color
yield convertColor(count, previousColor, brightness)
def convertColor(step, color, brightness):
"""Returns a tuple of the color and step."""
gcolor = [max(min(int(round(c * brightness * 16)), 15), 0) for c in color]
return (step if step <= 15 else 15, gcolor[0], gcolor[1], gcolor[2])
def isColorCut(c1, c2, hueLimit, brightLimit):
"""Checks if color c1 and color c2 difference exceed the given limits."""
hsv1 = colorsys.rgb_to_hsv(c1[0], c1[1], c1[2])
hsv2 = colorsys.rgb_to_hsv(c2[0], c2[1], c2[2])
# hue wraps around between 0.0 and 1.0
hue1 = hsv1[0] + (1.0 if hsv1[0] < 0.5 and hsv2[0] >= 0.5 else 0.0)
hue2 = hsv2[0] + (1.0 if hsv2[0] < 0.5 and hsv1[0] >= 0.5 else 0.0)
dh = math.fabs(hue1 - hue2)
db = math.fabs(hsv1[2] - hsv2[2])
return dh >= hueLimit or db >= brightLimit
def writeSource(out, filename, fps, gamma, stream):
"""Writes out the stream.h source code."""
out.write("""/*
* Converted movie stream: %s
*
* Generated by simencode.py, do not edit!
*/
#include <avr/pgmspace.h>
const unsigned int FPS = %d;
PROGMEM const byte GAMMA[] = {
""" % (filename, fps))
for cv in range(16):
if cv > 0:
out.write(", ")
out.write("%d" % (max(min(round(math.pow(cv / 15, gamma) * 255), 255), 0)))
out.write("\n};\n\nPROGMEM const unsigned int DATA[] = {");
count = 0
for c in stream:
if count > 0:
out.write(", ")
if count % 8 == 0:
out.write("\n ")
out.write("0x%1X%1X%1X%1X" % c)
count += 1
out.write("\n};\n")
parser = argparse.ArgumentParser(description='Convert movie to SimTV source')
parser.add_argument('file',
nargs='?',
help='input movie file')
parser.add_argument('-o', '--out',
dest='out',
default='./simtv/stream.h',
help='output source file (default: simtv/stream.h)')
parser.add_argument('-x', '--frames',
dest='frames',
type=int,
help='maximum number of frames to convert')
parser.add_argument('-r', '--fps',
type=int,
default=10,
choices=range(1, 51),
metavar="[1-50]",
dest='fps',
help='target frames per second (default: 10)')
parser.add_argument('-g', '--gamma',
dest='gamma',
type=float,
default=2.2,
help='gamma correction (default: 2.2)')
parser.add_argument('-b', '--brightness',
dest='brightness',
type=float,
default=1.0,
help='brightness correction (default: 1.0)')
parser.add_argument('-S', '--soft',
dest='soft',
type=int,
default=7,
choices=range(0, 101),
metavar="[0-100]",
help='hue/brightness threshold for soft color cuts (default: 7%%)')
parser.add_argument('-H', '--hard',
dest='hard',
type=int,
default=20,
choices=range(0, 101),
metavar="[0-100]",
help='hue/brightness threshold for hard color cuts (default: 20%%)')
args = parser.parse_args()
with open(args.out, 'w') as w:
writeSource(w, args.file, args.fps, args.gamma, \
streamColorData( \
streamPixels(args.file, args.fps, args.frames), \
args.hard / 100, \
args.soft / 100, \
args.brightness))