Debian Codegraph @

imageio/core/util.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # imageio is distributed under the terms of the (new) BSD License.
3
4 """
5 Various utilities for imageio
6 """
7
8 from collections import OrderedDict
9 import numpy as np
10 import os
11 import re
12 import struct
13 import sys
14 import time
15 import logging
16
17 logger = logging.getLogger("imageio")
18
19 IS_PYPY = "__pypy__" in sys.builtin_module_names
20 THIS_DIR = os.path.abspath(os.path.dirname(__file__))
21
22
23 def urlopen(*args, **kwargs):
24 """Compatibility function for the urlopen function. Raises an
25 RuntimeError if urlopen could not be imported (which can occur in
26 frozen applications.
27 """
28 try:
29 from urllib.request import urlopen
30 except ImportError:
31 raise RuntimeError("Could not import urlopen.")
32 return urlopen(*args, **kwargs)
33
34
35 def _precision_warn(p1, p2, extra=""):
36 t = (
37 "Lossy conversion from {} to {}. {} Convert image to {} prior to "
38 "saving to suppress this warning."
39 )
40 logger.warning(t.format(p1, p2, extra, p2))
41
42
43 def image_as_uint(im, bitdepth=None):
44 """Convert the given image to uint (default: uint8)
45
46 If the dtype already matches the desired format, it is returned
47 as-is. If the image is float, and all values are between 0 and 1,
48 the values are multiplied by np.power(2.0, bitdepth). In all other
49 situations, the values are scaled such that the minimum value
50 becomes 0 and the maximum value becomes np.power(2.0, bitdepth)-1
51 (255 for 8-bit and 65535 for 16-bit).
52 """
53 if not bitdepth:
54 bitdepth = 8
55 if not isinstance(im, np.ndarray):
56 raise ValueError("Image must be a numpy array")
57 if bitdepth == 8:
58 out_type = np.uint8
59 elif bitdepth == 16:
60 out_type = np.uint16
61 else:
62 raise ValueError("Bitdepth must be either 8 or 16")
63 dtype_str1 = str(im.dtype)
64 dtype_str2 = out_type.__name__
65 if (im.dtype == np.uint8 and bitdepth == 8) or (
66 im.dtype == np.uint16 and bitdepth == 16
67 ):
68 # Already the correct format? Return as-is
69 return im
70 if dtype_str1.startswith("float") and np.nanmin(im) >= 0 and np.nanmax(im) <= 1:
71 _precision_warn(dtype_str1, dtype_str2, "Range [0, 1].")
72 im = im.astype(np.float64) * (np.power(2.0, bitdepth) - 1) + 0.499999999
73 elif im.dtype == np.uint16 and bitdepth == 8:
74 _precision_warn(dtype_str1, dtype_str2, "Losing 8 bits of resolution.")
75 im = np.right_shift(im, 8)
76 elif im.dtype == np.uint32:
77 _precision_warn(
78 dtype_str1,
79 dtype_str2,
80 "Losing {} bits of resolution.".format(32 - bitdepth),
81 )
82 im = np.right_shift(im, 32 - bitdepth)
83 elif im.dtype == np.uint64:
84 _precision_warn(
85 dtype_str1,
86 dtype_str2,
87 "Losing {} bits of resolution.".format(64 - bitdepth),
88 )
89 im = np.right_shift(im, 64 - bitdepth)
90 else:
91 mi = np.nanmin(im)
92 ma = np.nanmax(im)
93 if not np.isfinite(mi):
94 raise ValueError("Minimum image value is not finite")
95 if not np.isfinite(ma):
96 raise ValueError("Maximum image value is not finite")
97 if ma == mi:
98 return im.astype(out_type)
99 _precision_warn(dtype_str1, dtype_str2, "Range [{}, {}].".format(mi, ma))
100 # Now make float copy before we scale
101 im = im.astype("float64")
102 # Scale the values between 0 and 1 then multiply by the max value
103 im = (im - mi) / (ma - mi) * (np.power(2.0, bitdepth) - 1) + 0.499999999
104 assert np.nanmin(im) >= 0
105 assert np.nanmax(im) < np.power(2.0, bitdepth)
106 return im.astype(out_type)
107
108
109 class Array(np.ndarray):
110 """Array(array, meta=None)
111
112 A subclass of np.ndarray that has a meta attribute. Get the dictionary
113 that contains the meta data using ``im.meta``. Convert to a plain numpy
114 array using ``np.asarray(im)``.
115
116 """
117
118 def __new__(cls, array, meta=None):
119 # Check
120 if not isinstance(array, np.ndarray):
121 raise ValueError("Array expects a numpy array.")
122 if not (meta is None or isinstance(meta, dict)):
123 raise ValueError("Array expects meta data to be a dict.")
124 # Convert and return
125 meta = meta if meta is not None else getattr(array, "meta", {})
126 try:
127 ob = array.view(cls)
128 except AttributeError: # pragma: no cover
129 # Just return the original; no metadata on the array in Pypy!
130 return array
131 ob._copy_meta(meta)
132 return ob
133
134 def _copy_meta(self, meta):
135 """Make a 2-level deep copy of the meta dictionary."""
136 self._meta = Dict()
137 for key, val in meta.items():
138 if isinstance(val, dict):
139 val = Dict(val) # Copy this level
140 self._meta[key] = val
141
142 @property
143 def meta(self):
144 """The dict with the meta data of this image."""
145 return self._meta
146
147 def __array_finalize__(self, ob):
148 """So the meta info is maintained when doing calculations with
149 the array.
150 """
151 if isinstance(ob, Array):
152 self._copy_meta(ob.meta)
153 else:
154 self._copy_meta({})
155
156 def __array_wrap__(self, out, context=None, return_scalar=False):
157 """So that we return a native numpy array (or scalar) when a
158 reducting ufunc is applied (such as sum(), std(), etc.)
159 """
160 if return_scalar or not out.shape:
161 return out.dtype.type(out) # Scalar
162 elif out.shape != self.shape:
163 return out.view(type=np.ndarray)
164 elif not isinstance(out, Array):
165 return Array(out, self.meta)
166 else:
167 return out # Type Array
168
169
170 Image = Array # Alias for backwards compatibility
171
172
173 def asarray(a):
174 """Pypy-safe version of np.asarray. Pypy's np.asarray consumes a
175 *lot* of memory if the given array is an ndarray subclass. This
176 function does not.
177 """
178 if isinstance(a, np.ndarray):
179 if IS_PYPY: # pragma: no cover
180 a = a.copy() # pypy has issues with base views
181 plain = a.view(type=np.ndarray)
182 return plain
183 return np.asarray(a)
184
185
186 class Dict(OrderedDict):
187 """A dict in which the keys can be get and set as if they were
188 attributes. Very convenient in combination with autocompletion.
189
190 This Dict still behaves as much as possible as a normal dict, and
191 keys can be anything that are otherwise valid keys. However,
192 keys that are not valid identifiers or that are names of the dict
193 class (such as 'items' and 'copy') cannot be get/set as attributes.
194 """
195
196 __reserved_names__ = dir(OrderedDict()) # Also from OrderedDict
197 __pure_names__ = dir(dict())
198
199 def __getattribute__(self, key):
200 try:
201 return object.__getattribute__(self, key)
202 except AttributeError:
203 if key in self:
204 return self[key]
205 else:
206 raise
207
208 def __setattr__(self, key, val):
209 if key in Dict.__reserved_names__:
210 # Either let OrderedDict do its work, or disallow
211 if key not in Dict.__pure_names__:
212 return OrderedDict.__setattr__(self, key, val)
213 else:
214 raise AttributeError(
215 "Reserved name, this key can only "
216 + "be set via ``d[%r] = X``" % key
217 )
218 else:
219 # if isinstance(val, dict): val = Dict(val) -> no, makes a copy!
220 self[key] = val
221
222 def __dir__(self):
223 def isidentifier(x):
224 return bool(re.match(r"[a-z_]\w*$", x, re.I))
225
226 names = [k for k in self.keys() if (isinstance(k, str) and isidentifier(k))]
227 return Dict.__reserved_names__ + names
228
229
230 class BaseProgressIndicator(object):
231 """BaseProgressIndicator(name)
232
233 A progress indicator helps display the progress of a task to the
234 user. Progress can be pending, running, finished or failed.
235
236 Each task has:
237 * a name - a short description of what needs to be done.
238 * an action - the current action in performing the task (e.g. a subtask)
239 * progress - how far the task is completed
240 * max - max number of progress units. If 0, the progress is indefinite
241 * unit - the units in which the progress is counted
242 * status - 0: pending, 1: in progress, 2: finished, 3: failed
243
244 This class defines an abstract interface. Subclasses should implement
245 _start, _stop, _update_progress(progressText), _write(message).
246 """
247
248 def __init__(self, name):
249 self._name = name
250 self._action = ""
251 self._unit = ""
252 self._max = 0
253 self._status = 0
254 self._last_progress_update = 0
255
256 def start(self, action="", unit="", max=0):
257 """start(action='', unit='', max=0)
258
259 Start the progress. Optionally specify an action, a unit,
260 and a maximum progress value.
261 """
262 if self._status == 1:
263 self.finish()
264 self._action = action
265 self._unit = unit
266 self._max = max
267 #
268 self._progress = 0
269 self._status = 1
270 self._start()
271
272 def status(self):
273 """status()
274
275 Get the status of the progress - 0: pending, 1: in progress,
276 2: finished, 3: failed
277 """
278 return self._status
279
280 def set_progress(self, progress=0, force=False):
281 """set_progress(progress=0, force=False)
282
283 Set the current progress. To avoid unnecessary progress updates
284 this will only have a visual effect if the time since the last
285 update is > 0.1 seconds, or if force is True.
286 """
287 self._progress = progress
288 # Update or not?
289 if not (force or (time.time() - self._last_progress_update > 0.1)):
290 return
291 self._last_progress_update = time.time()
292 # Compose new string
293 unit = self._unit or ""
294 progressText = ""
295 if unit == "%":
296 progressText = "%2.1f%%" % progress
297 elif self._max > 0:
298 percent = 100 * float(progress) / self._max
299 progressText = "%i/%i %s (%2.1f%%)" % (progress, self._max, unit, percent)
300 elif progress > 0:
301 if isinstance(progress, float):
302 progressText = "%0.4g %s" % (progress, unit)
303 else:
304 progressText = "%i %s" % (progress, unit)
305 # Update
306 self._update_progress(progressText)
307
308 def increase_progress(self, extra_progress):
309 """increase_progress(extra_progress)
310
311 Increase the progress by a certain amount.
312 """
313 self.set_progress(self._progress + extra_progress)
314
315 def finish(self, message=None):
316 """finish(message=None)
317
318 Finish the progress, optionally specifying a message. This will
319 not set the progress to the maximum.
320 """
321 self.set_progress(self._progress, True) # fore update
322 self._status = 2
323 self._stop()
324 if message is not None:
325 self._write(message)
326
327 def fail(self, message=None):
328 """fail(message=None)
329
330 Stop the progress with a failure, optionally specifying a message.
331 """
332 self.set_progress(self._progress, True) # fore update
333 self._status = 3
334 self._stop()
335 message = "FAIL " + (message or "")
336 self._write(message)
337
338 def write(self, message):
339 """write(message)
340
341 Write a message during progress (such as a warning).
342 """
343 if self.__class__ == BaseProgressIndicator:
344 # When this class is used as a dummy, print explicit message
345 print(message)
346 else:
347 return self._write(message)
348
349 # Implementing classes should implement these
350
351 def _start(self):
352 pass
353
354 def _stop(self):
355 pass
356
357 def _update_progress(self, progressText):
358 pass
359
360 def _write(self, message):
361 pass
362
363
364 class StdoutProgressIndicator(BaseProgressIndicator):
365 """StdoutProgressIndicator(name)
366
367 A progress indicator that shows the progress in stdout. It
368 assumes that the tty can appropriately deal with backspace
369 characters.
370 """
371
372 def _start(self):
373 self._chars_prefix, self._chars = "", ""
374 # Write message
375 if self._action:
376 self._chars_prefix = "%s (%s): " % (self._name, self._action)
377 else:
378 self._chars_prefix = "%s: " % self._name
379 sys.stdout.write(self._chars_prefix)
380 sys.stdout.flush()
381
382 def _update_progress(self, progressText):
383 # If progress is unknown, at least make something move
384 if not progressText:
385 i1, i2, i3, i4 = "-\\|/"
386 M = {i1: i2, i2: i3, i3: i4, i4: i1}
387 progressText = M.get(self._chars, i1)
388 # Store new string and write
389 delChars = "\b" * len(self._chars)
390 self._chars = progressText
391 sys.stdout.write(delChars + self._chars)
392 sys.stdout.flush()
393
394 def _stop(self):
395 self._chars = self._chars_prefix = ""
396 sys.stdout.write("\n")
397 sys.stdout.flush()
398
399 def _write(self, message):
400 # Write message
401 delChars = "\b" * len(self._chars_prefix + self._chars)
402 sys.stdout.write(delChars + " " + message + "\n")
403 # Reprint progress text
404 sys.stdout.write(self._chars_prefix + self._chars)
405 sys.stdout.flush()
406
407
408 # From pyzolib/paths.py (https://bitbucket.org/pyzo/pyzolib/src/tip/paths.py)
409 def appdata_dir(appname=None, roaming=False):
410 """appdata_dir(appname=None, roaming=False)
411
412 Get the path to the application directory, where applications are allowed
413 to write user specific files (e.g. configurations). For non-user specific
414 data, consider using common_appdata_dir().
415 If appname is given, a subdir is appended (and created if necessary).
416 If roaming is True, will prefer a roaming directory (Windows Vista/7).
417 """
418
419 # Define default user directory
420 userDir = os.getenv("IMAGEIO_USERDIR", None)
421 if userDir is None:
422 userDir = os.path.expanduser("~")
423 if not os.path.isdir(userDir): # pragma: no cover
424 userDir = "/var/tmp" # issue #54
425
426 # Get system app data dir
427 path = None
428 if sys.platform.startswith("win"):
429 path1, path2 = os.getenv("LOCALAPPDATA"), os.getenv("APPDATA")
430 path = (path2 or path1) if roaming else (path1 or path2)
431 elif sys.platform.startswith("darwin"):
432 path = os.path.join(userDir, "Library", "Application Support")
433 # On Linux and as fallback
434 if not (path and os.path.isdir(path)):
435 path = userDir
436
437 # Maybe we should store things local to the executable (in case of a
438 # portable distro or a frozen application that wants to be portable)
439 prefix = sys.prefix
440 if getattr(sys, "frozen", None):
441 prefix = os.path.abspath(os.path.dirname(sys.executable))
442 for reldir in ("settings", "../settings"):
443 localpath = os.path.abspath(os.path.join(prefix, reldir))
444 if os.path.isdir(localpath): # pragma: no cover
445 try:
446 open(os.path.join(localpath, "test.write"), "wb").close()
447 os.remove(os.path.join(localpath, "test.write"))
448 except IOError:
449 pass # We cannot write in this directory
450 else:
451 path = localpath
452 break
453
454 # Get path specific for this app
455 if appname:
456 if path == userDir:
457 appname = "." + appname.lstrip(".") # Make it a hidden directory
458 path = os.path.join(path, appname)
459 if not os.path.isdir(path): # pragma: no cover
460 os.makedirs(path, exist_ok=True)
461
462 # Done
463 return path
464
465
466 def resource_dirs():
467 """resource_dirs()
468
469 Get a list of directories where imageio resources may be located.
470 The first directory in this list is the "resources" directory in
471 the package itself. The second directory is the appdata directory
472 (~/.imageio on Linux). The list further contains the application
473 directory (for frozen apps), and may include additional directories
474 in the future.
475 """
476 dirs = [resource_package_dir()]
477 # Resource dir baked in the package.
478 # Appdata directory
479 try:
480 dirs.append(appdata_dir("imageio"))
481 except Exception: # pragma: no cover
482 pass # The home dir may not be writable
483 # Directory where the app is located (mainly for frozen apps)
484 if getattr(sys, "frozen", None):
485 dirs.append(os.path.abspath(os.path.dirname(sys.executable)))
486 elif sys.path and sys.path[0]:
487 dirs.append(os.path.abspath(sys.path[0]))
488 return dirs
489
490
491 def resource_package_dir():
492 """package_dir
493
494 Get the resources directory in the imageio package installation
495 directory.
496
497 Notes
498 -----
499 This is a convenience method that is used by `resource_dirs` and
500 imageio entry point scripts.
501 """
502 import importlib.resources
503
504 return str(importlib.resources.files("imageio") / "resources")
505
506
507 def get_platform():
508 """get_platform()
509
510 Get a string that specifies the platform more specific than
511 sys.platform does. The result can be: linux32, linux64, win32,
512 win64, osx32, osx64. Other platforms may be added in the future.
513 """
514 # Get platform
515 if sys.platform.startswith("linux"):
516 plat = "linux%i"
517 elif sys.platform.startswith("win"):
518 plat = "win%i"
519 elif sys.platform.startswith("darwin"):
520 plat = "osx%i"
521 elif sys.platform.startswith("freebsd"):
522 plat = "freebsd%i"
523 else: # pragma: no cover
524 return None
525
526 return plat % (struct.calcsize("P") * 8) # 32 or 64 bits
527
528
529 def has_module(module_name):
530 """Check to see if a python module is available."""
531 import importlib
532
533 name_parts = module_name.split(".")
534 for i in range(len(name_parts)):
535 if importlib.util.find_spec(".".join(name_parts[: i + 1])) is None:
536 return False
537 return True