Debian Codegraph @

dask_image/ndmorph/_utils.py

raw
1 # -*- coding: utf-8 -*-
2
3
4 import numbers
5
6 import dask.array as da
7 import numpy as np
8
9 from ..dispatch._dispatch_ndmorph import dispatch_binary_structure
10 from ..ndfilters._utils import (_get_depth, _get_depth_boundary, _get_origin,
11 _update_wrapper)
12
13 _update_wrapper = _update_wrapper
14 _get_depth_boundary = _get_depth_boundary
15 _get_origin = _get_origin
16 _get_depth = _get_depth
17
18
19 def _get_structure(image, structure):
20 # Create square connectivity as default
21 if structure is None:
22 generate_binary_structure = dispatch_binary_structure(image)
23 structure = generate_binary_structure(image.ndim, 1)
24 elif hasattr(structure, 'ndim'):
25 if structure.ndim != image.ndim:
26 raise RuntimeError(
27 "`structure` must have the same rank as `image`."
28 )
29 if not issubclass(structure.dtype.type, np.bool_):
30 structure = (structure != 0)
31 else:
32 raise TypeError("`structure` must be an array.")
33
34 return structure
35
36
37 def _get_iterations(iterations):
38 if not isinstance(iterations, numbers.Integral):
39 raise TypeError("`iterations` must be of integral type.")
40 if iterations < 1:
41 raise NotImplementedError(
42 "`iterations` must be equal to 1 or greater not less."
43 )
44
45 return iterations
46
47
48 def _get_dtype(a):
49 # Get the dtype of a value or an array.
50 # Even handle non-NumPy types.
51 return getattr(a, "dtype", np.dtype(type(a)))
52
53
54 def _get_mask(image, mask):
55 if mask is None:
56 mask = True
57
58 mask_type = _get_dtype(mask).type
59 if isinstance(mask, (np.ndarray, da.Array)):
60 if mask.shape != image.shape:
61 raise RuntimeError("`mask` must have the same shape as `image`.")
62 if not issubclass(mask_type, np.bool_):
63 mask = (mask != 0)
64 elif issubclass(mask_type, np.bool_):
65 mask = bool(mask)
66 else:
67 raise TypeError("`mask` must be a Boolean or an array.")
68
69 return mask
70
71
72 def _get_border_value(border_value):
73 if not isinstance(border_value, numbers.Integral):
74 raise TypeError("`border_value` must be of integral type.")
75
76 border_value = (border_value != 0)
77
78 return border_value
79
80
81 def _get_brute_force(brute_force):
82 if brute_force is not False:
83 if brute_force is True:
84 raise NotImplementedError(
85 "`brute_force` other than `False` is not yet supported."
86 )
87 else:
88 raise TypeError(
89 "`brute_force` must be `bool`."
90 )
91
92 return brute_force