2626"""
2727from io import BytesIO
2828import itertools
29+ import logging
2930import struct
3031from typing import List
3132
3233import numpy as np
3334from PIL import Image
3435
35- _BACKGROUND_RGBA = np .array ([255 , 255 , 255 , 255 ])
36- _BACKGROUND_RGBA .flags .writeable = False
36+ BACKGROUND_RGBA = np .array ([255 , 255 , 255 , 255 ], dtype = np . uint8 )
37+ BACKGROUND_RGBA .flags .writeable = False
3738_HEADER_LENGTH = 6 * 4
3839
3940
@@ -53,7 +54,7 @@ def encode(image_in: Image, colormap: List[np.array]):
5354 pixel_words = np .array (image ).reshape (- 1 , 4 )
5455 pixel_words .flags .writeable = False
5556
56- colormap = [np . zeros ( 4 , dtype = np . uint8 ) ] + \
57+ colormap = [BACKGROUND_RGBA ] + \
5758 list (map (lambda color : np .append (color , 255 ).astype (np .uint8 ), colormap ))
5859
5960 input_byte_len = len (np .array (image ).flat )
@@ -70,7 +71,7 @@ def _color_to_key(color):
7071 struct .pack_into ('<BBBB' , buff .getbuffer (), offset , * color )
7172 color_dict [_color_to_key (color )] = i
7273 offset += 4
73- color_dict [_color_to_key (_BACKGROUND_RGBA )] = len (colormap )
74+ # color_dict[_color_to_key(BACKGROUND_RGBA )] = len(colormap)
7475
7576 count = 0
7677 pixel_ints = np .apply_along_axis (_color_to_key , 1 , pixel_words )
@@ -79,9 +80,13 @@ def _color_to_key(color):
7980 if i + 1 == len (pixel_ints ) \
8081 or not pixel_int == pixel_ints [i + 1 ] \
8182 or count > 65534 :
82- struct .pack_into ('<HH' , buff .getbuffer (), offset , color_dict [pixel_int ], count )
83- offset += 4
84- count = 0
83+ try :
84+ struct .pack_into ('<HH' , buff .getbuffer (), offset , color_dict [pixel_int ], count )
85+ offset += 4
86+ count = 0
87+ except KeyError as e :
88+ logging .error ('Could not find color {} in colormap' .format (pixel_words [i ]))
89+ raise e
8590
8691 # write header
8792 struct .pack_into (
@@ -110,7 +115,7 @@ def decode(lbx: BytesIO):
110115 map (lambda x : x [0 ],
111116 struct .iter_unpack ('<B' , lbx .read (4 * num_colors ))),
112117 4 )) +
113- [_BACKGROUND_RGBA ])
118+ [BACKGROUND_RGBA ])
114119
115120 image_data = np .zeros ((width * height , 4 ), dtype = 'uint8' )
116121 offset = 0
0 commit comments