File size: 6,750 Bytes
b62898a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | from itertools import combinations_with_replacement
import itertools
import numpy as np
from skimage import filters, feature
from skimage.util.dtype import img_as_float32
from .._shared._dependency_checks import is_wasm
if not is_wasm:
from concurrent.futures import ThreadPoolExecutor as PoolExecutor
else:
from contextlib import AbstractContextManager
# Threading isn't supported on WASM, mock ThreadPoolExecutor as a fallback
class PoolExecutor(AbstractContextManager):
def __init__(self, *_, **__):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def map(self, fn, iterables):
return map(fn, iterables)
def _texture_filter(gaussian_filtered):
H_elems = [
np.gradient(np.gradient(gaussian_filtered)[ax0], axis=ax1)
for ax0, ax1 in combinations_with_replacement(range(gaussian_filtered.ndim), 2)
]
eigvals = feature.hessian_matrix_eigvals(H_elems)
return eigvals
def _singlescale_basic_features_singlechannel(
img, sigma, intensity=True, edges=True, texture=True
):
results = ()
gaussian_filtered = filters.gaussian(img, sigma=sigma, preserve_range=False)
if intensity:
results += (gaussian_filtered,)
if edges:
results += (filters.sobel(gaussian_filtered),)
if texture:
results += (*_texture_filter(gaussian_filtered),)
return results
def _mutiscale_basic_features_singlechannel(
img,
intensity=True,
edges=True,
texture=True,
sigma_min=0.5,
sigma_max=16,
num_sigma=None,
workers=None,
):
"""Features for a single channel nd image.
Parameters
----------
img : ndarray
Input image, which can be grayscale or multichannel.
intensity : bool, default True
If True, pixel intensities averaged over the different scales
are added to the feature set.
edges : bool, default True
If True, intensities of local gradients averaged over the different
scales are added to the feature set.
texture : bool, default True
If True, eigenvalues of the Hessian matrix after Gaussian blurring
at different scales are added to the feature set.
sigma_min : float, optional
Smallest value of the Gaussian kernel used to average local
neighborhoods before extracting features.
sigma_max : float, optional
Largest value of the Gaussian kernel used to average local
neighborhoods before extracting features.
num_sigma : int, optional
Number of values of the Gaussian kernel between sigma_min and sigma_max.
If None, sigma_min multiplied by powers of 2 are used.
workers : int or None, optional
The number of parallel threads to use. If set to ``None``, the full
set of available cores are used.
Returns
-------
features : list
List of features, each element of the list is an array of shape as img.
"""
# computations are faster as float32
img = np.ascontiguousarray(img_as_float32(img))
if num_sigma is None:
num_sigma = int(np.log2(sigma_max) - np.log2(sigma_min) + 1)
sigmas = np.logspace(
np.log2(sigma_min),
np.log2(sigma_max),
num=num_sigma,
base=2,
endpoint=True,
)
with PoolExecutor(max_workers=workers) as ex:
out_sigmas = list(
ex.map(
lambda s: _singlescale_basic_features_singlechannel(
img, s, intensity=intensity, edges=edges, texture=texture
),
sigmas,
)
)
features = itertools.chain.from_iterable(out_sigmas)
return features
def multiscale_basic_features(
image,
intensity=True,
edges=True,
texture=True,
sigma_min=0.5,
sigma_max=16,
num_sigma=None,
workers=None,
*,
channel_axis=None,
):
"""Local features for a single- or multi-channel nd image.
Intensity, gradient intensity and local structure are computed at
different scales thanks to Gaussian blurring.
Parameters
----------
image : ndarray
Input image, which can be grayscale or multichannel.
intensity : bool, default True
If True, pixel intensities averaged over the different scales
are added to the feature set.
edges : bool, default True
If True, intensities of local gradients averaged over the different
scales are added to the feature set.
texture : bool, default True
If True, eigenvalues of the Hessian matrix after Gaussian blurring
at different scales are added to the feature set.
sigma_min : float, optional
Smallest value of the Gaussian kernel used to average local
neighborhoods before extracting features.
sigma_max : float, optional
Largest value of the Gaussian kernel used to average local
neighborhoods before extracting features.
num_sigma : int, optional
Number of values of the Gaussian kernel between sigma_min and sigma_max.
If None, sigma_min multiplied by powers of 2 are used.
workers : int or None, optional
The number of parallel threads to use. If set to ``None``, the full
set of available cores are used.
channel_axis : int or None, optional
If None, the image is assumed to be a grayscale (single channel) image.
Otherwise, this parameter indicates which axis of the array corresponds
to channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
features : np.ndarray
Array of shape ``image.shape + (n_features,)``. When `channel_axis` is
not None, all channels are concatenated along the features dimension.
(i.e. ``n_features == n_features_singlechannel * n_channels``)
"""
if not any([intensity, edges, texture]):
raise ValueError(
"At least one of `intensity`, `edges` or `textures`"
"must be True for features to be computed."
)
if channel_axis is None:
image = image[..., np.newaxis]
channel_axis = -1
elif channel_axis != -1:
image = np.moveaxis(image, channel_axis, -1)
all_results = (
_mutiscale_basic_features_singlechannel(
image[..., dim],
intensity=intensity,
edges=edges,
texture=texture,
sigma_min=sigma_min,
sigma_max=sigma_max,
num_sigma=num_sigma,
workers=workers,
)
for dim in range(image.shape[-1])
)
features = list(itertools.chain.from_iterable(all_results))
out = np.stack(features, axis=-1)
return out
|