| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
"""Plugin for multi-image freeimafe formats, like animated GIF and ico.""" |
| 5 |
|
| 6 |
import logging |
| 7 |
import numpy as np |
| 8 |
|
| 9 |
from ..core import Format, image_as_uint |
| 10 |
from ._freeimage import fi, IO_FLAGS |
| 11 |
from .freeimage import FreeimageFormat |
| 12 |
|
| 13 |
logger = logging.getLogger(__name__) |
| 14 |
|
| 15 |
|
| 16 |
class FreeimageMulti(FreeimageFormat): |
| 17 |
"""Base class for freeimage formats that support multiple images.""" |
| 18 |
|
| 19 |
_modes = "iI" |
| 20 |
_fif = -1 |
| 21 |
|
| 22 |
class Reader(Format.Reader): |
| 23 |
def _open(self, flags=0): |
| 24 |
flags = int(flags) |
| 25 |
|
| 26 |
self._bm = fi.create_multipage_bitmap( |
| 27 |
self.request.filename, self.format.fif, flags |
| 28 |
) |
| 29 |
self._bm.load_from_filename(self.request.get_local_filename()) |
| 30 |
|
| 31 |
def _close(self): |
| 32 |
self._bm.close() |
| 33 |
|
| 34 |
def _get_length(self): |
| 35 |
return len(self._bm) |
| 36 |
|
| 37 |
def _get_data(self, index): |
| 38 |
sub = self._bm.get_page(index) |
| 39 |
try: |
| 40 |
return sub.get_image_data(), sub.get_meta_data() |
| 41 |
finally: |
| 42 |
sub.close() |
| 43 |
|
| 44 |
def _get_meta_data(self, index): |
| 45 |
index = index or 0 |
| 46 |
if index < 0 or index >= len(self._bm): |
| 47 |
raise IndexError() |
| 48 |
sub = self._bm.get_page(index) |
| 49 |
try: |
| 50 |
return sub.get_meta_data() |
| 51 |
finally: |
| 52 |
sub.close() |
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
class Writer(FreeimageFormat.Writer): |
| 57 |
def _open(self, flags=0): |
| 58 |
|
| 59 |
self._flags = flags = int(flags) |
| 60 |
|
| 61 |
self._bm = fi.create_multipage_bitmap( |
| 62 |
self.request.filename, self.format.fif, flags |
| 63 |
) |
| 64 |
self._bm.save_to_filename(self.request.get_local_filename()) |
| 65 |
|
| 66 |
def _close(self): |
| 67 |
|
| 68 |
self._bm.close() |
| 69 |
|
| 70 |
def _append_data(self, im, meta): |
| 71 |
|
| 72 |
if im.ndim == 3 and im.shape[-1] == 1: |
| 73 |
im = im[:, :, 0] |
| 74 |
im = image_as_uint(im, bitdepth=8) |
| 75 |
|
| 76 |
sub1 = fi.create_bitmap(self._bm._filename, self.format.fif) |
| 77 |
|
| 78 |
sub2 = self._append_bitmap(im, meta, sub1) |
| 79 |
|
| 80 |
self._bm.append_bitmap(sub2) |
| 81 |
sub2.close() |
| 82 |
if sub1 is not sub2: |
| 83 |
sub1.close() |
| 84 |
|
| 85 |
def _append_bitmap(self, im, meta, bitmap): |
| 86 |
|
| 87 |
bitmap.allocate(im) |
| 88 |
bitmap.set_image_data(im) |
| 89 |
bitmap.set_meta_data(meta) |
| 90 |
|
| 91 |
return bitmap |
| 92 |
|
| 93 |
def _set_meta_data(self, meta): |
| 94 |
pass |
| 95 |
|
| 96 |
|
| 97 |
class MngFormat(FreeimageMulti): |
| 98 |
"""An Mng format based on the Freeimage library. |
| 99 |
|
| 100 |
Read only. Seems broken. |
| 101 |
""" |
| 102 |
|
| 103 |
_fif = 6 |
| 104 |
|
| 105 |
def _can_write(self, request): |
| 106 |
return False |
| 107 |
|
| 108 |
|
| 109 |
class IcoFormat(FreeimageMulti): |
| 110 |
"""An ICO format based on the Freeimage library. |
| 111 |
|
| 112 |
This format supports grayscale, RGB and RGBA images. |
| 113 |
|
| 114 |
The freeimage plugin requires a `freeimage` binary. If this binary |
| 115 |
is not available on the system, it can be downloaded by either |
| 116 |
|
| 117 |
- the command line script ``imageio_download_bin freeimage`` |
| 118 |
- the Python method ``imageio.plugins.freeimage.download()`` |
| 119 |
|
| 120 |
Parameters for reading |
| 121 |
---------------------- |
| 122 |
makealpha : bool |
| 123 |
Convert to 32-bit and create an alpha channel from the AND- |
| 124 |
mask when loading. Default False. Note that this returns wrong |
| 125 |
results if the image was already RGBA. |
| 126 |
|
| 127 |
""" |
| 128 |
|
| 129 |
_fif = 1 |
| 130 |
|
| 131 |
class Reader(FreeimageMulti.Reader): |
| 132 |
def _open(self, flags=0, makealpha=False): |
| 133 |
|
| 134 |
flags = int(flags) |
| 135 |
if makealpha: |
| 136 |
flags |= IO_FLAGS.ICO_MAKEALPHA |
| 137 |
return FreeimageMulti.Reader._open(self, flags) |
| 138 |
|
| 139 |
|
| 140 |
class GifFormat(FreeimageMulti): |
| 141 |
"""A format for reading and writing static and animated GIF, based |
| 142 |
on the Freeimage library. |
| 143 |
|
| 144 |
Images read with this format are always RGBA. Currently, |
| 145 |
the alpha channel is ignored when saving RGB images with this |
| 146 |
format. |
| 147 |
|
| 148 |
The freeimage plugin requires a `freeimage` binary. If this binary |
| 149 |
is not available on the system, it can be downloaded by either |
| 150 |
|
| 151 |
- the command line script ``imageio_download_bin freeimage`` |
| 152 |
- the Python method ``imageio.plugins.freeimage.download()`` |
| 153 |
|
| 154 |
Parameters for reading |
| 155 |
---------------------- |
| 156 |
playback : bool |
| 157 |
'Play' the GIF to generate each frame (as 32bpp) instead of |
| 158 |
returning raw frame data when loading. Default True. |
| 159 |
|
| 160 |
Parameters for saving |
| 161 |
--------------------- |
| 162 |
loop : int |
| 163 |
The number of iterations. Default 0 (meaning loop indefinitely) |
| 164 |
duration : {float, list} |
| 165 |
The duration (in seconds) of each frame. Either specify one value |
| 166 |
that is used for all frames, or one value for each frame. |
| 167 |
Note that in the GIF format the duration/delay is expressed in |
| 168 |
hundredths of a second, which limits the precision of the duration. |
| 169 |
fps : float |
| 170 |
The number of frames per second. If duration is not given, the |
| 171 |
duration for each frame is set to 1/fps. Default 10. |
| 172 |
palettesize : int |
| 173 |
The number of colors to quantize the image to. Is rounded to |
| 174 |
the nearest power of two. Default 256. |
| 175 |
quantizer : {'wu', 'nq'} |
| 176 |
The quantization algorithm: |
| 177 |
* wu - Wu, Xiaolin, Efficient Statistical Computations for |
| 178 |
Optimal Color Quantization |
| 179 |
* nq (neuqant) - Dekker A. H., Kohonen neural networks for |
| 180 |
optimal color quantization |
| 181 |
subrectangles : bool |
| 182 |
If True, will try and optimize the GIF by storing only the |
| 183 |
rectangular parts of each frame that change with respect to the |
| 184 |
previous. Unfortunately, this option seems currently broken |
| 185 |
because FreeImage does not handle DisposalMethod correctly. |
| 186 |
Default False. |
| 187 |
""" |
| 188 |
|
| 189 |
_fif = 25 |
| 190 |
|
| 191 |
class Reader(FreeimageMulti.Reader): |
| 192 |
def _open(self, flags=0, playback=True): |
| 193 |
|
| 194 |
flags = int(flags) |
| 195 |
if playback: |
| 196 |
flags |= IO_FLAGS.GIF_PLAYBACK |
| 197 |
FreeimageMulti.Reader._open(self, flags) |
| 198 |
|
| 199 |
def _get_data(self, index): |
| 200 |
im, meta = FreeimageMulti.Reader._get_data(self, index) |
| 201 |
|
| 202 |
return im, meta |
| 203 |
|
| 204 |
|
| 205 |
|
| 206 |
class Writer(FreeimageMulti.Writer): |
| 207 |
|
| 208 |
|
| 209 |
|
| 210 |
def _open( |
| 211 |
self, |
| 212 |
flags=0, |
| 213 |
loop=0, |
| 214 |
duration=None, |
| 215 |
fps=10, |
| 216 |
palettesize=256, |
| 217 |
quantizer="Wu", |
| 218 |
subrectangles=False, |
| 219 |
): |
| 220 |
|
| 221 |
if palettesize < 2 or palettesize > 256: |
| 222 |
raise ValueError("GIF quantize param must be 2..256") |
| 223 |
if palettesize not in [2, 4, 8, 16, 32, 64, 128, 256]: |
| 224 |
palettesize = 2 ** int(np.log2(128) + 0.999) |
| 225 |
logger.warning( |
| 226 |
"Warning: palettesize (%r) modified to a factor of " |
| 227 |
"two between 2-256." % palettesize |
| 228 |
) |
| 229 |
self._palettesize = palettesize |
| 230 |
|
| 231 |
self._quantizer = {"wu": 0, "nq": 1}.get(quantizer.lower(), None) |
| 232 |
if self._quantizer is None: |
| 233 |
raise ValueError('Invalid quantizer, must be "wu" or "nq".') |
| 234 |
|
| 235 |
if duration is None: |
| 236 |
self._frametime = [int(1000 / float(fps) + 0.5)] |
| 237 |
elif isinstance(duration, list): |
| 238 |
self._frametime = [int(1000 * d) for d in duration] |
| 239 |
elif isinstance(duration, (float, int)): |
| 240 |
self._frametime = [int(1000 * duration)] |
| 241 |
else: |
| 242 |
raise ValueError("Invalid value for duration: %r" % duration) |
| 243 |
|
| 244 |
self._subrectangles = bool(subrectangles) |
| 245 |
self._prev_im = None |
| 246 |
|
| 247 |
FreeimageMulti.Writer._open(self, flags) |
| 248 |
|
| 249 |
self._meta = {} |
| 250 |
self._meta["ANIMATION"] = { |
| 251 |
|
| 252 |
"Loop": np.array([loop]).astype(np.uint32), |
| 253 |
|
| 254 |
|
| 255 |
} |
| 256 |
|
| 257 |
def _append_bitmap(self, im, meta, bitmap): |
| 258 |
|
| 259 |
meta = meta.copy() |
| 260 |
meta_a = meta["ANIMATION"] = {} |
| 261 |
|
| 262 |
if len(self._bm) == 0: |
| 263 |
meta.update(self._meta) |
| 264 |
meta_a = meta["ANIMATION"] |
| 265 |
|
| 266 |
index = len(self._bm) |
| 267 |
if index < len(self._frametime): |
| 268 |
ft = self._frametime[index] |
| 269 |
else: |
| 270 |
ft = self._frametime[-1] |
| 271 |
meta_a["FrameTime"] = np.array([ft]).astype(np.uint32) |
| 272 |
|
| 273 |
if im.ndim == 3 and im.shape[-1] == 4: |
| 274 |
im = im[:, :, :3] |
| 275 |
|
| 276 |
im_uncropped = im |
| 277 |
if self._subrectangles and self._prev_im is not None: |
| 278 |
im, xy = self._get_sub_rectangles(self._prev_im, im) |
| 279 |
meta_a["DisposalMethod"] = np.array([1]).astype(np.uint8) |
| 280 |
meta_a["FrameLeft"] = np.array([xy[0]]).astype(np.uint16) |
| 281 |
meta_a["FrameTop"] = np.array([xy[1]]).astype(np.uint16) |
| 282 |
self._prev_im = im_uncropped |
| 283 |
|
| 284 |
sub2 = sub1 = bitmap |
| 285 |
sub1.allocate(im) |
| 286 |
sub1.set_image_data(im) |
| 287 |
|
| 288 |
if im.ndim == 3 and im.shape[-1] == 3: |
| 289 |
sub2 = sub1.quantize(self._quantizer, self._palettesize) |
| 290 |
|
| 291 |
sub2.set_meta_data(meta) |
| 292 |
return sub2 |
| 293 |
|
| 294 |
def _get_sub_rectangles(self, prev, im): |
| 295 |
""" |
| 296 |
Calculate the minimal rectangles that need updating each frame. |
| 297 |
Returns a two-element tuple containing the cropped images and a |
| 298 |
list of x-y positions. |
| 299 |
""" |
| 300 |
|
| 301 |
diff = np.abs(im - prev) |
| 302 |
if diff.ndim == 3: |
| 303 |
diff = diff.sum(2) |
| 304 |
|
| 305 |
X = np.argwhere(diff.sum(0)) |
| 306 |
Y = np.argwhere(diff.sum(1)) |
| 307 |
|
| 308 |
if X.size and Y.size: |
| 309 |
x0, x1 = X[0].item(), X[-1].item() + 1 |
| 310 |
y0, y1 = Y[0].item(), Y[-1].item() + 1 |
| 311 |
else: |
| 312 |
x0, x1 = 0, 2 |
| 313 |
y0, y1 = 0, 2 |
| 314 |
|
| 315 |
return im[y0:y1, x0:x1], (x0, y0) |