-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathmorphology.py
More file actions
673 lines (550 loc) · 20 KB
/
morphology.py
File metadata and controls
673 lines (550 loc) · 20 KB
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
"""Morphological raster operators.
Applies grayscale morphological operations using a structuring element
(kernel) over a 2D raster. Erosion computes the local minimum and
dilation the local maximum within the kernel footprint. Opening
(erosion then dilation) removes small bright features; closing
(dilation then erosion) fills small dark gaps. Gradient, white
top-hat, and black top-hat are derived by subtracting pairs of the
above.
Supports all four backends: numpy, cupy, dask+numpy, dask+cupy.
"""
from __future__ import annotations
from functools import partial
import numpy as np
import xarray as xr
from xarray import DataArray
from numba import cuda, prange
try:
import cupy
except ImportError:
class cupy:
ndarray = False
try:
import dask.array as da
except ImportError:
da = None
from xrspatial.utils import (
ArrayTypeFunctionMapping,
_boundary_to_dask,
_pad_array,
_validate_boundary,
_validate_raster,
calc_cuda_dims,
has_cuda_and_cupy,
ngjit,
not_implemented_func,
)
from xrspatial.dataset_support import supports_dataset
# ---------------------------------------------------------------------------
# Kernel construction
# ---------------------------------------------------------------------------
def _circle_kernel(radius):
"""Return a boolean 2D array for a circular structuring element.
The kernel has shape ``(2*radius+1, 2*radius+1)`` with ``True``
for cells whose centre is within *radius* cells of the centre.
"""
size = 2 * radius + 1
y, x = np.ogrid[-radius:radius + 1, -radius:radius + 1]
return (x * x + y * y <= radius * radius).astype(np.uint8)
def _validate_kernel(kernel, func_name):
"""Ensure *kernel* is a 2D uint8 numpy array with odd dimensions."""
if not isinstance(kernel, np.ndarray):
raise TypeError(
f"{func_name}(): `kernel` must be a numpy ndarray, "
f"got {type(kernel).__name__}"
)
if kernel.ndim != 2:
raise ValueError(
f"{func_name}(): `kernel` must be 2D, got {kernel.ndim}D"
)
if kernel.shape[0] % 2 == 0 or kernel.shape[1] % 2 == 0:
raise ValueError(
f"{func_name}(): `kernel` dimensions must be odd, "
f"got {kernel.shape}"
)
return kernel.astype(np.uint8)
# ---------------------------------------------------------------------------
# numpy backend
# ---------------------------------------------------------------------------
@ngjit
def _erode_kernel_numpy(data, kernel, rows, cols, ky, kx):
"""Erosion (local minimum) on a padded array."""
out = np.empty((rows, cols), dtype=data.dtype)
hy = ky // 2
hx = kx // 2
for i in prange(rows):
for j in range(cols):
val = data[i + hy, j + hx]
if val != val: # NaN
out[i, j] = val
continue
mn = val
for dy in range(ky):
for dx in range(kx):
if kernel[dy, dx] == 0:
continue
v = data[i + dy, j + dx]
if v != v: # NaN neighbour
mn = v
break
if v < mn:
mn = v
if mn != mn: # propagate NaN
break
out[i, j] = mn
return out
@ngjit
def _dilate_kernel_numpy(data, kernel, rows, cols, ky, kx):
"""Dilation (local maximum) on a padded array."""
out = np.empty((rows, cols), dtype=data.dtype)
hy = ky // 2
hx = kx // 2
for i in prange(rows):
for j in range(cols):
val = data[i + hy, j + hx]
if val != val: # NaN
out[i, j] = val
continue
mx = val
for dy in range(ky):
for dx in range(kx):
if kernel[dy, dx] == 0:
continue
v = data[i + dy, j + dx]
if v != v: # NaN neighbour
mx = v
break
if v > mx:
mx = v
if mx != mx:
break
out[i, j] = mx
return out
def _morph_numpy(data, kernel, op, boundary):
"""Run erosion or dilation on a numpy array."""
ky, kx = kernel.shape
hy, hx = ky // 2, kx // 2
rows, cols = data.shape
arr = data.astype(np.float64)
if boundary == 'nan':
padded = np.pad(arr, ((hy, hy), (hx, hx)),
mode='constant', constant_values=np.nan)
else:
padded = _pad_array(arr, (hy, hx), boundary)
if op == 'erode':
return _erode_kernel_numpy(padded, kernel, rows, cols, ky, kx)
else:
return _dilate_kernel_numpy(padded, kernel, rows, cols, ky, kx)
def _erode_numpy(data, kernel, boundary):
return _morph_numpy(data, kernel, 'erode', boundary)
def _dilate_numpy(data, kernel, boundary):
return _morph_numpy(data, kernel, 'dilate', boundary)
def _opening_numpy(data, kernel, boundary):
tmp = _morph_numpy(data, kernel, 'erode', boundary)
return _morph_numpy(tmp, kernel, 'dilate', boundary)
def _closing_numpy(data, kernel, boundary):
tmp = _morph_numpy(data, kernel, 'dilate', boundary)
return _morph_numpy(tmp, kernel, 'erode', boundary)
# ---------------------------------------------------------------------------
# cupy backend
# ---------------------------------------------------------------------------
@cuda.jit
def _erode_gpu(data, kernel, out, hy, hx, ky, kx):
i, j = cuda.grid(2)
rows = out.shape[0]
cols = out.shape[1]
if i < rows and j < cols:
val = data[i + hy, j + hx]
if val != val:
out[i, j] = val
return
mn = val
for dy in range(ky):
for dx in range(kx):
if kernel[dy, dx] == 0:
continue
v = data[i + dy, j + dx]
if v != v:
mn = v
break
if v < mn:
mn = v
if mn != mn:
break
out[i, j] = mn
@cuda.jit
def _dilate_gpu(data, kernel, out, hy, hx, ky, kx):
i, j = cuda.grid(2)
rows = out.shape[0]
cols = out.shape[1]
if i < rows and j < cols:
val = data[i + hy, j + hx]
if val != val:
out[i, j] = val
return
mx = val
for dy in range(ky):
for dx in range(kx):
if kernel[dy, dx] == 0:
continue
v = data[i + dy, j + dx]
if v != v:
mx = v
break
if v > mx:
mx = v
if mx != mx:
break
out[i, j] = mx
def _morph_cupy(data, kernel, op, boundary):
import cupy as cp
ky, kx = kernel.shape
hy, hx = ky // 2, kx // 2
rows, cols = data.shape
arr = cp.asarray(data, dtype=cp.float64)
kern_dev = cp.asarray(kernel)
if boundary == 'nan':
padded = cp.pad(arr, ((hy, hy), (hx, hx)),
mode='constant', constant_values=cp.nan)
else:
padded = _pad_array(arr, (hy, hx), boundary)
out = cp.empty((rows, cols), dtype=cp.float64)
bpg, tpb = calc_cuda_dims((rows, cols))
if op == 'erode':
_erode_gpu[bpg, tpb](padded, kern_dev, out, hy, hx, ky, kx)
else:
_dilate_gpu[bpg, tpb](padded, kern_dev, out, hy, hx, ky, kx)
return out
def _erode_cupy(data, kernel, boundary):
return _morph_cupy(data, kernel, 'erode', boundary)
def _dilate_cupy(data, kernel, boundary):
return _morph_cupy(data, kernel, 'dilate', boundary)
def _opening_cupy(data, kernel, boundary):
tmp = _morph_cupy(data, kernel, 'erode', boundary)
return _morph_cupy(tmp, kernel, 'dilate', boundary)
def _closing_cupy(data, kernel, boundary):
tmp = _morph_cupy(data, kernel, 'dilate', boundary)
return _morph_cupy(tmp, kernel, 'erode', boundary)
# ---------------------------------------------------------------------------
# dask + numpy backend
# ---------------------------------------------------------------------------
def _morph_chunk_numpy(chunk, kernel, op, block_info=None):
"""Process a single overlapped dask chunk."""
ky, kx = kernel.shape
hy, hx = ky // 2, kx // 2
rows = chunk.shape[0] - 2 * hy
cols = chunk.shape[1] - 2 * hx
if op == 'erode':
interior = _erode_kernel_numpy(chunk, kernel, rows, cols, ky, kx)
else:
interior = _dilate_kernel_numpy(chunk, kernel, rows, cols, ky, kx)
result = chunk.copy()
result[hy:-hy, hx:-hx] = interior
return result
def _morph_dask_numpy(data, kernel, op, boundary):
ky, kx = kernel.shape
hy, hx = ky // 2, kx // 2
_func = partial(_morph_chunk_numpy, kernel=kernel, op=op)
return data.astype(np.float64).map_overlap(
_func,
depth=(hy, hx),
boundary=_boundary_to_dask(boundary),
meta=np.array(()),
)
def _erode_dask_numpy(data, kernel, boundary):
return _morph_dask_numpy(data, kernel, 'erode', boundary)
def _dilate_dask_numpy(data, kernel, boundary):
return _morph_dask_numpy(data, kernel, 'dilate', boundary)
def _opening_dask_numpy(data, kernel, boundary):
tmp = _morph_dask_numpy(data, kernel, 'erode', boundary)
return _morph_dask_numpy(tmp, kernel, 'dilate', boundary)
def _closing_dask_numpy(data, kernel, boundary):
tmp = _morph_dask_numpy(data, kernel, 'dilate', boundary)
return _morph_dask_numpy(tmp, kernel, 'erode', boundary)
# ---------------------------------------------------------------------------
# dask + cupy backend
# ---------------------------------------------------------------------------
def _morph_chunk_cupy(chunk, kernel, op, block_info=None):
"""Process a single overlapped dask+cupy chunk."""
import cupy as cp
ky, kx = kernel.shape
hy, hx = ky // 2, kx // 2
rows = chunk.shape[0] - 2 * hy
cols = chunk.shape[1] - 2 * hx
kern_dev = cp.asarray(kernel)
out = cp.empty((rows, cols), dtype=cp.float64)
bpg, tpb = calc_cuda_dims((rows, cols))
if op == 'erode':
_erode_gpu[bpg, tpb](chunk, kern_dev, out, hy, hx, ky, kx)
else:
_dilate_gpu[bpg, tpb](chunk, kern_dev, out, hy, hx, ky, kx)
result = chunk.copy()
result[hy:-hy, hx:-hx] = out
return result
def _morph_dask_cupy(data, kernel, op, boundary):
import cupy as cp
ky, kx = kernel.shape
hy, hx = ky // 2, kx // 2
_func = partial(_morph_chunk_cupy, kernel=kernel, op=op)
return data.astype(cp.float64).map_overlap(
_func,
depth=(hy, hx),
boundary=_boundary_to_dask(boundary, is_cupy=True),
meta=cp.array(()),
)
def _erode_dask_cupy(data, kernel, boundary):
return _morph_dask_cupy(data, kernel, 'erode', boundary)
def _dilate_dask_cupy(data, kernel, boundary):
return _morph_dask_cupy(data, kernel, 'dilate', boundary)
def _opening_dask_cupy(data, kernel, boundary):
tmp = _morph_dask_cupy(data, kernel, 'erode', boundary)
return _morph_dask_cupy(tmp, kernel, 'dilate', boundary)
def _closing_dask_cupy(data, kernel, boundary):
tmp = _morph_dask_cupy(data, kernel, 'dilate', boundary)
return _morph_dask_cupy(tmp, kernel, 'erode', boundary)
# ---------------------------------------------------------------------------
# Dispatcher helpers
# ---------------------------------------------------------------------------
def _dispatch(agg, kernel, boundary, name, numpy_fn, cupy_fn, dask_fn, dask_cupy_fn):
"""Common dispatch logic for all four morphological functions."""
_validate_raster(agg, func_name=name, name='agg', ndim=2)
kernel = _validate_kernel(kernel, name)
_validate_boundary(boundary)
mapper = ArrayTypeFunctionMapping(
numpy_func=partial(numpy_fn, kernel=kernel, boundary=boundary),
cupy_func=partial(cupy_fn, kernel=kernel, boundary=boundary),
dask_func=partial(dask_fn, kernel=kernel, boundary=boundary),
dask_cupy_func=partial(dask_cupy_fn, kernel=kernel, boundary=boundary),
)
out = mapper(agg)(agg.data)
return DataArray(
out,
name=name,
dims=agg.dims,
coords=agg.coords,
attrs=agg.attrs,
)
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
@supports_dataset
def morph_erode(agg, kernel=None, boundary='nan', name='erode'):
"""Apply morphological erosion (local minimum) to a 2D raster.
Each output cell receives the minimum value found within the
structuring element footprint centred on that cell.
Parameters
----------
agg : xarray.DataArray
2D raster of numeric values.
kernel : numpy.ndarray or None
2D structuring element with odd dimensions. Non-zero entries
mark the footprint. Defaults to a 3x3 square
(``np.ones((3, 3), dtype=np.uint8)``).
boundary : str, default ``'nan'``
Edge handling: ``'nan'``, ``'nearest'``, ``'reflect'``, or
``'wrap'``.
name : str, default ``'erode'``
Name for the output DataArray.
Returns
-------
xarray.DataArray
Eroded raster with the same shape, coords, dims, and attrs
as the input.
Examples
--------
>>> from xrspatial.morphology import morph_erode
>>> eroded = morph_erode(raster, kernel=np.ones((5, 5), dtype=np.uint8))
"""
if kernel is None:
kernel = np.ones((3, 3), dtype=np.uint8)
return _dispatch(
agg, kernel, boundary, name,
_erode_numpy, _erode_cupy, _erode_dask_numpy, _erode_dask_cupy,
)
@supports_dataset
def morph_dilate(agg, kernel=None, boundary='nan', name='dilate'):
"""Apply morphological dilation (local maximum) to a 2D raster.
Each output cell receives the maximum value found within the
structuring element footprint centred on that cell.
Parameters
----------
agg : xarray.DataArray
2D raster of numeric values.
kernel : numpy.ndarray or None
2D structuring element with odd dimensions. Non-zero entries
mark the footprint. Defaults to a 3x3 square.
boundary : str, default ``'nan'``
Edge handling: ``'nan'``, ``'nearest'``, ``'reflect'``, or
``'wrap'``.
name : str, default ``'dilate'``
Name for the output DataArray.
Returns
-------
xarray.DataArray
Dilated raster.
Examples
--------
>>> from xrspatial.morphology import morph_dilate
>>> dilated = morph_dilate(raster, kernel=np.ones((5, 5), dtype=np.uint8))
"""
if kernel is None:
kernel = np.ones((3, 3), dtype=np.uint8)
return _dispatch(
agg, kernel, boundary, name,
_dilate_numpy, _dilate_cupy, _dilate_dask_numpy, _dilate_dask_cupy,
)
@supports_dataset
def morph_opening(agg, kernel=None, boundary='nan', name='opening'):
"""Apply morphological opening (erosion then dilation) to a 2D raster.
Opening removes small bright features and salt noise while
preserving the overall shape of larger structures.
Parameters
----------
agg : xarray.DataArray
2D raster of numeric values.
kernel : numpy.ndarray or None
2D structuring element with odd dimensions. Defaults to a
3x3 square.
boundary : str, default ``'nan'``
Edge handling: ``'nan'``, ``'nearest'``, ``'reflect'``, or
``'wrap'``.
name : str, default ``'opening'``
Name for the output DataArray.
Returns
-------
xarray.DataArray
Opened raster.
Examples
--------
>>> from xrspatial.morphology import morph_opening
>>> cleaned = morph_opening(binary_mask)
"""
if kernel is None:
kernel = np.ones((3, 3), dtype=np.uint8)
return _dispatch(
agg, kernel, boundary, name,
_opening_numpy, _opening_cupy, _opening_dask_numpy, _opening_dask_cupy,
)
@supports_dataset
def morph_closing(agg, kernel=None, boundary='nan', name='closing'):
"""Apply morphological closing (dilation then erosion) to a 2D raster.
Closing fills small dark gaps and pepper noise while preserving
the overall shape of larger structures.
Parameters
----------
agg : xarray.DataArray
2D raster of numeric values.
kernel : numpy.ndarray or None
2D structuring element with odd dimensions. Defaults to a
3x3 square.
boundary : str, default ``'nan'``
Edge handling: ``'nan'``, ``'nearest'``, ``'reflect'``, or
``'wrap'``.
name : str, default ``'closing'``
Name for the output DataArray.
Returns
-------
xarray.DataArray
Closed raster.
Examples
--------
>>> from xrspatial.morphology import morph_closing
>>> filled = morph_closing(binary_mask)
"""
if kernel is None:
kernel = np.ones((3, 3), dtype=np.uint8)
return _dispatch(
agg, kernel, boundary, name,
_closing_numpy, _closing_cupy, _closing_dask_numpy, _closing_dask_cupy,
)
@supports_dataset
def morph_gradient(agg, kernel=None, boundary='nan', name='gradient'):
"""Morphological gradient: dilation minus erosion.
Highlights edges and transitions in a 2D raster. The result is
always non-negative for non-NaN cells.
Parameters
----------
agg : xarray.DataArray
2D raster of numeric values.
kernel : numpy.ndarray or None
2D structuring element with odd dimensions. Defaults to a
3x3 square.
boundary : str, default ``'nan'``
Edge handling: ``'nan'``, ``'nearest'``, ``'reflect'``, or
``'wrap'``.
name : str, default ``'gradient'``
Name for the output DataArray.
Returns
-------
xarray.DataArray
Gradient raster (dilate - erode).
Examples
--------
>>> from xrspatial.morphology import morph_gradient
>>> edges = morph_gradient(elevation)
"""
dilated = morph_dilate(agg, kernel=kernel, boundary=boundary)
eroded = morph_erode(agg, kernel=kernel, boundary=boundary)
result = dilated - eroded
result.name = name
return result
@supports_dataset
def morph_white_tophat(agg, kernel=None, boundary='nan', name='white_tophat'):
"""White top-hat: original minus opening.
Isolates bright features that are smaller than the structuring
element.
Parameters
----------
agg : xarray.DataArray
2D raster of numeric values.
kernel : numpy.ndarray or None
2D structuring element with odd dimensions. Defaults to a
3x3 square.
boundary : str, default ``'nan'``
Edge handling: ``'nan'``, ``'nearest'``, ``'reflect'``, or
``'wrap'``.
name : str, default ``'white_tophat'``
Name for the output DataArray.
Returns
-------
xarray.DataArray
White top-hat raster (original - opening).
Examples
--------
>>> from xrspatial.morphology import morph_white_tophat
>>> bright = morph_white_tophat(elevation, kernel=circle_kernel)
"""
opened = morph_opening(agg, kernel=kernel, boundary=boundary)
result = agg - opened
result.name = name
return result
@supports_dataset
def morph_black_tophat(agg, kernel=None, boundary='nan', name='black_tophat'):
"""Black top-hat: closing minus original.
Isolates dark features that are smaller than the structuring
element.
Parameters
----------
agg : xarray.DataArray
2D raster of numeric values.
kernel : numpy.ndarray or None
2D structuring element with odd dimensions. Defaults to a
3x3 square.
boundary : str, default ``'nan'``
Edge handling: ``'nan'``, ``'nearest'``, ``'reflect'``, or
``'wrap'``.
name : str, default ``'black_tophat'``
Name for the output DataArray.
Returns
-------
xarray.DataArray
Black top-hat raster (closing - original).
Examples
--------
>>> from xrspatial.morphology import morph_black_tophat
>>> dark = morph_black_tophat(elevation, kernel=circle_kernel)
"""
closed = morph_closing(agg, kernel=kernel, boundary=boundary)
result = closed - agg
result.name = name
return result