| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
""" |
| 8 |
Provides a function (write_swf) to store a series of numpy arrays in an |
| 9 |
SWF movie, that can be played on a wide range of OS's. |
| 10 |
|
| 11 |
In desperation of wanting to share animated images, and then lacking a good |
| 12 |
writer for animated gif or .avi, I decided to look into SWF. This format |
| 13 |
is very well documented. |
| 14 |
|
| 15 |
This is a pure python module to create an SWF file that shows a series |
| 16 |
of images. The images are stored using the DEFLATE algorithm (same as |
| 17 |
PNG and ZIP and which is included in the standard Python distribution). |
| 18 |
As this compression algorithm is much more effective than that used in |
| 19 |
GIF images, we obtain better quality (24 bit colors + alpha channel) |
| 20 |
while still producesing smaller files (a test showed ~75%). Although |
| 21 |
SWF also allows for JPEG compression, doing so would probably require |
| 22 |
a third party library for the JPEG encoding/decoding, we could |
| 23 |
perhaps do this via Pillow or freeimage. |
| 24 |
|
| 25 |
sources and tools: |
| 26 |
|
| 27 |
- SWF on wikipedia |
| 28 |
- Adobes "SWF File Format Specification" version 10 |
| 29 |
(http://www.adobe.com/devnet/swf/pdf/swf_file_format_spec_v10.pdf) |
| 30 |
- swftools (swfdump in specific) for debugging |
| 31 |
- iwisoft swf2avi can be used to convert swf to avi/mpg/flv with really |
| 32 |
good quality, while file size is reduced with factors 20-100. |
| 33 |
A good program in my opinion. The free version has the limitation |
| 34 |
of a watermark in the upper left corner. |
| 35 |
|
| 36 |
""" |
| 37 |
|
| 38 |
import os |
| 39 |
import zlib |
| 40 |
import time |
| 41 |
import logging |
| 42 |
|
| 43 |
import numpy as np |
| 44 |
|
| 45 |
logger = logging.getLogger(__name__) |
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
class BitArray: |
| 54 |
"""Dynamic array of bits that automatically resizes |
| 55 |
with factors of two. |
| 56 |
Append bits using .append() or += |
| 57 |
You can reverse bits using .reverse() |
| 58 |
""" |
| 59 |
|
| 60 |
def __init__(self, initvalue=None): |
| 61 |
self.data = np.zeros((16,), dtype=np.uint8) |
| 62 |
self._len = 0 |
| 63 |
if initvalue is not None: |
| 64 |
self.append(initvalue) |
| 65 |
|
| 66 |
def __len__(self): |
| 67 |
return self._len |
| 68 |
|
| 69 |
def __repr__(self): |
| 70 |
return self.data[: self._len].tobytes().decode("ascii") |
| 71 |
|
| 72 |
def _checkSize(self): |
| 73 |
|
| 74 |
arraylen = self.data.shape[0] |
| 75 |
if self._len >= arraylen: |
| 76 |
tmp = np.zeros((arraylen * 2,), dtype=np.uint8) |
| 77 |
tmp[: self._len] = self.data[: self._len] |
| 78 |
self.data = tmp |
| 79 |
|
| 80 |
def __add__(self, value): |
| 81 |
self.append(value) |
| 82 |
return self |
| 83 |
|
| 84 |
def append(self, bits): |
| 85 |
|
| 86 |
if isinstance(bits, BitArray): |
| 87 |
bits = str(bits) |
| 88 |
if isinstance(bits, int): |
| 89 |
bits = str(bits) |
| 90 |
if not isinstance(bits, str): |
| 91 |
raise ValueError("Append bits as strings or integers!") |
| 92 |
|
| 93 |
|
| 94 |
for bit in bits: |
| 95 |
self.data[self._len] = ord(bit) |
| 96 |
self._len += 1 |
| 97 |
self._checkSize() |
| 98 |
|
| 99 |
def reverse(self): |
| 100 |
"""In-place reverse.""" |
| 101 |
tmp = self.data[: self._len].copy() |
| 102 |
self.data[: self._len] = tmp[::-1] |
| 103 |
|
| 104 |
def tobytes(self): |
| 105 |
"""Convert to bytes. If necessary, |
| 106 |
zeros are padded to the end (right side). |
| 107 |
""" |
| 108 |
bits = str(self) |
| 109 |
|
| 110 |
|
| 111 |
nbytes = 0 |
| 112 |
while nbytes * 8 < len(bits): |
| 113 |
nbytes += 1 |
| 114 |
|
| 115 |
bits = bits.ljust(nbytes * 8, "0") |
| 116 |
|
| 117 |
|
| 118 |
bb = bytes() |
| 119 |
for i in range(nbytes): |
| 120 |
tmp = int(bits[i * 8 : (i + 1) * 8], 2) |
| 121 |
bb += int2uint8(tmp) |
| 122 |
|
| 123 |
|
| 124 |
return bb |
| 125 |
|
| 126 |
|
| 127 |
def int2uint32(i): |
| 128 |
return int(i).to_bytes(4, "little") |
| 129 |
|
| 130 |
|
| 131 |
def int2uint16(i): |
| 132 |
return int(i).to_bytes(2, "little") |
| 133 |
|
| 134 |
|
| 135 |
def int2uint8(i): |
| 136 |
return int(i).to_bytes(1, "little") |
| 137 |
|
| 138 |
|
| 139 |
def int2bits(i, n=None): |
| 140 |
"""convert int to a string of bits (0's and 1's in a string), |
| 141 |
pad to n elements. Convert back using int(ss,2).""" |
| 142 |
ii = i |
| 143 |
|
| 144 |
|
| 145 |
bb = BitArray() |
| 146 |
while ii > 0: |
| 147 |
bb += str(ii % 2) |
| 148 |
ii = ii >> 1 |
| 149 |
bb.reverse() |
| 150 |
|
| 151 |
|
| 152 |
if n is not None: |
| 153 |
if len(bb) > n: |
| 154 |
raise ValueError("int2bits fail: len larger than padlength.") |
| 155 |
bb = str(bb).rjust(n, "0") |
| 156 |
|
| 157 |
|
| 158 |
return BitArray(bb) |
| 159 |
|
| 160 |
|
| 161 |
def bits2int(bb, n=8): |
| 162 |
|
| 163 |
value = "" |
| 164 |
|
| 165 |
|
| 166 |
for i in range(len(bb)): |
| 167 |
b = bb[i : i + 1] |
| 168 |
tmp = bin(ord(b))[2:] |
| 169 |
|
| 170 |
value = tmp.rjust(8, "0") + value |
| 171 |
|
| 172 |
|
| 173 |
return int(value[:n], 2) |
| 174 |
|
| 175 |
|
| 176 |
def get_type_and_len(bb): |
| 177 |
"""bb should be 6 bytes at least |
| 178 |
Return (type, length, length_of_full_tag) |
| 179 |
""" |
| 180 |
|
| 181 |
value = "" |
| 182 |
|
| 183 |
|
| 184 |
for i in range(2): |
| 185 |
b = bb[i : i + 1] |
| 186 |
tmp = bin(ord(b))[2:] |
| 187 |
|
| 188 |
value = tmp.rjust(8, "0") + value |
| 189 |
|
| 190 |
|
| 191 |
type = int(value[:10], 2) |
| 192 |
L = int(value[10:], 2) |
| 193 |
L2 = L + 2 |
| 194 |
|
| 195 |
|
| 196 |
if L == 63: |
| 197 |
value = "" |
| 198 |
for i in range(2, 6): |
| 199 |
b = bb[i : i + 1] |
| 200 |
tmp = bin(ord(b))[2:] |
| 201 |
|
| 202 |
value = tmp.rjust(8, "0") + value |
| 203 |
L = int(value, 2) |
| 204 |
L2 = L + 6 |
| 205 |
|
| 206 |
|
| 207 |
return type, L, L2 |
| 208 |
|
| 209 |
|
| 210 |
def signedint2bits(i, n=None): |
| 211 |
"""convert signed int to a string of bits (0's and 1's in a string), |
| 212 |
pad to n elements. Negative numbers are stored in 2's complement bit |
| 213 |
patterns, thus positive numbers always start with a 0. |
| 214 |
""" |
| 215 |
|
| 216 |
|
| 217 |
ii = i |
| 218 |
if i < 0: |
| 219 |
|
| 220 |
ii = abs(ii) - 1 |
| 221 |
|
| 222 |
|
| 223 |
bb = BitArray() |
| 224 |
while ii > 0: |
| 225 |
bb += str(ii % 2) |
| 226 |
ii = ii >> 1 |
| 227 |
bb.reverse() |
| 228 |
|
| 229 |
|
| 230 |
bb = "0" + str(bb) |
| 231 |
if n is not None: |
| 232 |
if len(bb) > n: |
| 233 |
raise ValueError("signedint2bits fail: len larger than padlength.") |
| 234 |
bb = bb.rjust(n, "0") |
| 235 |
|
| 236 |
|
| 237 |
if i < 0: |
| 238 |
bb = bb.replace("0", "x").replace("1", "0").replace("x", "1") |
| 239 |
|
| 240 |
|
| 241 |
return BitArray(bb) |
| 242 |
|
| 243 |
|
| 244 |
def twits2bits(arr): |
| 245 |
"""Given a few (signed) numbers, store them |
| 246 |
as compactly as possible in the wat specifief by the swf format. |
| 247 |
The numbers are multiplied by 20, assuming they |
| 248 |
are twits. |
| 249 |
Can be used to make the RECT record. |
| 250 |
""" |
| 251 |
|
| 252 |
|
| 253 |
maxlen = 1 |
| 254 |
for i in arr: |
| 255 |
tmp = len(signedint2bits(i * 20)) |
| 256 |
if tmp > maxlen: |
| 257 |
maxlen = tmp |
| 258 |
|
| 259 |
|
| 260 |
bits = int2bits(maxlen, 5) |
| 261 |
for i in arr: |
| 262 |
bits += signedint2bits(i * 20, maxlen) |
| 263 |
|
| 264 |
return bits |
| 265 |
|
| 266 |
|
| 267 |
def floats2bits(arr): |
| 268 |
"""Given a few (signed) numbers, convert them to bits, |
| 269 |
stored as FB (float bit values). We always use 16.16. |
| 270 |
Negative numbers are not (yet) possible, because I don't |
| 271 |
know how the're implemented (ambiguity). |
| 272 |
""" |
| 273 |
bits = int2bits(31, 5) |
| 274 |
for i in arr: |
| 275 |
if i < 0: |
| 276 |
raise ValueError("Dit not implement negative floats!") |
| 277 |
i1 = int(i) |
| 278 |
i2 = i - i1 |
| 279 |
bits += int2bits(i1, 15) |
| 280 |
bits += int2bits(i2 * 2**16, 16) |
| 281 |
return bits |
| 282 |
|
| 283 |
|
| 284 |
|
| 285 |
|
| 286 |
|
| 287 |
class Tag: |
| 288 |
def __init__(self): |
| 289 |
self.bytes = bytes() |
| 290 |
self.tagtype = -1 |
| 291 |
|
| 292 |
def process_tag(self): |
| 293 |
"""Implement this to create the tag.""" |
| 294 |
raise NotImplementedError() |
| 295 |
|
| 296 |
def get_tag(self): |
| 297 |
"""Calls processTag and attaches the header.""" |
| 298 |
self.process_tag() |
| 299 |
|
| 300 |
|
| 301 |
bits = int2bits(self.tagtype, 10) |
| 302 |
|
| 303 |
|
| 304 |
bits += "1" * 6 |
| 305 |
|
| 306 |
bb = int2uint16(int(str(bits), 2)) |
| 307 |
|
| 308 |
|
| 309 |
bb += int2uint32(len(self.bytes)) |
| 310 |
|
| 311 |
|
| 312 |
bb += self.bytes |
| 313 |
return bb |
| 314 |
|
| 315 |
def make_rect_record(self, xmin, xmax, ymin, ymax): |
| 316 |
"""Simply uses makeCompactArray to produce |
| 317 |
a RECT Record.""" |
| 318 |
return twits2bits([xmin, xmax, ymin, ymax]) |
| 319 |
|
| 320 |
def make_matrix_record(self, scale_xy=None, rot_xy=None, trans_xy=None): |
| 321 |
|
| 322 |
if scale_xy is None and rot_xy is None and trans_xy is None: |
| 323 |
return "0" * 8 |
| 324 |
|
| 325 |
|
| 326 |
bits = BitArray() |
| 327 |
|
| 328 |
|
| 329 |
if scale_xy: |
| 330 |
bits += "1" |
| 331 |
bits += floats2bits([scale_xy[0], scale_xy[1]]) |
| 332 |
else: |
| 333 |
bits += "0" |
| 334 |
|
| 335 |
|
| 336 |
if rot_xy: |
| 337 |
bits += "1" |
| 338 |
bits += floats2bits([rot_xy[0], rot_xy[1]]) |
| 339 |
else: |
| 340 |
bits += "0" |
| 341 |
|
| 342 |
|
| 343 |
if trans_xy: |
| 344 |
bits += twits2bits([trans_xy[0], trans_xy[1]]) |
| 345 |
else: |
| 346 |
bits += twits2bits([0, 0]) |
| 347 |
|
| 348 |
|
| 349 |
return bits |
| 350 |
|
| 351 |
|
| 352 |
|
| 353 |
|
| 354 |
|
| 355 |
class ControlTag(Tag): |
| 356 |
def __init__(self): |
| 357 |
Tag.__init__(self) |
| 358 |
|
| 359 |
|
| 360 |
class FileAttributesTag(ControlTag): |
| 361 |
def __init__(self): |
| 362 |
ControlTag.__init__(self) |
| 363 |
self.tagtype = 69 |
| 364 |
|
| 365 |
def process_tag(self): |
| 366 |
self.bytes = "\x00".encode("ascii") * (1 + 3) |
| 367 |
|
| 368 |
|
| 369 |
class ShowFrameTag(ControlTag): |
| 370 |
def __init__(self): |
| 371 |
ControlTag.__init__(self) |
| 372 |
self.tagtype = 1 |
| 373 |
|
| 374 |
def process_tag(self): |
| 375 |
self.bytes = bytes() |
| 376 |
|
| 377 |
|
| 378 |
class SetBackgroundTag(ControlTag): |
| 379 |
"""Set the color in 0-255, or 0-1 (if floats given).""" |
| 380 |
|
| 381 |
def __init__(self, *rgb): |
| 382 |
self.tagtype = 9 |
| 383 |
if len(rgb) == 1: |
| 384 |
rgb = rgb[0] |
| 385 |
self.rgb = rgb |
| 386 |
|
| 387 |
def process_tag(self): |
| 388 |
bb = bytes() |
| 389 |
for i in range(3): |
| 390 |
clr = self.rgb[i] |
| 391 |
if isinstance(clr, float): |
| 392 |
clr = clr * 255 |
| 393 |
bb += int2uint8(clr) |
| 394 |
self.bytes = bb |
| 395 |
|
| 396 |
|
| 397 |
class DoActionTag(Tag): |
| 398 |
def __init__(self, action="stop"): |
| 399 |
Tag.__init__(self) |
| 400 |
self.tagtype = 12 |
| 401 |
self.actions = [action] |
| 402 |
|
| 403 |
def append(self, action): |
| 404 |
self.actions.append(action) |
| 405 |
|
| 406 |
def process_tag(self): |
| 407 |
bb = bytes() |
| 408 |
|
| 409 |
for action in self.actions: |
| 410 |
action = action.lower() |
| 411 |
if action == "stop": |
| 412 |
bb += "\x07".encode("ascii") |
| 413 |
elif action == "play": |
| 414 |
bb += "\x06".encode("ascii") |
| 415 |
else: |
| 416 |
logger.warning("unknown action: %s" % action) |
| 417 |
|
| 418 |
bb += int2uint8(0) |
| 419 |
self.bytes = bb |
| 420 |
|
| 421 |
|
| 422 |
|
| 423 |
class DefinitionTag(Tag): |
| 424 |
counter = 0 |
| 425 |
|
| 426 |
def __init__(self): |
| 427 |
Tag.__init__(self) |
| 428 |
DefinitionTag.counter += 1 |
| 429 |
self.id = DefinitionTag.counter |
| 430 |
|
| 431 |
|
| 432 |
class BitmapTag(DefinitionTag): |
| 433 |
def __init__(self, im): |
| 434 |
DefinitionTag.__init__(self) |
| 435 |
self.tagtype = 36 |
| 436 |
|
| 437 |
|
| 438 |
|
| 439 |
|
| 440 |
|
| 441 |
|
| 442 |
|
| 443 |
if len(im.shape) == 3: |
| 444 |
if im.shape[2] in [3, 4]: |
| 445 |
tmp = np.ones((im.shape[0], im.shape[1], 4), dtype=np.uint8) * 255 |
| 446 |
for i in range(3): |
| 447 |
tmp[:, :, i + 1] = im[:, :, i] |
| 448 |
if im.shape[2] == 4: |
| 449 |
tmp[:, :, 0] = im[:, :, 3] |
| 450 |
else: |
| 451 |
raise ValueError("Invalid shape to be an image.") |
| 452 |
|
| 453 |
elif len(im.shape) == 2: |
| 454 |
tmp = np.ones((im.shape[0], im.shape[1], 4), dtype=np.uint8) * 255 |
| 455 |
for i in range(3): |
| 456 |
tmp[:, :, i + 1] = im[:, :] |
| 457 |
else: |
| 458 |
raise ValueError("Invalid shape to be an image.") |
| 459 |
|
| 460 |
|
| 461 |
|
| 462 |
self._data = zlib.compress(tmp.tobytes(), zlib.DEFLATED) |
| 463 |
self.imshape = im.shape |
| 464 |
|
| 465 |
def process_tag(self): |
| 466 |
|
| 467 |
bb = bytes() |
| 468 |
bb += int2uint16(self.id) |
| 469 |
bb += int2uint8(5) |
| 470 |
bb += int2uint16(self.imshape[1]) |
| 471 |
bb += int2uint16(self.imshape[0]) |
| 472 |
bb += self._data |
| 473 |
|
| 474 |
self.bytes = bb |
| 475 |
|
| 476 |
|
| 477 |
class PlaceObjectTag(ControlTag): |
| 478 |
def __init__(self, depth, idToPlace=None, xy=(0, 0), move=False): |
| 479 |
ControlTag.__init__(self) |
| 480 |
self.tagtype = 26 |
| 481 |
self.depth = depth |
| 482 |
self.idToPlace = idToPlace |
| 483 |
self.xy = xy |
| 484 |
self.move = move |
| 485 |
|
| 486 |
def process_tag(self): |
| 487 |
|
| 488 |
depth = self.depth |
| 489 |
xy = self.xy |
| 490 |
id = self.idToPlace |
| 491 |
|
| 492 |
|
| 493 |
bb = bytes() |
| 494 |
if self.move: |
| 495 |
bb += "\x07".encode("ascii") |
| 496 |
else: |
| 497 |
|
| 498 |
bb += "\x06".encode("ascii") |
| 499 |
bb += int2uint16(depth) |
| 500 |
bb += int2uint16(id) |
| 501 |
bb += self.make_matrix_record(trans_xy=xy).tobytes() |
| 502 |
self.bytes = bb |
| 503 |
|
| 504 |
|
| 505 |
class ShapeTag(DefinitionTag): |
| 506 |
def __init__(self, bitmapId, xy, wh): |
| 507 |
DefinitionTag.__init__(self) |
| 508 |
self.tagtype = 2 |
| 509 |
self.bitmapId = bitmapId |
| 510 |
self.xy = xy |
| 511 |
self.wh = wh |
| 512 |
|
| 513 |
def process_tag(self): |
| 514 |
"""Returns a defineshape tag. with a bitmap fill""" |
| 515 |
|
| 516 |
bb = bytes() |
| 517 |
bb += int2uint16(self.id) |
| 518 |
xy, wh = self.xy, self.wh |
| 519 |
tmp = self.make_rect_record(xy[0], wh[0], xy[1], wh[1]) |
| 520 |
bb += tmp.tobytes() |
| 521 |
|
| 522 |
|
| 523 |
|
| 524 |
|
| 525 |
bb += int2uint8(1) |
| 526 |
bb += "\x41".encode("ascii") |
| 527 |
bb += int2uint16(self.bitmapId) |
| 528 |
|
| 529 |
bb += self.make_matrix_record(scale_xy=(20, 20)).tobytes() |
| 530 |
|
| 531 |
|
| 532 |
|
| 533 |
|
| 534 |
|
| 535 |
|
| 536 |
|
| 537 |
bb += int2uint8(0) |
| 538 |
|
| 539 |
|
| 540 |
|
| 541 |
|
| 542 |
|
| 543 |
bb += "\x44".encode("ascii") |
| 544 |
|
| 545 |
self.bytes = bb |
| 546 |
|
| 547 |
|
| 548 |
|
| 549 |
bits = BitArray() |
| 550 |
bits += self.make_style_change_record(0, 1, moveTo=(self.wh[0], self.wh[1])) |
| 551 |
|
| 552 |
bits += self.make_straight_edge_record(-self.wh[0], 0) |
| 553 |
bits += self.make_straight_edge_record(0, -self.wh[1]) |
| 554 |
bits += self.make_straight_edge_record(self.wh[0], 0) |
| 555 |
bits += self.make_straight_edge_record(0, self.wh[1]) |
| 556 |
|
| 557 |
|
| 558 |
bits += self.make_end_shape_record() |
| 559 |
|
| 560 |
self.bytes += bits.tobytes() |
| 561 |
|
| 562 |
|
| 563 |
|
| 564 |
|
| 565 |
def make_style_change_record(self, lineStyle=None, fillStyle=None, moveTo=None): |
| 566 |
|
| 567 |
|
| 568 |
|
| 569 |
|
| 570 |
bits = BitArray() |
| 571 |
bits += "0" |
| 572 |
bits += "0" |
| 573 |
if lineStyle: |
| 574 |
bits += "1" |
| 575 |
else: |
| 576 |
bits += "0" |
| 577 |
if fillStyle: |
| 578 |
bits += "1" |
| 579 |
else: |
| 580 |
bits += "0" |
| 581 |
bits += "0" |
| 582 |
if moveTo: |
| 583 |
bits += "1" |
| 584 |
else: |
| 585 |
bits += "0" |
| 586 |
|
| 587 |
|
| 588 |
|
| 589 |
|
| 590 |
if moveTo: |
| 591 |
bits += twits2bits([moveTo[0], moveTo[1]]) |
| 592 |
if fillStyle: |
| 593 |
bits += int2bits(fillStyle, 4) |
| 594 |
if lineStyle: |
| 595 |
bits += int2bits(lineStyle, 4) |
| 596 |
|
| 597 |
return bits |
| 598 |
|
| 599 |
def make_straight_edge_record(self, *dxdy): |
| 600 |
if len(dxdy) == 1: |
| 601 |
dxdy = dxdy[0] |
| 602 |
|
| 603 |
|
| 604 |
xbits = signedint2bits(dxdy[0] * 20) |
| 605 |
ybits = signedint2bits(dxdy[1] * 20) |
| 606 |
nbits = max([len(xbits), len(ybits)]) |
| 607 |
|
| 608 |
bits = BitArray() |
| 609 |
bits += "11" |
| 610 |
bits += int2bits(nbits - 2, 4) |
| 611 |
bits += "1" |
| 612 |
bits += signedint2bits(dxdy[0] * 20, nbits) |
| 613 |
bits += signedint2bits(dxdy[1] * 20, nbits) |
| 614 |
|
| 615 |
|
| 616 |
|
| 617 |
return bits |
| 618 |
|
| 619 |
def make_end_shape_record(self): |
| 620 |
bits = BitArray() |
| 621 |
bits += "0" |
| 622 |
bits += "0" * 5 |
| 623 |
return bits |
| 624 |
|
| 625 |
|
| 626 |
def read_pixels(bb, i, tagType, L1): |
| 627 |
"""With pf's seed after the recordheader, reads the pixeldata.""" |
| 628 |
|
| 629 |
|
| 630 |
charId = bb[i : i + 2] |
| 631 |
i += 2 |
| 632 |
format = ord(bb[i : i + 1]) |
| 633 |
i += 1 |
| 634 |
width = bits2int(bb[i : i + 2], 16) |
| 635 |
i += 2 |
| 636 |
height = bits2int(bb[i : i + 2], 16) |
| 637 |
i += 2 |
| 638 |
|
| 639 |
|
| 640 |
if format != 5: |
| 641 |
logger.warning("Can only read 24bit or 32bit RGB(A) lossless images.") |
| 642 |
else: |
| 643 |
|
| 644 |
offset = 2 + 1 + 2 + 2 |
| 645 |
bb2 = bb[i : i + (L1 - offset)] |
| 646 |
|
| 647 |
|
| 648 |
data = zlib.decompress(bb2) |
| 649 |
a = np.frombuffer(data, dtype=np.uint8) |
| 650 |
|
| 651 |
|
| 652 |
if tagType == 20: |
| 653 |
|
| 654 |
try: |
| 655 |
a = a.reshape(height, width, 3) |
| 656 |
except Exception: |
| 657 |
|
| 658 |
logger.warning("Cannot read image due to byte alignment") |
| 659 |
if tagType == 36: |
| 660 |
|
| 661 |
a = a.reshape(height, width, 4) |
| 662 |
|
| 663 |
b = a |
| 664 |
a = np.zeros_like(a) |
| 665 |
a[:, :, 0] = b[:, :, 1] |
| 666 |
a[:, :, 1] = b[:, :, 2] |
| 667 |
a[:, :, 2] = b[:, :, 3] |
| 668 |
a[:, :, 3] = b[:, :, 0] |
| 669 |
|
| 670 |
return a |
| 671 |
|
| 672 |
|
| 673 |
|
| 674 |
|
| 675 |
|
| 676 |
|
| 677 |
|
| 678 |
|
| 679 |
|
| 680 |
def checkImages(images): |
| 681 |
"""checkImages(images) |
| 682 |
Check numpy images and correct intensity range etc. |
| 683 |
The same for all movie formats. |
| 684 |
""" |
| 685 |
|
| 686 |
images2 = [] |
| 687 |
|
| 688 |
for im in images: |
| 689 |
if isinstance(im, np.ndarray): |
| 690 |
|
| 691 |
if im.dtype == np.uint8: |
| 692 |
images2.append(im) |
| 693 |
elif im.dtype in [np.float32, np.float64]: |
| 694 |
theMax = im.max() |
| 695 |
if 128 < theMax < 300: |
| 696 |
pass |
| 697 |
else: |
| 698 |
im = im.copy() |
| 699 |
im[im < 0] = 0 |
| 700 |
im[im > 1] = 1 |
| 701 |
im *= 255 |
| 702 |
images2.append(im.astype(np.uint8)) |
| 703 |
else: |
| 704 |
im = im.astype(np.uint8) |
| 705 |
images2.append(im) |
| 706 |
|
| 707 |
if im.ndim == 2: |
| 708 |
pass |
| 709 |
elif im.ndim == 3: |
| 710 |
if im.shape[2] not in [3, 4]: |
| 711 |
raise ValueError("This array can not represent an image.") |
| 712 |
else: |
| 713 |
raise ValueError("This array can not represent an image.") |
| 714 |
else: |
| 715 |
raise ValueError("Invalid image type: " + str(type(im))) |
| 716 |
|
| 717 |
|
| 718 |
return images2 |
| 719 |
|
| 720 |
|
| 721 |
def build_file( |
| 722 |
fp, taglist, nframes=1, framesize=(500, 500), fps=10, version=8 |
| 723 |
): |
| 724 |
"""Give the given file (as bytes) a header.""" |
| 725 |
|
| 726 |
|
| 727 |
bb = bytes() |
| 728 |
bb += "F".encode("ascii") |
| 729 |
bb += "WS".encode("ascii") |
| 730 |
bb += int2uint8(version) |
| 731 |
bb += "0000".encode("ascii") |
| 732 |
bb += Tag().make_rect_record(0, framesize[0], 0, framesize[1]).tobytes() |
| 733 |
bb += int2uint8(0) + int2uint8(fps) |
| 734 |
bb += int2uint16(nframes) |
| 735 |
fp.write(bb) |
| 736 |
|
| 737 |
|
| 738 |
for tag in taglist: |
| 739 |
fp.write(tag.get_tag()) |
| 740 |
|
| 741 |
|
| 742 |
fp.write("\x00\x00".encode("ascii")) |
| 743 |
|
| 744 |
|
| 745 |
sze = fp.tell() |
| 746 |
fp.seek(4) |
| 747 |
fp.write(int2uint32(sze)) |
| 748 |
|
| 749 |
|
| 750 |
def write_swf(filename, images, duration=0.1, repeat=True): |
| 751 |
"""Write an swf-file from the specified images. If repeat is False, |
| 752 |
the movie is finished with a stop action. Duration may also |
| 753 |
be a list with durations for each frame (note that the duration |
| 754 |
for each frame is always an integer amount of the minimum duration.) |
| 755 |
|
| 756 |
Images should be a list consisting numpy arrays with values between |
| 757 |
0 and 255 for integer types, and between 0 and 1 for float types. |
| 758 |
|
| 759 |
""" |
| 760 |
|
| 761 |
|
| 762 |
images2 = checkImages(images) |
| 763 |
|
| 764 |
|
| 765 |
taglist = [FileAttributesTag(), SetBackgroundTag(0, 0, 0)] |
| 766 |
|
| 767 |
|
| 768 |
if hasattr(duration, "__len__"): |
| 769 |
if len(duration) == len(images2): |
| 770 |
duration = [d for d in duration] |
| 771 |
else: |
| 772 |
raise ValueError("len(duration) doesn't match amount of images.") |
| 773 |
else: |
| 774 |
duration = [duration for im in images2] |
| 775 |
|
| 776 |
|
| 777 |
minDuration = float(min(duration)) |
| 778 |
delays = [round(d / minDuration) for d in duration] |
| 779 |
delays = [max(1, int(d)) for d in delays] |
| 780 |
|
| 781 |
|
| 782 |
fps = 1.0 / minDuration |
| 783 |
|
| 784 |
|
| 785 |
|
| 786 |
nframes = 0 |
| 787 |
for im in images2: |
| 788 |
bm = BitmapTag(im) |
| 789 |
wh = (im.shape[1], im.shape[0]) |
| 790 |
sh = ShapeTag(bm.id, (0, 0), wh) |
| 791 |
po = PlaceObjectTag(1, sh.id, move=nframes > 0) |
| 792 |
taglist.extend([bm, sh, po]) |
| 793 |
for i in range(delays[nframes]): |
| 794 |
taglist.append(ShowFrameTag()) |
| 795 |
nframes += 1 |
| 796 |
|
| 797 |
if not repeat: |
| 798 |
taglist.append(DoActionTag("stop")) |
| 799 |
|
| 800 |
|
| 801 |
|
| 802 |
fp = open(filename, "wb") |
| 803 |
try: |
| 804 |
build_file(fp, taglist, nframes=nframes, framesize=wh, fps=fps) |
| 805 |
except Exception: |
| 806 |
raise |
| 807 |
finally: |
| 808 |
fp.close() |
| 809 |
|
| 810 |
|
| 811 |
|
| 812 |
|
| 813 |
|
| 814 |
def read_swf(filename): |
| 815 |
"""Read all images from an SWF (shockwave flash) file. Returns a list |
| 816 |
of numpy arrays. |
| 817 |
|
| 818 |
Limitation: only read the PNG encoded images (not the JPG encoded ones). |
| 819 |
""" |
| 820 |
|
| 821 |
|
| 822 |
if not os.path.isfile(filename): |
| 823 |
raise IOError("File not found: " + str(filename)) |
| 824 |
|
| 825 |
|
| 826 |
images = [] |
| 827 |
|
| 828 |
|
| 829 |
fp = open(filename, "rb") |
| 830 |
bb = fp.read() |
| 831 |
|
| 832 |
try: |
| 833 |
|
| 834 |
tmp = bb[0:3].decode("ascii", "ignore") |
| 835 |
if tmp.upper() == "FWS": |
| 836 |
pass |
| 837 |
elif tmp.upper() == "CWS": |
| 838 |
|
| 839 |
bb = bb[:8] + zlib.decompress(bb[8:]) |
| 840 |
else: |
| 841 |
raise IOError("Not a valid SWF file: " + str(filename)) |
| 842 |
|
| 843 |
|
| 844 |
i = 8 |
| 845 |
nbits = bits2int(bb[i : i + 1], 5) |
| 846 |
nbits = 5 + nbits * 4 |
| 847 |
Lrect = nbits / 8.0 |
| 848 |
if Lrect % 1: |
| 849 |
Lrect += 1 |
| 850 |
Lrect = int(Lrect) |
| 851 |
i += Lrect + 4 |
| 852 |
|
| 853 |
|
| 854 |
counter = 0 |
| 855 |
while True: |
| 856 |
counter += 1 |
| 857 |
|
| 858 |
|
| 859 |
head = bb[i : i + 6] |
| 860 |
if not head: |
| 861 |
break |
| 862 |
|
| 863 |
|
| 864 |
T, L1, L2 = get_type_and_len(head) |
| 865 |
if not L2: |
| 866 |
logger.warning("Invalid tag length, could not proceed") |
| 867 |
break |
| 868 |
|
| 869 |
|
| 870 |
|
| 871 |
if T in [20, 36]: |
| 872 |
im = read_pixels(bb, i + 6, T, L1) |
| 873 |
if im is not None: |
| 874 |
images.append(im) |
| 875 |
elif T in [6, 21, 35, 90]: |
| 876 |
logger.warning("Ignoring JPEG image: cannot read JPEG.") |
| 877 |
else: |
| 878 |
pass |
| 879 |
|
| 880 |
|
| 881 |
if T == 0: |
| 882 |
break |
| 883 |
|
| 884 |
|
| 885 |
i += L2 |
| 886 |
|
| 887 |
finally: |
| 888 |
fp.close() |
| 889 |
|
| 890 |
|
| 891 |
return images |
| 892 |
|
| 893 |
|
| 894 |
|
| 895 |
writeSwf = write_swf |
| 896 |
readSwf = read_swf |