-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathresampler_notebook.py
5783 lines (4858 loc) · 228 KB
/
resampler_notebook.py
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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# %% [markdown]
# # Resampler notebook
# <a name="Resampler-notebook"></a>
#
# [Hugues Hoppe](https://hhoppe.com/)
# Aug 2022.
#
# [**[Open in Colab]**](https://colab.research.google.com/github/hhoppe/resampler/blob/main/resampler_notebook.ipynb)
#
# [**[Kaggle]**](https://www.kaggle.com/notebooks/welcome?src=https://github.com/hhoppe/resampler/blob/main/resampler_notebook.ipynb)
#
# [**[MyBinder]**](https://mybinder.org/v2/gh/hhoppe/resampler/main?filepath=resampler_notebook.ipynb)
# <!-- [**[MyBinder]**](https://mybinder.org/v2/gh/hhoppe/resampler/HEAD?urlpath=lab/tree/resampler_notebook.ipynb) -->
# [**[DeepNote]**](https://deepnote.com/launch?url=https%3A%2F%2Fgithub.com%2Fhhoppe%2Fresampler%2Fblob%2Fmain%2Fresampler_notebook.ipynb)
#
# [**[GitHub source]**](https://github.com/hhoppe/resampler)
#
# [**[API docs]**](https://hhoppe.github.io/resampler/)
#
# [**[PyPI package]**](https://pypi.org/project/resampler/)
# %% [markdown]
# <!--
# Resize, warp, or interpolate arbitrary data arrays.
# A general-purpose library for resizing, scaling, transforming, and warping data sampled
# on regular grids.
# Flexible, differentiable resampling of arbitrary grids for efficient resizing and warping.
# -->
#
# The `resampler` library enables fast differentiable resizing and warping of arbitrary grids.
# It supports:
#
# - grids of **any dimension** (e.g., 1D, 2D images, 3D video, 4D batches of videos), containing
#
# - **samples of any shape** (e.g., scalars, colors, motion vectors, Jacobian matrices) and
#
# - any **numeric type** (e.g., `uint8`, `float64`, `complex128`)
#
# - within several [**array libraries**](#Array-libraries)
# (`numpy`, `tensorflow`, `torch`, and `jax`);
#
# - either `'dual'` ("half-integer") or `'primal'` [**grid-type**](#Grid-types--dual-and-primal-)
# for each dimension;
#
# - many [**boundary**](#Boundary-rules) rules,
# specified per dimension, extensible via subclassing;
#
# - an extensible set of [**filter**](#Filter-kernels) kernels, selectable per dimension;
#
# - optional [**gamma**](#Gamma-correction) transfer functions for correct linear-space filtering;
#
# - prefiltering for accurate **antialiasing** when `resize` downsampling;
#
# - efficient backpropagation of [**gradients**](#Gradient-backpropagation)
# for `tensorflow`, `torch`, and `jax`;
#
# - few dependencies (only `numpy` and `scipy`) and **no C extension code**, yet
#
# - [**faster resizing**](#Test-other-libraries) than C++ implementations
# in `tf.image` and `torch.nn`.
#
# A key strategy is to leverage existing sparse matrix representations and tensor operations.
# %% [markdown]
# **Example usage:**
#
# ```python
# !pip install -q mediapy resampler
# import mediapy as media
# import numpy as np
# import resampler
# ```
#
# ```python
# array = np.random.default_rng(1).random((4, 6, 3)) # 4x6 RGB image.
# upsampled = resampler.resize(array, (128, 192)) # To 128x192 resolution.
# media.show_images({'4x6': array, '128x192': upsampled}, height=128)
# ```
# > <img src="https://github.com/hhoppe/resampler/raw/main/media/example_array_upsampled.png"/>
#
# ```python
# image = media.read_image('https://github.com/hhoppe/data/raw/main/image.png')
# downsampled = resampler.resize(image, (32, 32))
# media.show_images({'128x128': image, '32x32': downsampled}, height=128)
# ```
# > <img src="https://github.com/hhoppe/resampler/raw/main/media/example_array_downsampled.png"/>
#
# ```python
# import matplotlib.pyplot as plt
# ```
#
# ```python
# array = [3.0, 5.0, 8.0, 7.0] # 4 source samples in 1D.
# new_dual = resampler.resize(array, (32,)) # (default gridtype='dual') 8x resolution.
# new_primal = resampler.resize(array, (25,), gridtype='primal') # 8x resolution.
#
# _, axs = plt.subplots(1, 2, figsize=(7, 1.5))
# axs[0].set(title="gridtype='dual'")
# axs[0].plot((np.arange(len(array)) + 0.5) / len(array), array, 'o')
# axs[0].plot((np.arange(len(new_dual)) + 0.5) / len(new_dual), new_dual, '.')
# axs[1].set(title="gridtype='primal'")
# axs[1].plot(np.arange(len(array)) / (len(array) - 1), array, 'o')
# axs[1].plot(np.arange(len(new_primal)) / (len(new_primal) - 1), new_primal, '.')
# plt.show()
# ```
# > <img src="https://github.com/hhoppe/resampler/raw/main/media/examples_1d_upsampling.png"/>
#
# ```python
# batch_size = 4
# batch_of_images = media.moving_circle((16, 16), batch_size)
# upsampled = resampler.resize(batch_of_images, (batch_size, 64, 64))
# media.show_videos({'original': batch_of_images, 'upsampled': upsampled}, fps=1)
# ```
# > original
# <img src="https://github.com/hhoppe/resampler/raw/main/media/batch_original.gif"/>
# upsampled
# <img src="https://github.com/hhoppe/resampler/raw/main/media/batch_upsampled.gif"/>
#
# Most examples above use the default
# [`resize()`](#Resize) settings:
# - [`gridtype='dual'`](#Grid-types--dual-and-primal-) for both source and destination arrays,
# - [`boundary='auto'`](#Boundary-rules)
# which uses `'reflect'` for upsampling and `'clamp'` for downsampling,
# - [`filter='lanczos3'`](#Filter-kernels)
# (a [Lanczos](https://en.wikipedia.org/wiki/Lanczos_resampling) kernel with radius 3),
# - [`gamma=None`](#Gamma-correction) which by default uses the `'power2'`
# transfer function for the `uint8` image in the second example,
# - `scale=1.0, translate=0.0` (no domain transformation),
# - default `precision` and output `dtype`.
# %% [markdown]
# **Advanced usage:**
#
# Map an image to a wider grid using custom `scale` and `translate` vectors,
# with horizontal `'reflect'` and vertical `'natural'` boundary rules,
# providing a constant value for the exterior,
# using different filters (Lanczos and O-MOMS) in the two dimensions,
# disabling gamma correction, performing computations in double-precision,
# and returning an output array in single-precision:
#
# ```python
# new = resampler.resize(
# image, (128, 512), boundary=('natural', 'reflect'), cval=(0.2, 0.7, 0.3),
# filter=('lanczos3', 'omoms5'), gamma='identity', scale=(0.8, 0.25),
# translate=(0.1, 0.35), precision='float64', dtype='float32')
# media.show_images({'image': image, 'new': new})
# ```
# > <img src="https://github.com/hhoppe/resampler/raw/main/media/example_advanced_usage1.png"/>
#
# Warp an image by transforming it using
# [polar coordinates](https://en.wikipedia.org/wiki/Polar_coordinate_system):
#
# ```python
# shape = image.shape[:2]
# yx = ((np.indices(shape).T + 0.5) / shape - 0.5).T # [-0.5, 0.5]^2
# radius, angle = np.linalg.norm(yx, axis=0), np.arctan2(*yx)
# angle += (0.8 - radius).clip(0, 1) * 2.0 - 0.6
# coords = np.dstack((np.sin(angle) * radius, np.cos(angle) * radius)) + 0.5
# resampled = resampler.resample(image, coords, boundary='constant')
# media.show_images({'image': image, 'resampled': resampled})
# ```
# > <img src="https://github.com/hhoppe/resampler/raw/main/media/example_warp.png"/>
# %% [markdown]
# **Limitations:**
#
# - Over multiple dimensions, filters are assumed to be [separable](https://en.wikipedia.org/wiki/Separable_filter).
# - Although `resize` implements prefiltering, `resample` does not yet have it (and therefore
# may have aliased results if downsampling).
# - Differentiability is with respect to the grid values,
# not wrt the `resize()` shape, scale, and translation, or wrt the `resample()` coordinates.
# %% [markdown]
# # Signal-processing concepts
# %% [markdown]
# In [digital signal processing](https://en.wikipedia.org/wiki/Digital_signal_processing),
# a [scalar field](https://en.wikipedia.org/wiki/Scalar_field)
# \(defined over a [Euclidean space](https://en.wikipedia.org/wiki/Euclidean_space)\)
# is represented using discrete
# [samples](https://en.wikipedia.org/wiki/Sampling_(signal_processing))
# \(defined over a [regular grid](https://en.wikipedia.org/wiki/Regular_grid)\).
# Converting between the field and samples involves
# [*reconstruction*](https://en.wikipedia.org/wiki/Sinc_interpolation)
# and [*sampling*](https://en.wikipedia.org/wiki/Sampling_(signal_processing)) (Figure 1).
# %% [markdown]
# <center>
# <img style="margin: 15px 0px 0px 0px;" src="https://github.com/hhoppe/resampler/raw/main/media/reconstruction_then_sampling.png" width="600"/>
# <br/>
# Figure 1: Reconstruction of an RGB color field from a 2D grid of pixel samples,
# and sampling of the field to obtain pixel values.
# </center>
# %% [markdown]
# - The **domain** is the region of interest:
# e.g., a 1D time interval, the 2D extent of an image, or a 3D cuboid of volumetric data.
# For simplicity, we let this domain be the unit
# [hypercube](https://en.wikipedia.org/wiki/Hypercube) $[0, 1]^d$.
#
# - A [*regular grid*](https://en.wikipedia.org/wiki/Regular_grid) distributes samples
# within the domain according to the
# [**grid-type**](#Grid-types--dual-and-primal-) (*dual* or *primal*):
# <center><img style="margin: 15px 0px 15px 0px;" src="https://github.com/hhoppe/resampler/raw/main/media/dual_primal.png"/></center>
#
# - [*Reconstruction*](https://en.wikipedia.org/wiki/Sinc_interpolation)
# creates an interpolating function (e.g., a 2D color field)
# from a sample grid (e.g., image pixels).
# The function is obtained as a sum along each dimension of translated *reconstruction filters*
# [weighted](https://en.wikipedia.org/wiki/Lanczos_resampling)
# by the sample values:
# <center><img style="margin: 15px 0px 15px 0px;" src="https://github.com/hhoppe/resampler/raw/main/media/reconstruction_weighted_kernels.png" width="500"/></center>
#
# - Common [**filter**](#Filter-kernels) choices include:
# <center><img style="margin: 15px 0px 15px 0px;" src="https://github.com/hhoppe/resampler/raw/main/media/filter_summary.png"/></center>
#
#
# - [**Boundary**](#Boundary-rules) rules determine the behavior of the
# reconstruction near and beyond the domain extent. Choices include:
# <center><img style="margin: 15px 0px 15px 0px;" src="https://github.com/hhoppe/resampler/raw/main/media/boundary_summary.png"/></center>
#
# - [*Sampling*](https://en.wikipedia.org/wiki/Sampling_(signal_processing))
# determines sample values given a field.
# To prevent [aliasing](https://en.wikipedia.org/wiki/Aliasing) artifacts,
# we convolve the field with a *prefilter*
# to remove frequencies larger than the destination grid's
# [Nyquist frequency](https://en.wikipedia.org/wiki/Nyquist_frequency)
# before evaluating the grid samples.
# Sampling does not involve boundary rules because the reconstructed field
# is already defined over the full space $\mathbb{R}^d$.
#
# - [**Gamma**](#Gamma-correction) correction uses
# [nonlinear transfer functions](https://en.wikipedia.org/wiki/Gamma_correction)
# \(e.g., [sRGB](https://en.wikipedia.org/wiki/SRGB)\)
# to decode/encode sample values, especially quantized `uint8` values.
#
# - The [**resize**](#Resize) operation converts a *source grid* to
# a *destination grid* as the composition of reconstruction and sampling (Figure 1).
# Such [sample rate conversion](https://en.wikipedia.org/wiki/Sample-rate_conversion)
# enables [downsampling](https://en.wikipedia.org/wiki/Downsampling_(signal_processing))
# and [upsampling](https://en.wikipedia.org/wiki/Upsampling).
# The operation also supports translation and non-uniform scaling
# from the source to the destination domain.
#
# - The [**resample_affine**](#resample-affine-function) operation allows an
# [affine map](https://en.wikipedia.org/wiki/Affine_transformation)
# (i.e., including rotation and shear) from the source to the destination domain.
#
# - The [**resample**](#Resample) operation is a generalization in which
# the destination samples are mapped to *arbitrary* coordinates in the source domain:
# <center><img style="margin: 15px 0px 15px 0px;" src="https://github.com/hhoppe/resampler/raw/main/media/example_warp_coords.png"/></center>
#
# - Efficient implementation of resize/resample is enabled by [two key
# observations](https://www2.eecs.berkeley.edu/Pubs/TechRpts/1989/CSD-89-516.pdf):
#
# 1. For upsampling (magnification), the sampling prefilter is *unnecessary*
# because the reconstructed field is already
# [bandlimited](https://en.wikipedia.org/wiki/Bandlimiting).
#
# 2. For downsampling (minification), the reconstruction filter
# can be replaced by a trivial *impulse* function because the
# reconstructed field is subsequently bandlimited by the sampling prefilter.
#
# <!--
# However, the *intermediate function* is impractical to represent on a computer.
# Most computations involve discretized representations.
#
# One can approximate the intermediate function using a high-resolution grid as was done
# in the previous figure.
#
# But in practice, it is possible to take a shortcut.
#
# - Magnification -> omit the prefilter kernel.
#
# - Minification -> omit the reconstruction kernel.
#
# To avoid the shortcut and obtain a higher-quality resampling, one can manually apply two
# successive resizing operations, where the intermediate grid has higher-resolution than
# either the source or destination grid.
#
# Computer graphics: supersampling.
# Given a procedural vector graphics or computer graphics rendering.
#
# Unused:
#
# https://en.wikipedia.org/wiki/Multidimensional_sampling
#
# https://en.wikipedia.org/wiki/Multivariate_interpolation
#
# -->
# %% [markdown]
# # Notebook header
# %%
# !command -v ffmpeg >/dev/null || conda install -y ffmpeg >&/dev/null || (apt update && apt install -y ffmpeg) # For mediapy.
# %%
# !pip install -qU numba numpy
# %%
# !pip list | grep opencv-python >/dev/null || pip install -q opencv-python-headless
# %%
# !pip install -q autopep8 hhoppe-tools 'jax[cpu]' matplotlib mediapy mypy \
# pdoc Pillow pyink pylint pytest resampler scipy scikit-image tensorflow-cpu torch
# %%
# %load_ext autoreload
# %autoreload 2
# %%
"""Python notebook demonstrating the `resampler` package."""
from __future__ import annotations
import collections
from collections.abc import Callable, Iterable, Mapping, Sequence
import concurrent.futures
import copy
import dataclasses
import functools
import heapq
import itertools
import math
import os
import pathlib
import sys
import types
import typing
from typing import Any, Literal, TypeVar
import warnings
import hhoppe_tools as hh # https://github.com/hhoppe/hhoppe-tools/blob/main/hhoppe_tools/__init__.py
import IPython
import jax
import jax.numpy as jnp
import matplotlib
import matplotlib.pyplot as plt
import mediapy as media # https://github.com/google/mediapy
import numpy as np
import pdoc
import scipy.signal
import skimage
import skimage.metrics
import tensorflow as tf
import torch
import torch.autograd
import resampler
try:
import numba
except ModuleNotFoundError:
numba = sys.modules['numba'] = types.ModuleType('numba')
numba.njit = hh.noop_decorator
using_numba = hasattr(numba, 'jit')
# pylint: disable=protected-access, missing-function-docstring
# mypy: allow-incomplete-defs, allow-untyped-defs
_ArrayLike = resampler._ArrayLike
_NDArray = resampler._NDArray
_TensorflowTensor = resampler._TensorflowTensor
_TorchTensor = resampler._TorchTensor
_JaxArray = resampler._JaxArray
_Array = TypeVar('_Array', _NDArray, _TensorflowTensor, _TorchTensor, _JaxArray)
_AnyArray = resampler._AnyArray
_UNICODE_DAGGER = '\u2020'
# %%
EFFORT: Literal[0, 1, 2, 3] = hh.get_env_int('EFFORT', 1) # type: ignore[assignment]
"""Controls the breadth and precision of the notebook experiments; 0 <= value <= 3."""
# %%
_ORIGINAL_GLOBALS = list(globals())
_: Any = np.seterr(all='raise') # Let all numpy warnings raise errors.
hh.start_timing_notebook_cells()
# %%
# Silence "This TensorFlow binary is optimized with oneAPI.."; https://stackoverflow.com/a/42121886
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
# %%
# Silence tf warning: "TqdmWarning: IProgress not found. Please update jupyter and ipywidgets."
warnings.filterwarnings('ignore', message='IProgress not found') # category=tqdm.TqdmWarning
# %%
# Silence "...but a CUDA-enabled jaxlib is not installed. Falling back to cpu."
# See https://github.com/google/jax/issues/6805.
jax.config.update('jax_platforms', 'cpu')
# %%
# Silence "RuntimeWarning: More than 20 figures have been opened." when run as script.
matplotlib.rcParams['figure.max_open_warning'] = 0
warnings.filterwarnings('ignore', message='FigureCanvasAgg is non-interactive')
# %%
def enable_jax_float64() -> None:
"""Enable use of double-precision float in Jax; this only works at startup."""
jax.config.update('jax_enable_x64', True)
enable_jax_float64()
# %%
def _check_eq(a: Any, b: Any) -> None:
"""If the two values or arrays are not equal, raise an exception with a useful message."""
are_equal = np.all(a == b) if isinstance(a, np.ndarray) else a == b
if not are_equal:
raise AssertionError(f'{a!r} == {b!r}')
# %%
_URL_BASE = 'https://github.com/hhoppe/data/raw/main'
EXAMPLE_IMAGE = media.read_image(f'{_URL_BASE}/image.png') # (128, 128, 3)
EXAMPLE_PHOTO = media.read_image(f'{_URL_BASE}/lillian_640x480.png') # (480, 640)
# %%
@functools.cache
def example_tissot_image() -> _NDArray:
"""Return image of shape (1000, 2000, 3) from
https://commons.wikimedia.org/wiki/File:Tissot_indicatrix_world_map_equirectangular_proj.svg"""
url = (
'https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/'
'Tissot_indicatrix_world_map_equirectangular_proj.svg/'
'2000px-Tissot_indicatrix_world_map_equirectangular_proj.svg.png'
)
return media.read_image(url)[..., :3]
# %%
@functools.cache
def example_vector_graphics_image() -> _NDArray:
"""Return image of shape (3300, 2550, 3)."""
# (We used the https://cloudconvert.com/pdf-to-png service to obtain this vector graphics
# rasterization, as it antialiases nicely without ringing.)
return media.read_image(f'{_URL_BASE}/apptexsyn_cloudconvert_page4_300dpi.png')
# %%
def display_markdown(text: str) -> None:
"""Show Markdown as output if within a notebook, or else noop."""
IPython.display.display(IPython.display.Markdown(text)) # type: ignore
# %%
hh.adjust_jupyterlab_markdown_width()
# %%
def show_var_docstring(module_dot_name: str) -> None:
"""Display a variable's documentation as formatted HTML."""
modulename, name = module_dot_name.rsplit('.', 1)
module = sys.modules[modulename]
ast_info = pdoc.doc_ast.walk_tree(module)
# text = ast_info.docstrings.get(name, '')
text = ast_info.var_docstrings.get(name, '')
text = f'**`{name}`** = {getattr(module, name)}<br/>{text}'
display_markdown(text)
hh.no_vertical_scroll()
# %%
def must_be_int(x: _ArrayLike) -> _NDArray:
"""Return float cast as int, asserting that there is no fractional part."""
result = np.asarray(x).astype(int, copy=False)
_check_eq(result, x)
return result
_check_eq(must_be_int(6 / 2), 3)
# %%
def get_rms(a: _ArrayLike, b: _ArrayLike) -> float:
"""Return the root-mean-square difference between two arrays."""
a2: _NDArray = media.to_float01(a)
b2: _NDArray = media.to_float01(b)
rms: float = np.sqrt(np.mean(np.square(a2 - b2))).item()
return rms
assert math.isclose(get_rms(0.2, 0.3), 0.1)
# %%
def get_psnr(a: _ArrayLike, b: _ArrayLike) -> float:
"""Return the Peak-Signal-to-Noise-Ratio (dB) between values, assuming a [0.0, 1.0] range."""
rms = get_rms(a, b)
psnr: float = 20 * np.log10(1.0 / (rms + 1e-10)).item()
return psnr
assert math.isclose(get_psnr(0.2, 0.3), 20.0)
# %%
def get_ssim(image1: _NDArray, image2: _NDArray) -> float:
"""Return the structural similarity metric [0.0, 1.0] between two images."""
_check_eq(image1.shape, image2.shape)
assert np.issubdtype(image1.dtype, np.floating)
assert np.issubdtype(image2.dtype, np.floating)
if 1:
func = skimage.metrics.structural_similarity
kwargs = dict(data_range=1.0, gaussian_weights=True, sigma=1.5, use_sample_covariance=False)
if image1.ndim == 3:
kwargs |= dict(channel_axis=2)
# Infers win_size=11.
return float(func(image1, image2, **kwargs)) # type: ignore[no-untyped-call]
# Identical result but ~10x slower. Default filter_size=11, filter_sigma=1.5.
return float(tf.image.ssim(image1, image2, max_val=1.0))
# %%
def test_ssim() -> None:
image1 = media.to_float01(EXAMPLE_IMAGE)
image2 = image1 * np.float32(0.9)
ssim = get_ssim(image1, image2)
assert 0.99 < ssim < 1.0 # Change in mean value does not change structure.
filter = np.ones((3, 3, 1)) / 9
image3 = scipy.ndimage.convolve(image1, filter, mode='reflect')
time1, ssim1 = hh.get_time_and_result(lambda: get_ssim(image1, image3))
assert 0.75 < ssim1 < 0.9 # Blurring causes loss of structural detail.
time2, ssim2 = hh.get_time_and_result(lambda: float(tf.image.ssim(image1, image3, max_val=1.0)))
if EFFORT >= 2:
print(f'{ssim1=:.6f} {ssim2=:.6f} {time1=:.4f} {time2=:.4f}')
assert abs(ssim1 - ssim2) < 0.0001
if EFFORT >= 1:
test_ssim()
# ssim1=0.789012 ssim2=0.789010 time1=0.0029 time2=0.0354
# %%
def crop_array(array: _ArrayLike, width: _ArrayLike, cval: _ArrayLike = 0) -> _NDArray:
"""Return array cropped (or padded) along each dimension.
Args:
array: Input data.
width: Crop widths (or pad widths if negative) before each dimension and after each dimension.
Must be broadcastable onto (2, array.ndim).
cval: Value to use when padding.
>>> array1 = np.arange(15).reshape(3, 5)
>>> crop_array(array1, 1)
array([[6, 7, 8]])
>>> crop_array(array1, (1, 2))
array([[7]])
>>> crop_array(array1, ((2, 1), (-1, 2)))
array([[11, 12],
[ 0, 0]])
>>> crop_array([1], -3, cval=5)
array([5, 5, 5, 1, 5, 5, 5])
>>> crop_array([1], [[-2], [-1]], cval=5)
array([5, 5, 1, 5])
"""
# https://stackoverflow.com/questions/66846983
array = np.asarray(array)
width = np.broadcast_to(width, (2, array.ndim))
if (width > 0).any():
slices = tuple(
slice(before, (-after if after else None)) for (before, after) in np.maximum(width, 0).T
)
array = array[slices]
if (width < 0).any():
array = np.pad(array, -np.minimum(width, 0).T, constant_values=cval)
return array
# %%
def show_grid_values(array, figsize=(14, 4), cmap='gray', **kwargs) -> None:
"""Show the values of a 2D grayscale array."""
array = np.asarray(array)
_check_eq(array.ndim, 2)
_, ax = plt.subplots(figsize=figsize)
ax.matshow(array, cmap=cmap, **kwargs)
for yx, value in np.ndenumerate(array):
text = f'{value}' if np.issubdtype(array.dtype, np.integer) else f'{value:.3f}'
# https://matplotlib.org/stable/api/_as_gen/matplotlib.patches.FancyBboxPatch.html
bbox = dict(boxstyle='square,pad=0.1', fc='white', lw=0)
x, y = yx[::-1]
ax.text(x, y, text, va='center', ha='center', bbox=bbox)
_ = ax.xaxis.set_ticks([]), ax.yaxis.set_ticks([])
plt.show()
# %%
def test_show_grid_values() -> None:
rng = np.random.default_rng(0)
show_grid_values(rng.integers(0, 256, size=(4, 16)), figsize=(14, 2), vmin=0, vmax=255)
show_grid_values(rng.random((2, 7)), figsize=(8, 1.3))
if EFFORT >= 1:
test_show_grid_values()
# %%
def create_checkerboard(
output_shape: tuple[int, ...], block_shape=(1, 1), dtype=np.float32
) -> _NDArray:
"""Return a grid of alternating blocks of 0 and 1 values.
>>> array = create_checkerboard((5, 7))
>>> array.dtype, array.shape, array.sum()
(dtype('float32'), (5, 7), 17.0)
"""
indices = np.moveaxis(np.indices(output_shape), 0, -1)
return ((indices // block_shape).sum(axis=-1) % 2).astype(dtype)
# %%
def experiment_preload_arraylibs_for_accurate_timings() -> None:
"""Perform library imports now so that later timings do not include this."""
for arraylib in resampler.ARRAYLIBS:
resampler._make_array(np.ones(1), arraylib)
if EFFORT >= 1:
experiment_preload_arraylibs_for_accurate_timings()
# %%
# TODO:
# - instead use default prefilter='trapezoid'.
# but then even more discontinuous at transition from minification to magnification? Not really.
# - Optimize the case of an affine map:
# convolve the source grid with a prefilter using FFT (if any dim is downsampling),
# then proceed as before. Slow!
# - For an affine map, create an anisotropic footprint of destination within the source domain.
# - Use jacobian and prefilter in resample().
# - Is lightness-space upsampling justified using experiments on natural images?
# (is linear-space downsampling justified using such experiments? it should be obvious.)
# - Try [gpu].
# %%
# Useful resources:
# https://legacy.imagemagick.org/Usage/filter/
# %% [markdown]
# # Library elements
# %% [markdown]
# ## Array libraries
# <a name="Array-libraries"></a>
# %% [markdown]
# The [`resize`](#resize-function) and [`resample`](#Resample)
# functions operate transparently on multidimensional arrays from several libraries,
# listed in `ARRAYLIBS`:
# %%
show_var_docstring('resampler.ARRAYLIBS')
# %% [markdown]
# Another array library that we could include is:
# - `cupy` (with `cupy.ndarray` and `cupyx.scipy.sparse.csr_matrix`).
# %% [markdown]
# We may consider switching to [`eagerpy`](https://github.com/jonasrauber/eagerpy) for cross-library support;
# it is more complete but less specialized;
# some missing features include:
# - Support for `einsum()` using a `str` subscripts argument.
# - The equivalent of `_make_sparse_matrix` and `_arr_matmul_sparse_dense`.
# - Support for `_make_array(array, arraylib)` and `arr_arraylib(array)`; or use `ep.get_dummy(str)`?
# - Alternatively, use of subclassing for extensibility.
# - Use of `np.dtype` as a shared standard for `dtype` attributes and `astype(...)` functions.
# - Implementations of `moveaxis()` and `swapaxes()` in the base class `eagerpy.Tensor` using `transpose()`.
# - Fix of the type signature of `full(shape, value)` to indicate that `value` may be scalar or tensor.
# %% [markdown]
# And, [`einops`](https://einops.rocks/) is another nice cross-library interface, but its functionality is focused on `einsum()`.
# %% [markdown]
# ## Grid-types (dual and primal)
# <a name="Grid-types--dual-and-primal-"></a>
# %% [markdown]
# Digital signal processing is commonly described with
# [samples at integer coordinates](https://en.wikipedia.org/wiki/Sinc_interpolation).
# However, this becomes cumbersome when a field is sampled at several resolutions,
# for example in an [image pyramid](https://en.wikipedia.org/wiki/Pyramid_(image_processing)).
# Indeed, the standard in computer graphics (including GPU hardware) is to let image pixels
# correspond to sample points at the center of grid cells, as shown in the
# *dual* grid-structure below.
# Each pyramid resolution level has a power-of-two number of pixels.
# Notably, sample locations are *different* at each resolution level.
#
# The alternative is the *primal* grid structure,
# in which samples have a nice nesting property.
# However, representing a domain at power-of-two scales requires a
# sequence of grids with non-power-of-two samples,
# which complicates data structures and algorithms
# (e.g. the [FFT](https://en.wikipedia.org/wiki/Fast_Fourier_transform)).
#
# We support both grid-types, selectable as either `gridtype='dual'` or `gridtype='primal'`.
# To avoid confusion, the `coords` parameter in `resampler.resample()` refers to coordinates
# with respect to the unit domain $[0, 1]^d$ rather than the sample lattice $\mathbb{Z}^d$.
# %%
show_var_docstring('resampler.GRIDTYPES')
# %% [markdown]
# ## Boundary rules
# <a name="Boundary-rules"></a>
# %% [markdown]
# Reconstruction creates a field as a sum of filters
# weighted by the sample values.
# However, the source samples are within a finite domain grid.
#
# <table><tr>
# <td><img src="https://github.com/hhoppe/resampler/raw/main/media/reconstruction_weighted_kernels.png" width="400"/></td>
# <td>    </td>
# <td><img src="https://github.com/hhoppe/resampler/raw/main/media/reconstruction.png" width="350"/></td>
# </tr></table>
#
# Boundary rules let us define the reconstructed function
# both near the domain boundary and beyond it.
#
# For a multidimensional domain $\mathbb{R}^d$,
# we can specify a separate boundary rule for each dimension.
#
# Given a point $p=(x_1,\ldots,x_d)\in \mathbb{R}^d$,
# the boundary rules affect its reconstructed value $f(p)$ as follows:
#
# 1. Optionally remap the coordinate $x_i$ to the domain interior $[0, 1]$.
#
# 2. Assign values to exterior grid samples, particularly those whose basis functions overlap
# the domain interior.
# These exterior samples may be assigned linear combinations of interior
# samples and/or some special constant value `cval`.
#
# 3. Compute the weighted interpolation $f(p)$.
#
# 4. Optionally override the reconstructed function $f(p)$ as an affine combination with the
# special constant value `cval` near or outside the domain boundary.
#
# Steps 1, 2, and 4 are specified by the classes `RemapCoordinates`, `ExtendSamples`,
# and `OverrideExteriorValue`, all of which are components of the class `Boundary`.
#
# Here are some [predefined `boundary` settings](#Predefined-boundary-rules):
# %%
show_var_docstring('resampler.BOUNDARIES')
# %% [markdown]
# ## Filter kernels
# <a name="Filter-kernels"></a>
# %% [markdown]
# Let us assume a dual grid in 1D, i.e. a domain $[0, 1]$ with sample values $a_i$ at positions $\frac{i+0.5}{N}$, $0\leq i < N$.
#
# The reconstructed field
# $f(x) = \sum_{i\in\mathbb{Z}} \,a_i\, \phi((x-(i+0.5))\cdot N)$
# is a sum of the grid samples $\{a_i\}$ weighted by a reconstruction
# [*filter kernel*](https://en.wikipedia.org/wiki/Kernel_(statistics))
# $\phi$.
# <!-- (A kernel is a [window function](https://en.wikipedia.org/wiki/Window_function),
# i.e., it has value zero outside of some some radius.) -->
#
# The [Nyquist-Shannon sampling
# theorem](https://en.wikipedia.org/wiki/Nyquist%E2%80%93Shannon_sampling_theorem)
# states that a function $f$ is exactly reconstructed
# from its samples $a_i = f(\frac{i+0.5}{N})$ if $\phi(x)$ is the
# [*sinc function*](https://en.wikipedia.org/wiki/Sinc_function)
# $\text{sinc}(x) = \frac{sin(\pi x)}{\pi x}$
# and $f$ has no frequencies higher than $2N$, i.e., twice the sample rate $N$.
#
# Because the sinc function has infinite support,
# in practice it is approximated by multiplying it with a window function $w(x)$.
# A frequently used approximation is the
# [Lanczos filter](https://en.wikipedia.org/wiki/Lanczos_resampling),
# whose radius parameter trades off speed and accuracy.
#
# A filter kernel is also used to prefilter the reconstructed field prior to sampling.
# By default, we assign this filter to be the same as the reconstruction filter.
# %% [markdown]
# All multidimensional filters are assumed to be separable.
# For rotation equivariance (e.g., bandlimit the signal uniformly in all directions),
# it would be nice to support the (non-separable) 2D rotationally symmetric
# [sombrero function](https://en.wikipedia.org/wiki/Sombrero_function)
# $f(\textbf{x}) = \text{jinc}(\|\textbf{x}\|)$,
# where $\text{jinc}(r) = 2J_1(\pi r)/(\pi r)$.
# (The Fourier transform of a circle
# [involves the first-order Bessel function of the first kind](https://en.wikipedia.org/wiki/Airy_disk).)
# %%
show_var_docstring('resampler.FILTERS')
# %% [markdown]
# The `'trapezoid'` filter is an antialiased version of the `'box'` filter.
# Its implementation is special in that its parameterized shape (edge slope)
# is made to adapt to the scaling factor in a `resize` operation.
#
# [Experiments](#Best-filter-for-resize) show that `'lanczos3'` is generally an effective filter,
# except when *downsampling vector graphics content*,
# in which case the `'trapezoid'` filter is favored because it minimizes
# [*ringing*](https://en.wikipedia.org/wiki/Ringing_artifacts) artifacts.
# %% [markdown]
# ## Gamma correction
# <a name="Gamma-correction"></a>
# %% [markdown]
# Quantized values (e.g., `uint8`) often lack sufficient precision,
# causing [banding](https://en.wikipedia.org/wiki/Color_banding) artifacts in images.
# To reduce this problem, it is common to transform physical ("linear-space") intensities $l$
# to more perceptual ("lightness space") values $e$
# using a nonlinear transfer function
# (a.k.a. [gamma correction](https://en.wikipedia.org/wiki/Gamma_correction)\)
# prior to quantization.
#
# Here are the predefined schemes:
# %%
show_var_docstring('resampler.GAMMAS')
# %% [markdown]
# (`'srgb'` corresponds to the [sRGB](https://en.wikipedia.org/wiki/SRGB) standard
# and its encoding function includes an additional linear map segment near zero.)
#
# For grids with data type `uint8`, the default is `gamma='power2'`
# (chosen for its tradeoff of accuracy and efficiency).
# Therefore, we square the values when converting them to floating-point, perform resampling,
# and take the square-root before quantizing the values back to `uint8`.
#
# For other data types, the default transfer function is `gamma='identity'`.
# %% [markdown]
# ## Resize
# <a name="Resize"></a>
# %%
hh.pdoc_help(resampler.resize)
hh.no_vertical_scroll()
# %% [markdown]
# Because the reconstruction and prefilter kernels are assumed to be separable functions,
# we implement multidimensional resizing by iteratively modifying the sampling resolution
# along one dimension at a time.
# The order of these 1D resize operations does not affect the final result
# (up to machine precision), but it affects total execution time.
# %%
hh.pdoc_help(resampler.resize_in_arraylib)
# %%
hh.pdoc_help(resampler.jaxjit_resize)
# %%
# display_markdown(resampler.resize.__doc__) # It omits the function parameters and defaults.
# %%
if 0: # For testing.
resampler.resize = typing.cast(
Any, functools.partial(resampler._resize_possibly_in_arraylib, arraylib='torch')
)
# Note: resize() in jax may return a non-writable np.ndarray, and consequently torch may warn
# "The given NumPy array is not writable, and PyTorch does not support non-writable tensors".
# %%
def resize_showing_domain_boundary(
array: _NDArray, shape, *, scale=0.6, translate=0.2, **kwargs
) -> _NDArray:
array = np.asarray(resampler.resize(array, shape, scale=scale, translate=translate, **kwargs))
yx_low = (np.array(shape) * translate + 0.5).astype(int)
yx_high = (np.array(shape) * (translate + scale) + 0.5).astype(int)
yx = np.indices(shape)
conditions = [
((t == l) | (t == h)) & (t2 >= l2) & (t2 <= h2)
for t, l, h, t2, l2, h2 in zip(yx, yx_low, yx_high, yx[::-1], yx_low[::-1], yx_high[::-1])
]
on_boundary = np.logical_or.reduce(conditions)
line_color = np.mod(yx.sum(axis=0), 8) < 4 # Dashed black-and-white line.
array = np.where(on_boundary, line_color.T, array.T).T
return array
# %%
def visualize_filters_on_checkerboard(src_shape=(12, 8), boundary='wrap') -> None:
original = create_checkerboard(src_shape)
for dst_shape in [(11, 7), (9, 6), (7, 5), (6, 4), (5, 3), (15, 14)]:
filters = 'impulse box trapezoid triangle cubic lanczos3 lanczos5 lanczos10'.split()
display_markdown(
f'Resizing checkerboard from shape `{src_shape}`'
f" to `{dst_shape}` with boundary=`'{boundary}'`:"
)
images = {
f"'{filter}'": resampler.resize(original, dst_shape, filter=filter, boundary=boundary)
for filter in filters
}
images = {'original': original} | images
media.show_images(images, border=True, vmin=0, vmax=1, width=64)
if EFFORT >= 1:
visualize_filters_on_checkerboard()
# %% [markdown]
# ## Resample
# <a name="Resample"></a>
# %%
hh.pdoc_help(resampler.resample)
hh.no_vertical_scroll()
# %%
hh.pdoc_help(resampler.resample_affine)
hh.no_vertical_scroll()
# %%
hh.pdoc_help(resampler.rotation_about_center_in_2d)
# %%
hh.pdoc_help(resampler.rotate_image_about_center)
# %%
# General resample:
# Jacobian matrix: of the parametric map from destination pixel coordinates to source pixel
# coordinates.
# Desirable to adjust in 2 ways:
# (1) orthogonalize the column vectors, to avoid interference-pattern artifacts due to
# interference of x and y kernels with negative lobes.
# (2) if either column vector has norm less than 1, indicating upsampling in that direction,
# the vector should be normalized so that the filter kernel acts as reconstruction rather
# than prefiltering.
# %%
# Samples the color at a destination image pixel (x, y) given the 'location' (u, v) in a source
# image and the 2x2 Jacobian matrix of the map from the destination to the source:
#
# [du/dx, du/dy]
# [dv/dx, dv/dy]
#
# Thus, the two columns of the Jacobian matrix represent the preimages in the source of the
# destination image's unit axis vectors. I.e., if the norm of the first column is less than 1,
# then the resampling operation from source to destination performs upsampling along the X axis of
# the destination image. Internally, the column vectors of the Jacobian are orthogonalized and
# rescaled as desired for sampling if the options.adjust_jacobian is set to True.
# %%
# Currently we cannot apply jax.jit to resampler.resample() because the `coords` argument is
# processed using numpy and therefore cannot be differentiated.
# Also, because `coords` is an array it cannot be marked as a static argument.
# We could allow `coords` to be a general `_Array` type;
# this would involve generalizing the code in the Boundary and Filter classes?
# %%
def test_profile_resample() -> None:
def run(src_shape, dst_shape) -> None:
hh.prun(lambda: resampler._resize_using_resample(np.ones(src_shape), dst_shape), top=5)
run((8192,) * 2 + (3,), (2048,) * 2)
run((1024,) * 2 + (3,), (2048,) * 2)
if EFFORT >= 2:
test_profile_resample()
# The bottleneck is the memory gather:
# Prun: tottime 3.441 overall_cumtime
# 1.694 1.694 getitem (/mnt/c/Users/hhoppe/Dropbox/proj/resampler/resampler/__init__.py:345)
# 0.398 0.398 numpy.core._multiarray_umath.c_einsum (built-in)
# 0.361 0.361 ones (numpy/core/numeric.py:136)
# 0.279 3.007 resample (/mnt/c/Users/hhoppe/Dropbox/proj/resampler/resampler/__init__.py:2956)
# 0.185 0.247 interpolate_using_cached_samples (/mnt/c/Users/hhoppe/Dropbox/proj/resampler/resampler/__init__.py:158)
# Prun: tottime 2.986 overall_cumtime
# 1.659 1.659 getitem (/mnt/c/Users/hhoppe/Dropbox/proj/resampler/resampler/__init__.py:345)
# 0.384 0.384 numpy.core._multiarray_umath.c_einsum (built-in)
# 0.280 2.936 resample (/mnt/c/Users/hhoppe/Dropbox/proj/resampler/resampler/__init__.py:2956)
# 0.182 0.245 interpolate_using_cached_samples (/mnt/c/Users/hhoppe/Dropbox/proj/resampler/resampler/__init__.py:158)
# 0.128 0.128 numpy.ufunc.reduce
# %%
if 0: # For testing.
resampler.resize = typing.cast(
Any, functools.partial(resampler._resize_using_resample, fallback=True)
)
# %% [markdown]
# # Tests
# %%
def test_cached_sampling_of_1d_function(radius=2.0) -> None: