Debian Codegraph @

imgviz/nchannel.py

raw symbols SCIP
1 import numpy as np
2
3 from . import normalize
4
5
6 class Nchannel2RGB(object):
7 """Convert nchannel array to rgb by PCA.
8
9 Parameters
10 ----------
11 pca: sklearn.decomposition.PCA
12 PCA.
13
14 """
15
16 def __init__(self, pca=None):
17 self._pca = pca
18 # for uint8
19 self._min_max_value = (None, None)
20
21 @property
22 def pca(self):
23 """PCA for N channel to 3."""
24 return self._pca
25
26 def __call__(self, nchannel, dtype=np.uint8):
27 """Convert nchannel array to rgb by PCA.
28
29 Parameters
30 ----------
31 nchannel: numpy.ndarray, (H, W, C), float
32 N channel image.
33 dtype: numpy.dtype
34 Dtype (default: numpy.uint8).
35
36 Returns
37 -------
38 dst: numpy.ndarray, (H, W, 3), numpy.uint8
39 Visualized image.
40
41 """
42 import sklearn.decomposition
43
44 assert nchannel.ndim == 3, "nchannel.ndim must be 3"
45 assert np.issubdtype(
46 nchannel.dtype, np.floating
47 ), "nchannel.dtype must be floating"
48 H, W, D = nchannel.shape
49
50 dst = nchannel.reshape(-1, D)
51 if self._pca is None:
52 self._pca = sklearn.decomposition.PCA(n_components=3, random_state=1234)
53 dst = self._pca.fit_transform(dst)
54 else:
55 dst = self._pca.transform(dst)
56 dst = dst.reshape(H, W, 3)
57
58 if dtype == np.uint8:
59 if self._min_max_value is None:
60 self._min_max_value = (
61 np.nanmin(dst, axis=(0, 1)),
62 np.nanmax(dst, axis=(0, 1)),
63 )
64 min_value, max_value = self._min_max_value
65 dst = normalize.normalize(dst, min_value, max_value)
66 dst = (dst * 255).round().astype(np.uint8)
67 else:
68 assert np.issubdtype(dtype, np.floating)
69 dst = dst.astype(dtype)
70
71 return dst
72
73
74 def nchannel2rgb(nchannel, dtype=np.uint8, pca=None):
75 """Convert nchannel array to rgb by PCA.
76
77 Parameters
78 ----------
79 nchannel: numpy.ndarray, (H, W, C), float
80 N channel image.
81 dtype: numpy.dtype
82 Dtype (default: numpy.uint8).
83 pca: sklearn.decomposition.PCA
84 PCA.
85
86 Returns
87 -------
88 dst: numpy.ndarray, (H, W, 3), numpy.uint8
89 Visualized image.
90
91 """
92 return Nchannel2RGB(pca)(nchannel, dtype)