-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy path__init__.py
More file actions
2085 lines (1774 loc) · 69.8 KB
/
__init__.py
File metadata and controls
2085 lines (1774 loc) · 69.8 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
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
# Copyright 2025 The mediapy Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""`mediapy`: Read/write/show images and videos in an IPython/Jupyter notebook.
[**[GitHub source]**](https://github.com/google/mediapy)
[**[API docs]**](https://google.github.io/mediapy/)
[**[PyPI package]**](https://pypi.org/project/mediapy/)
[**[Colab
example]**](https://colab.research.google.com/github/google/mediapy/blob/main/mediapy_examples.ipynb)
See the [example
notebook](https://github.com/google/mediapy/blob/main/mediapy_examples.ipynb),
or better yet, [**open it in
Colab**](https://colab.research.google.com/github/google/mediapy/blob/main/mediapy_examples.ipynb).
## Image examples
Display an image (2D or 3D `numpy` array):
```python
checkerboard = np.kron([[0, 1] * 16, [1, 0] * 16] * 16, np.ones((4, 4)))
show_image(checkerboard)
```
Read and display an image (either local or from the Web):
```python
IMAGE = 'https://github.com/hhoppe/data/raw/main/image.png'
show_image(read_image(IMAGE))
```
Read and display an image from a local file:
```python
!wget -q -O /tmp/burano.png {IMAGE}
show_image(read_image('/tmp/burano.png'))
```
Show titled images side-by-side:
```python
images = {
'original': checkerboard,
'darkened': checkerboard * 0.7,
'random': np.random.rand(32, 32, 3),
}
show_images(images, vmin=0.0, vmax=1.0, border=True, height=64)
```
Compare two images using an interactive slider:
```python
compare_images([checkerboard, np.random.rand(128, 128, 3)])
```
## Video examples
Display a video (an iterable of images, e.g., a 3D or 4D array):
```python
video = moving_circle((100, 100), num_images=10)
show_video(video, fps=10)
```
Show the video frames side-by-side:
```python
show_images(video, columns=6, border=True, height=64)
```
Show the frames with their indices:
```python
show_images({f'{i}': image for i, image in enumerate(video)}, width=32)
```
Read and display a video (either local or from the Web):
```python
VIDEO = 'https://github.com/hhoppe/data/raw/main/video.mp4'
show_video(read_video(VIDEO))
```
Create and display a looping two-frame GIF video:
```python
image1 = resize_image(np.random.rand(10, 10, 3), (50, 50))
show_video([image1, image1 * 0.8], fps=2, codec='gif')
```
Darken a video frame-by-frame:
```python
output_path = '/tmp/out.mp4'
with VideoReader(VIDEO) as r:
darken_image = lambda image: to_float01(image) * 0.5
with VideoWriter(output_path, shape=r.shape, fps=r.fps, bps=r.bps) as w:
for image in r:
w.add_image(darken_image(image))
```
"""
from __future__ import annotations
__docformat__ = 'google'
__version__ = '1.2.6'
__version_info__ = tuple(int(num) for num in __version__.split('.'))
import base64
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
import contextlib
import functools
import importlib
import io
import itertools
import math
import numbers
import os # Package only needed for typing.TYPE_CHECKING.
import pathlib
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
import typing
from typing import Any
import urllib.request
import warnings
import IPython.display
import matplotlib.pyplot
import numpy as np
import numpy.typing as npt
import PIL.Image
import PIL.ImageOps
if not hasattr(PIL.Image, 'Resampling'): # Allow Pillow<9.0.
PIL.Image.Resampling = PIL.Image # type: ignore
# Selected and reordered here for pdoc documentation.
__all__ = [
'show_image',
'show_images',
'compare_images',
'show_video',
'show_videos',
'read_image',
'write_image',
'read_video',
'write_video',
'VideoReader',
'VideoWriter',
'VideoMetadata',
'compress_image',
'decompress_image',
'compress_video',
'decompress_video',
'html_from_compressed_image',
'html_from_compressed_video',
'resize_image',
'resize_video',
'to_rgb',
'to_type',
'to_float01',
'to_uint8',
'set_output_height',
'set_max_output_height',
'color_ramp',
'moving_circle',
'set_show_save_dir',
'set_ffmpeg',
'video_is_available',
]
if typing.TYPE_CHECKING:
_ArrayLike = npt.ArrayLike
_DTypeLike = npt.DTypeLike
_NDArray = npt.NDArray[Any]
_DType = np.dtype[Any]
else:
# Create named types for use in the `pdoc` documentation.
_ArrayLike = typing.TypeVar('_ArrayLike')
_DTypeLike = typing.TypeVar('_DTypeLike')
_NDArray = typing.TypeVar('_NDArray')
_DType = typing.TypeVar('_DType') # pylint: disable=invalid-name
_IPYTHON_HTML_SIZE_LIMIT = 10**10 # Unlimited seems to be OK now.
_T = typing.TypeVar('_T')
_Path = typing.Union[str, 'os.PathLike[str]']
_IMAGE_COMPARISON_HTML = """\
<script
defer
src="https://unpkg.com/img-comparison-slider@7/dist/index.js"
></script>
<link
rel="stylesheet"
href="https://unpkg.com/img-comparison-slider@7/dist/styles.css"
/>
<img-comparison-slider>
<img slot="first" src="data:image/png;base64,{b64_1}" />
<img slot="second" src="data:image/png;base64,{b64_2}" />
</img-comparison-slider>
"""
# ** Miscellaneous.
class _Config:
ffmpeg_name_or_path: _Path = 'ffmpeg'
show_save_dir: _Path | None = None
_config = _Config()
def _open(path: _Path, *args: Any, **kwargs: Any) -> Any:
"""Opens the file; this is a hook for the built-in `open()`."""
return open(path, *args, **kwargs)
def _path_is_local(path: _Path) -> bool:
"""Returns True if the path is in the filesystem accessible by `ffmpeg`."""
del path
return True
def _search_for_ffmpeg_path() -> str | None:
"""Returns a path to the ffmpeg program, or None if not found."""
if filename := shutil.which(_config.ffmpeg_name_or_path):
return str(filename)
return None
def _print_err(*args: str, **kwargs: Any) -> None:
"""Prints arguments to stderr immediately."""
kwargs = {**dict(file=sys.stderr, flush=True), **kwargs}
print(*args, **kwargs)
def _chunked(
iterable: Iterable[_T], n: int | None = None
) -> Iterator[tuple[_T, ...]]:
"""Returns elements collected as tuples of length at most `n` if not None."""
def take(n: int | None, iterable: Iterable[_T]) -> tuple[_T, ...]:
return tuple(itertools.islice(iterable, n))
return iter(functools.partial(take, n, iter(iterable)), ())
def _peek_first(iterator: Iterable[_T]) -> tuple[_T, Iterable[_T]]:
"""Given an iterator, returns first element and re-initialized iterator.
>>> first_image, images = _peek_first(moving_circle())
Args:
iterator: An input iterator or iterable.
Returns:
A tuple (first_element, iterator_reinitialized) containing:
first_element: The first element of the input.
iterator_reinitialized: A clone of the original iterator/iterable.
"""
# Inspired from https://stackoverflow.com/a/12059829/1190077
peeker, iterator_reinitialized = itertools.tee(iterator)
first = next(peeker)
return first, iterator_reinitialized
def _check_2d_shape(shape: tuple[int, int]) -> None:
"""Checks that `shape` is of the form (height, width) with two integers."""
if len(shape) != 2:
raise ValueError(f'Shape {shape} is not of the form (height, width).')
if not all(isinstance(i, numbers.Integral) for i in shape):
raise ValueError(f'Shape {shape} contains non-integers.')
def _run(args: str | Sequence[str]) -> None:
"""Executes command, printing output from stdout and stderr.
Args:
args: Command to execute, which can be either a string or a sequence of word
strings, as in `subprocess.run()`. If `args` is a string, the shell is
invoked to interpret it.
Raises:
RuntimeError: If the command's exit code is nonzero.
"""
proc = subprocess.run(
args,
shell=isinstance(args, str),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
check=False,
universal_newlines=True,
)
print(proc.stdout, end='', flush=True)
if proc.returncode:
raise RuntimeError(
f"Command '{proc.args}' failed with code {proc.returncode}."
)
def _display_html(text: str, /) -> None:
"""In a Jupyter notebook, display the HTML `text`."""
IPython.display.display(IPython.display.HTML(text)) # type: ignore
def set_ffmpeg(name_or_path: _Path) -> None:
"""Specifies the name or path for the `ffmpeg` external program.
The `ffmpeg` program is required for compressing and decompressing video.
(It is used in `read_video`, `write_video`, `show_video`, `show_videos`,
etc.)
Args:
name_or_path: Either a filename within a directory of `os.environ['PATH']`
or a filepath. The default setting is 'ffmpeg'.
"""
_config.ffmpeg_name_or_path = name_or_path
def set_output_height(num_pixels: int) -> None:
"""Overrides the height of the current output cell, if using Colab."""
try:
# We want to fail gracefully for non-Colab IPython notebooks.
output = importlib.import_module('google.colab.output')
s = f'google.colab.output.setIframeHeight("{num_pixels}px")'
output.eval_js(s)
except (ModuleNotFoundError, AttributeError):
pass
def set_max_output_height(num_pixels: int) -> None:
"""Sets the maximum height of the current output cell, if using Colab."""
try:
# We want to fail gracefully for non-Colab IPython notebooks.
output = importlib.import_module('google.colab.output')
s = (
'google.colab.output.setIframeHeight('
f'0, true, {{maxHeight: {num_pixels}}})'
)
output.eval_js(s)
except (ModuleNotFoundError, AttributeError):
pass
# ** Type conversions.
def _as_valid_media_type(dtype: _DTypeLike) -> _DType:
"""Returns validated media data type."""
dtype = np.dtype(dtype)
if not issubclass(dtype.type, (np.unsignedinteger, np.floating)):
raise ValueError(
f'Type {dtype} is not a valid media data type (uint or float).'
)
return dtype
def _as_valid_media_array(x: _ArrayLike) -> _NDArray:
"""Converts to ndarray (if not already), and checks validity of data type."""
a = np.asarray(x)
if a.dtype == bool:
a = a.astype(np.uint8) * np.iinfo(np.uint8).max
_as_valid_media_type(a.dtype)
return a
def to_type(array: _ArrayLike, dtype: _DTypeLike) -> _NDArray:
"""Returns media array converted to specified type.
A "media array" is one in which the dtype is either a floating-point type
(np.float32 or np.float64) or an unsigned integer type. The array values are
assumed to lie in the range [0.0, 1.0] for floating-point values, and in the
full range for unsigned integers, e.g. [0, 255] for np.uint8.
Conversion between integers and floats maps uint(0) to 0.0 and uint(MAX) to
1.0. The input array may also be of type bool, whereby True maps to
uint(MAX) or 1.0. The values are scaled and clamped as appropriate during
type conversions.
Args:
array: Input array-like object (floating-point, unsigned int, or bool).
dtype: Desired output type (floating-point or unsigned int).
Returns:
Array `a` if it is already of the specified dtype, else a converted array.
"""
a = np.asarray(array)
dtype = np.dtype(dtype)
del array
if a.dtype != bool:
_as_valid_media_type(a.dtype) # Verify that 'a' has a valid dtype.
if a.dtype == bool:
result = a.astype(dtype)
if np.issubdtype(dtype, np.unsignedinteger):
result = result * dtype.type(np.iinfo(dtype).max)
elif a.dtype == dtype:
result = a
elif np.issubdtype(dtype, np.unsignedinteger):
if np.issubdtype(a.dtype, np.unsignedinteger):
src_max: float = np.iinfo(a.dtype).max
else:
a = np.clip(a, 0.0, 1.0)
src_max = 1.0
dst_max = np.iinfo(dtype).max
if dst_max <= np.iinfo(np.uint16).max:
scale = np.array(dst_max / src_max, dtype=np.float32)
result = (a * scale + 0.5).astype(dtype)
elif dst_max <= np.iinfo(np.uint32).max:
result = (a.astype(np.float64) * (dst_max / src_max) + 0.5).astype(dtype)
else:
# https://stackoverflow.com/a/66306123/
a = a.astype(np.float64) * (dst_max / src_max) + 0.5
dst = np.atleast_1d(a)
values_too_large = dst >= np.float64(dst_max)
with np.errstate(invalid='ignore'):
dst = dst.astype(dtype)
dst[values_too_large] = dst_max
result = dst if a.ndim > 0 else dst[0]
else:
assert np.issubdtype(dtype, np.floating)
result = a.astype(dtype)
if np.issubdtype(a.dtype, np.unsignedinteger):
result = result / dtype.type(np.iinfo(a.dtype).max)
return result
def to_float01(a: _ArrayLike, dtype: _DTypeLike = np.float32) -> _NDArray:
"""If array has unsigned integers, rescales them to the range [0.0, 1.0].
Scaling is such that uint(0) maps to 0.0 and uint(MAX) maps to 1.0. See
`to_type`.
Args:
a: Input array.
dtype: Desired floating-point type if rescaling occurs.
Returns:
A new array of dtype values in the range [0.0, 1.0] if the input array `a`
contains unsigned integers; otherwise, array `a` is returned unchanged.
"""
a = np.asarray(a)
dtype = np.dtype(dtype)
if not np.issubdtype(dtype, np.floating):
raise ValueError(f'Type {dtype} is not floating-point.')
if np.issubdtype(a.dtype, np.floating):
return a
return to_type(a, dtype)
def to_uint8(a: _ArrayLike) -> _NDArray:
"""Returns array converted to uint8 values; see `to_type`."""
return to_type(a, np.uint8)
# ** Functions to generate example image and video data.
def color_ramp(
shape: tuple[int, int] = (64, 64), *, dtype: _DTypeLike = np.float32
) -> _NDArray:
"""Returns an image of a red-green color gradient.
This is useful for quick experimentation and testing. See also
`moving_circle` to generate a sample video.
Args:
shape: 2D spatial dimensions (height, width) of generated image.
dtype: Type (uint or floating) of resulting pixel values.
"""
_check_2d_shape(shape)
dtype = _as_valid_media_type(dtype)
yx = (np.moveaxis(np.indices(shape), 0, -1) + 0.5) / shape
image = np.insert(yx, 2, 0.0, axis=-1)
return to_type(image, dtype)
def moving_circle(
shape: tuple[int, int] = (256, 256),
num_images: int = 10,
*,
dtype: _DTypeLike = np.float32,
) -> _NDArray:
"""Returns a video of a circle moving in front of a color ramp.
This is useful for quick experimentation and testing. See also `color_ramp`
to generate a sample image.
>>> show_video(moving_circle((480, 640), 60), fps=60)
Args:
shape: 2D spatial dimensions (height, width) of generated video.
num_images: Number of video frames.
dtype: Type (uint or floating) of resulting pixel values.
"""
_check_2d_shape(shape)
dtype = np.dtype(dtype)
def generate_image(image_index: int) -> _NDArray:
"""Returns a video frame image."""
image = color_ramp(shape, dtype=dtype)
yx = np.moveaxis(np.indices(shape), 0, -1)
center = shape[0] * 0.6, shape[1] * (image_index + 0.5) / num_images
radius_squared = (min(shape) * 0.1) ** 2
inside = np.sum((yx - center) ** 2, axis=-1) < radius_squared
white_circle_color = 1.0, 1.0, 1.0
if np.issubdtype(dtype, np.unsignedinteger):
white_circle_color = to_type([white_circle_color], dtype)[0]
image[inside] = white_circle_color
return image
return np.array([generate_image(i) for i in range(num_images)])
# ** Color-space conversions.
# Same matrix values as in two sources:
# https://github.com/scikit-image/scikit-image/blob/master/skimage/color/colorconv.py#L377
# https://github.com/tensorflow/tensorflow/blob/r1.14/tensorflow/python/ops/image_ops_impl.py#L2754
_YUV_FROM_RGB_MATRIX = np.array(
[
[0.299, -0.14714119, 0.61497538],
[0.587, -0.28886916, -0.51496512],
[0.114, 0.43601035, -0.10001026],
],
dtype=np.float32,
)
_RGB_FROM_YUV_MATRIX = np.linalg.inv(_YUV_FROM_RGB_MATRIX)
_YUV_CHROMA_OFFSET = np.array([0.0, 0.5, 0.5], dtype=np.float32)
def yuv_from_rgb(rgb: _ArrayLike) -> _NDArray:
"""Returns the RGB image/video mapped to YUV [0,1] color space.
Note that the "YUV" color space used by video compressors is actually YCbCr!
Args:
rgb: Input image in sRGB space.
"""
rgb = to_float01(rgb)
if rgb.shape[-1] != 3:
raise ValueError(f'The last dimension in {rgb.shape} is not 3.')
return rgb @ _YUV_FROM_RGB_MATRIX + _YUV_CHROMA_OFFSET
def rgb_from_yuv(yuv: _ArrayLike) -> _NDArray:
"""Returns the YUV image/video mapped to RGB [0,1] color space."""
yuv = to_float01(yuv)
if yuv.shape[-1] != 3:
raise ValueError(f'The last dimension in {yuv.shape} is not 3.')
return (yuv - _YUV_CHROMA_OFFSET) @ _RGB_FROM_YUV_MATRIX
# Same matrix values as in
# https://github.com/scikit-image/scikit-image/blob/master/skimage/color/colorconv.py#L1654
# and https://en.wikipedia.org/wiki/YUV#Studio_swing_for_BT.601
_YCBCR_FROM_RGB_MATRIX = np.array(
[
[65.481, 128.553, 24.966],
[-37.797, -74.203, 112.0],
[112.0, -93.786, -18.214],
],
dtype=np.float32,
).transpose()
_RGB_FROM_YCBCR_MATRIX = np.linalg.inv(_YCBCR_FROM_RGB_MATRIX)
_YCBCR_OFFSET = np.array([16.0, 128.0, 128.0], dtype=np.float32)
# Note that _YCBCR_FROM_RGB_MATRIX =~ _YUV_FROM_RGB_MATRIX * [219, 256, 182];
# https://en.wikipedia.org/wiki/YUV: "Y' values are conventionally shifted and
# scaled to the range [16, 235] (referred to as studio swing or 'TV levels')";
# "studio range of 16-240 for U and V". (Where does value 182 come from?)
def ycbcr_from_rgb(rgb: _ArrayLike) -> _NDArray:
"""Returns the RGB image/video mapped to YCbCr [0,1] color space.
The YCbCr color space is the one called "YUV" by video compressors.
Args:
rgb: Input image in sRGB space.
"""
rgb = to_float01(rgb)
if rgb.shape[-1] != 3:
raise ValueError(f'The last dimension in {rgb.shape} is not 3.')
return (rgb @ _YCBCR_FROM_RGB_MATRIX + _YCBCR_OFFSET) / 255.0
def rgb_from_ycbcr(ycbcr: _ArrayLike) -> _NDArray:
"""Returns the YCbCr image/video mapped to RGB [0,1] color space."""
ycbcr = to_float01(ycbcr)
if ycbcr.shape[-1] != 3:
raise ValueError(f'The last dimension in {ycbcr.shape} is not 3.')
return (ycbcr * 255.0 - _YCBCR_OFFSET) @ _RGB_FROM_YCBCR_MATRIX
# ** Image processing.
def _pil_image(image: _ArrayLike, mode: str | None = None) -> PIL.Image.Image:
"""Returns a PIL image given a numpy matrix (either uint8 or float [0,1])."""
image = _as_valid_media_array(image)
if image.ndim not in (2, 3):
raise ValueError(f'Image shape {image.shape} is neither 2D nor 3D.')
pil_image: PIL.Image.Image = PIL.Image.fromarray(image, mode=mode)
return pil_image
def resize_image(image: _ArrayLike, shape: tuple[int, int]) -> _NDArray:
"""Resizes image to specified spatial dimensions using a Lanczos filter.
Args:
image: Array-like 2D or 3D object, where dtype is uint or floating-point.
shape: 2D spatial dimensions (height, width) of output image.
Returns:
A resampled image whose spatial dimensions match `shape`.
"""
image = _as_valid_media_array(image)
if image.ndim not in (2, 3):
raise ValueError(f'Image shape {image.shape} is neither 2D nor 3D.')
_check_2d_shape(shape)
# A PIL image can be multichannel only if it has 3 or 4 uint8 channels,
# and it can be resized only if it is uint8 or float32.
supported_single_channel = (
np.issubdtype(image.dtype, np.floating) or image.dtype == np.uint8
) and image.ndim == 2
supported_multichannel = (
image.dtype == np.uint8 and image.ndim == 3 and image.shape[2] in (3, 4)
)
if supported_single_channel or supported_multichannel:
return np.array(
_pil_image(image).resize(
shape[::-1], resample=PIL.Image.Resampling.LANCZOS
),
dtype=image.dtype,
)
if image.ndim == 2:
# We convert to floating-point for resizing and convert back.
return to_type(resize_image(to_float01(image), shape), image.dtype)
# We resize each image channel individually.
return np.dstack(
[resize_image(channel, shape) for channel in np.moveaxis(image, -1, 0)]
)
# ** Video processing.
def resize_video(video: Iterable[_NDArray], shape: tuple[int, int]) -> _NDArray:
"""Resizes `video` to specified spatial dimensions using a Lanczos filter.
Args:
video: Iterable of images.
shape: 2D spatial dimensions (height, width) of output video.
Returns:
A resampled video whose spatial dimensions match `shape`.
"""
_check_2d_shape(shape)
return np.array([resize_image(image, shape) for image in video])
# ** General I/O.
def _is_url(path_or_url: _Path) -> bool:
return isinstance(path_or_url, str) and path_or_url.startswith(
('http://', 'https://', 'file://')
)
def read_contents(path_or_url: _Path) -> bytes:
"""Returns the contents of the file specified by either a path or URL."""
data: bytes
if _is_url(path_or_url):
assert isinstance(path_or_url, str)
headers = {'User-Agent': 'Chrome'}
request = urllib.request.Request(path_or_url, headers=headers)
with urllib.request.urlopen(request) as response:
data = response.read()
else:
with _open(path_or_url, 'rb') as f:
data = f.read()
return data
@contextlib.contextmanager
def _read_via_local_file(path_or_url: _Path) -> Iterator[str]:
"""Context to copy a remote file locally to read from it.
Args:
path_or_url: File, which may be remote.
Yields:
The name of a local file which may be a copy of a remote file.
"""
if _is_url(path_or_url) or not _path_is_local(path_or_url):
suffix = pathlib.Path(path_or_url).suffix
with tempfile.TemporaryDirectory() as directory_name:
tmp_path = pathlib.Path(directory_name) / f'file{suffix}'
tmp_path.write_bytes(read_contents(path_or_url))
yield str(tmp_path)
else:
yield str(path_or_url)
@contextlib.contextmanager
def _write_via_local_file(path: _Path) -> Iterator[str]:
"""Context to write a temporary local file and subsequently copy it remotely.
Args:
path: File, which may be remote.
Yields:
The name of a local file which may be subsequently copied remotely.
"""
if _path_is_local(path):
yield str(path)
else:
suffix = pathlib.Path(path).suffix
with tempfile.TemporaryDirectory() as directory_name:
tmp_path = pathlib.Path(directory_name) / f'file{suffix}'
yield str(tmp_path)
with _open(path, mode='wb') as f:
f.write(tmp_path.read_bytes())
class set_show_save_dir: # pylint: disable=invalid-name
"""Save all titled output from `show_*()` calls into files.
If the specified `directory` is not None, all titled images and videos
displayed by `show_image`, `show_images`, `show_video`, and `show_videos` are
also saved as files within the directory.
It can be used either to set the state or as a context manager:
>>> set_show_save_dir('/tmp')
>>> show_image(color_ramp(), title='image1') # Creates /tmp/image1.png.
>>> show_video(moving_circle(), title='video2') # Creates /tmp/video2.mp4.
>>> set_show_save_dir(None)
>>> with set_show_save_dir('/tmp'):
... show_image(color_ramp(), title='image1') # Creates /tmp/image1.png.
... show_video(moving_circle(), title='video2') # Creates /tmp/video2.mp4.
"""
def __init__(self, directory: _Path | None):
self._old_show_save_dir = _config.show_save_dir
_config.show_save_dir = directory
def __enter__(self) -> None:
pass
def __exit__(self, *_: Any) -> None:
_config.show_save_dir = self._old_show_save_dir
# ** Image I/O.
def read_image(
path_or_url: _Path,
*,
apply_exif_transpose: bool = True,
dtype: _DTypeLike = None,
) -> _NDArray:
"""Returns an image read from a file path or URL.
Decoding is performed using `PIL`, which supports `uint8` images with 1, 3,
or 4 channels and `uint16` images with a single channel.
Args:
path_or_url: Path of input file.
apply_exif_transpose: If True, rotate image according to EXIF orientation.
dtype: Data type of the returned array. If None, `np.uint8` or `np.uint16`
is inferred automatically.
"""
data = read_contents(path_or_url)
return decompress_image(data, dtype, apply_exif_transpose)
def write_image(
path: _Path, image: _ArrayLike, fmt: str = 'png', **kwargs: Any
) -> None:
"""Writes an image to a file.
Encoding is performed using `PIL`, which supports `uint8` images with 1, 3,
or 4 channels and `uint16` images with a single channel.
File format is explicitly provided by `fmt` and not inferred by `path`.
Args:
path: Path of output file.
image: Array-like object. If its type is float, it is converted to np.uint8
using `to_uint8` (thus clamping to the input to the range [0.0, 1.0]).
Otherwise it must be np.uint8 or np.uint16.
fmt: Desired compression encoding, e.g. 'png'.
**kwargs: Additional parameters for `PIL.Image.save()`.
"""
image = _as_valid_media_array(image)
if np.issubdtype(image.dtype, np.floating):
image = to_uint8(image)
with _open(path, 'wb') as f:
_pil_image(image).save(f, format=fmt, **kwargs)
def to_rgb(
array: _ArrayLike,
*,
vmin: float | None = None,
vmax: float | None = None,
cmap: str | Callable[[_ArrayLike], _NDArray] = 'gray',
) -> _NDArray:
"""Maps scalar values to RGB using value bounds and a color map.
Args:
array: Scalar values, with arbitrary shape.
vmin: Explicit min value for remapping; if None, it is obtained as the
minimum finite value of `array`.
vmax: Explicit max value for remapping; if None, it is obtained as the
maximum finite value of `array`.
cmap: A `pyplot` color map or callable, to map from 1D value to 3D or 4D
color.
Returns:
A new array in which each element is affinely mapped from [vmin, vmax]
to [0.0, 1.0] and then color-mapped.
"""
a = _as_valid_media_array(array)
del array
# For future numpy version 1.7.0:
# vmin = np.amin(a, where=np.isfinite(a)) if vmin is None else vmin
# vmax = np.amax(a, where=np.isfinite(a)) if vmax is None else vmax
vmin = np.amin(np.where(np.isfinite(a), a, np.inf)) if vmin is None else vmin
vmax = np.amax(np.where(np.isfinite(a), a, -np.inf)) if vmax is None else vmax
a = (a.astype('float') - vmin) / (vmax - vmin + np.finfo(float).eps)
if isinstance(cmap, str):
if hasattr(matplotlib, 'colormaps'):
rgb_from_scalar: Any = matplotlib.colormaps[cmap] # Newer version.
else:
rgb_from_scalar = matplotlib.pyplot.cm.get_cmap(cmap) # pylint: disable=no-member
else:
rgb_from_scalar = cmap
a = typing.cast(_NDArray, rgb_from_scalar(a))
# If there is a fully opaque alpha channel, remove it.
if a.shape[-1] == 4 and np.all(to_float01(a[..., 3])) == 1.0:
a = a[..., :3]
return a
def compress_image(
image: _ArrayLike, *, fmt: str = 'png', **kwargs: Any
) -> bytes:
"""Returns a buffer containing a compressed image.
Args:
image: Array in a format supported by `PIL`, e.g. np.uint8 or np.uint16.
fmt: Desired compression encoding, e.g. 'png'.
**kwargs: Options for `PIL.save()`, e.g. `optimize=True` for greater
compression.
"""
image = _as_valid_media_array(image)
with io.BytesIO() as output:
_pil_image(image).save(output, format=fmt, **kwargs)
return output.getvalue()
def decompress_image(
data: bytes, dtype: _DTypeLike = None, apply_exif_transpose: bool = True
) -> _NDArray:
"""Returns an image from a compressed data buffer.
Decoding is performed using `PIL`, which supports `uint8` images with 1, 3,
or 4 channels and `uint16` images with a single channel.
Args:
data: Buffer containing compressed image.
dtype: Data type of the returned array. If None, `np.uint8` or `np.uint16`
is inferred automatically.
apply_exif_transpose: If True, rotate image according to EXIF orientation.
"""
pil_image: PIL.Image.Image = PIL.Image.open(io.BytesIO(data))
if apply_exif_transpose:
tmp_image = PIL.ImageOps.exif_transpose(pil_image) # Future: in_place=True.
assert tmp_image
pil_image = tmp_image
if dtype is None:
dtype = np.uint16 if pil_image.mode.startswith('I') else np.uint8
return np.array(pil_image, dtype=dtype)
def html_from_compressed_image(
data: bytes,
width: int,
height: int,
*,
title: str | None = None,
border: bool | str = False,
pixelated: bool = True,
fmt: str = 'png',
) -> str:
"""Returns an HTML string with an image tag containing encoded data.
Args:
data: Compressed image bytes.
width: Width of HTML image in pixels.
height: Height of HTML image in pixels.
title: Optional text shown centered above image.
border: If `bool`, whether to place a black boundary around the image, or if
`str`, the boundary CSS style.
pixelated: If True, sets the CSS style to 'image-rendering: pixelated;'.
fmt: Compression encoding.
"""
b64 = base64.b64encode(data).decode('utf-8')
if isinstance(border, str):
border = f'{border}; '
elif border:
border = 'border:1px solid black; '
else:
border = ''
s_pixelated = 'pixelated' if pixelated else 'auto'
s = (
f'<img width="{width}" height="{height}"'
f' style="{border}image-rendering:{s_pixelated}; object-fit:cover;"'
f' src="data:image/{fmt};base64,{b64}"/>'
)
if title is not None:
s = f"""<div style="display:flex; align-items:left;">
<div style="display:flex; flex-direction:column; align-items:center;">
<div>{title}</div><div>{s}</div></div></div>"""
return s
def _get_width_height(
width: int | None, height: int | None, shape: tuple[int, int]
) -> tuple[int, int]:
"""Returns (width, height) given optional parameters and image shape."""
assert len(shape) == 2, shape
if width and height:
return width, height
if width and not height:
return width, int(width * (shape[0] / shape[1]) + 0.5)
if height and not width:
return int(height * (shape[1] / shape[0]) + 0.5), height
return shape[::-1]
def _ensure_mapped_to_rgb(
image: _ArrayLike,
*,
vmin: float | None = None,
vmax: float | None = None,
cmap: str | Callable[[_ArrayLike], _NDArray] = 'gray',
) -> _NDArray:
"""Ensure image is mapped to RGB."""
image = _as_valid_media_array(image)
if not (image.ndim == 2 or (image.ndim == 3 and image.shape[2] in (1, 3, 4))):
raise ValueError(
f'Image with shape {image.shape} is neither a 2D array'
' nor a 3D array with 1, 3, or 4 channels.'
)
if image.ndim == 3 and image.shape[2] == 1:
image = image[:, :, 0]
if image.ndim == 2:
image = to_rgb(image, vmin=vmin, vmax=vmax, cmap=cmap)
return image
def show_image(
image: _ArrayLike, *, title: str | None = None, **kwargs: Any
) -> str | None:
"""Displays an image in the notebook and optionally saves it to a file.
See `show_images`.
>>> show_image(np.random.rand(100, 100))
>>> show_image(np.random.randint(0, 256, size=(80, 80, 3), dtype='uint8'))
>>> show_image(np.random.rand(10, 10) - 0.5, cmap='bwr', height=100)
>>> show_image(read_image('/tmp/image.png'))
>>> url = 'https://github.com/hhoppe/data/raw/main/image.png'
>>> show_image(read_image(url))
Args:
image: 2D array-like, or 3D array-like with 1, 3, or 4 channels.
title: Optional text shown centered above the image.
**kwargs: See `show_images`.
Returns:
html string if `return_html` is `True`.
"""
return show_images([np.asarray(image)], [title], **kwargs)