libstb 0.4.0__tar.gz → 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. {libstb-0.4.0 → libstb-0.5.0}/PKG-INFO +32 -6
  2. {libstb-0.4.0 → libstb-0.5.0}/README.md +31 -5
  3. libstb-0.5.0/examples/cpp/.gitignore +8 -0
  4. libstb-0.5.0/examples/notebooks/.gitignore +5 -0
  5. libstb-0.5.0/examples/notebooks/01_getting_started.ipynb +210 -0
  6. libstb-0.5.0/examples/notebooks/02_resize_filters.ipynb +144 -0
  7. libstb-0.5.0/examples/notebooks/03_font_rendering.ipynb +127 -0
  8. libstb-0.5.0/examples/notebooks/requirements.txt +4 -0
  9. libstb-0.5.0/examples/python/.gitignore +4 -0
  10. libstb-0.5.0/examples/python/01_open_and_inspect.py +51 -0
  11. libstb-0.5.0/examples/python/02_encode_formats.py +47 -0
  12. libstb-0.5.0/examples/python/03_resize_filters.py +48 -0
  13. libstb-0.5.0/examples/python/04_numpy_interop.py +49 -0
  14. libstb-0.5.0/examples/python/05_font_render.py +55 -0
  15. libstb-0.5.0/examples/python/06_imread_imwrite.py +37 -0
  16. libstb-0.5.0/examples/python/07_dlpack.py +76 -0
  17. libstb-0.5.0/examples/python/requirements.txt +3 -0
  18. {libstb-0.4.0 → libstb-0.5.0}/include/stb.h +1 -1
  19. {libstb-0.4.0 → libstb-0.5.0}/src/bindings/python/bind_image.cpp +47 -6
  20. libstb-0.5.0/src/bindings/python/libstb/__init__.py +100 -0
  21. libstb-0.5.0/tests/python/test_dlpack.py +176 -0
  22. {libstb-0.4.0 → libstb-0.5.0}/tests/python/test_encode.py +10 -10
  23. {libstb-0.4.0 → libstb-0.5.0}/tests/python/test_errors.py +2 -2
  24. {libstb-0.4.0 → libstb-0.5.0}/tests/python/test_font.py +6 -6
  25. libstb-0.5.0/tests/python/test_functional.py +101 -0
  26. {libstb-0.4.0 → libstb-0.5.0}/tests/python/test_image.py +22 -22
  27. {libstb-0.4.0 → libstb-0.5.0}/tests/python/test_lossless_exact.py +9 -9
  28. {libstb-0.4.0 → libstb-0.5.0}/tests/python/test_lossy_tolerance.py +2 -2
  29. {libstb-0.4.0 → libstb-0.5.0}/tests/python/test_no_numpy.py +16 -4
  30. {libstb-0.4.0 → libstb-0.5.0}/tests/python/test_oop.py +32 -32
  31. {libstb-0.4.0 → libstb-0.5.0}/tests/python/test_pillow_parity.py +20 -20
  32. {libstb-0.4.0 → libstb-0.5.0}/tests/python/test_resizer.py +18 -18
  33. libstb-0.4.0/src/bindings/python/libstb/__init__.py +0 -62
  34. {libstb-0.4.0 → libstb-0.5.0}/.github/workflows/cmake.yml +0 -0
  35. {libstb-0.4.0 → libstb-0.5.0}/.github/workflows/orchestrator.yml +0 -0
  36. {libstb-0.4.0 → libstb-0.5.0}/.github/workflows/release_template.md +0 -0
  37. {libstb-0.4.0 → libstb-0.5.0}/.github/workflows/wheels.yml +0 -0
  38. {libstb-0.4.0 → libstb-0.5.0}/.gitignore +0 -0
  39. {libstb-0.4.0 → libstb-0.5.0}/CMakeLists.txt +0 -0
  40. {libstb-0.4.0 → libstb-0.5.0}/LICENSE.txt +0 -0
  41. {libstb-0.4.0 → libstb-0.5.0}/benchmarks/CMakeLists.txt +0 -0
  42. {libstb-0.4.0 → libstb-0.5.0}/benchmarks/README.md +0 -0
  43. {libstb-0.4.0 → libstb-0.5.0}/benchmarks/cmake/Download.cmake +0 -0
  44. {libstb-0.4.0 → libstb-0.5.0}/benchmarks/cmake/FetchRealCorpus.cmake +0 -0
  45. {libstb-0.4.0 → libstb-0.5.0}/benchmarks/corpus/.gitignore +0 -0
  46. {libstb-0.4.0 → libstb-0.5.0}/benchmarks/python/CMakeLists.txt +0 -0
  47. {libstb-0.4.0 → libstb-0.5.0}/benchmarks/python/bench_fonts.py +0 -0
  48. {libstb-0.4.0 → libstb-0.5.0}/benchmarks/python/bench_op_memory_driver.py +0 -0
  49. {libstb-0.4.0 → libstb-0.5.0}/benchmarks/python/bench_op_memory_one.py +0 -0
  50. {libstb-0.4.0 → libstb-0.5.0}/benchmarks/python/bench_scaling.py +0 -0
  51. {libstb-0.4.0 → libstb-0.5.0}/benchmarks/python/bench_sizes.py +0 -0
  52. {libstb-0.4.0 → libstb-0.5.0}/benchmarks/python/bench_throughput.py +0 -0
  53. {libstb-0.4.0 → libstb-0.5.0}/benchmarks/python/corpus.py +0 -0
  54. {libstb-0.4.0 → libstb-0.5.0}/benchmarks/python/real_corpus_manifest.py +0 -0
  55. {libstb-0.4.0 → libstb-0.5.0}/benchmarks/python/requirements.txt +0 -0
  56. {libstb-0.4.0 → libstb-0.5.0}/benchmarks/python/runners.py +0 -0
  57. {libstb-0.4.0 → libstb-0.5.0}/benchmarks/python/system_info.py +0 -0
  58. {libstb-0.4.0 → libstb-0.5.0}/benchmarks/python/verify.py +0 -0
  59. {libstb-0.4.0 → libstb-0.5.0}/benchmarks/report/CMakeLists.txt +0 -0
  60. {libstb-0.4.0 → libstb-0.5.0}/benchmarks/report/generate_report.py +0 -0
  61. {libstb-0.4.0 → libstb-0.5.0}/benchmarks/report/template.html.jinja2 +0 -0
  62. {libstb-0.4.0 → libstb-0.5.0}/cmake/DynamicVersion.cmake +0 -0
  63. {libstb-0.4.0 → libstb-0.5.0}/cmake/Optimize.cmake +0 -0
  64. {libstb-0.4.0 → libstb-0.5.0}/cmake/Startup.cmake +0 -0
  65. {libstb-0.4.0 → libstb-0.5.0}/cmake/libstbConfig.cmake.in +0 -0
  66. {libstb-0.4.0 → libstb-0.5.0}/include/stb/error.hpp +0 -0
  67. {libstb-0.4.0 → libstb-0.5.0}/include/stb/font.hpp +0 -0
  68. {libstb-0.4.0 → libstb-0.5.0}/include/stb/image.hpp +0 -0
  69. {libstb-0.4.0 → libstb-0.5.0}/include/stb/resizer.hpp +0 -0
  70. {libstb-0.4.0 → libstb-0.5.0}/include/stb/utf8.hpp +0 -0
  71. {libstb-0.4.0 → libstb-0.5.0}/pyproject.toml +0 -0
  72. {libstb-0.4.0 → libstb-0.5.0}/requirements-dev.txt +0 -0
  73. {libstb-0.4.0 → libstb-0.5.0}/src/bindings/python/CMakeLists.txt +0 -0
  74. {libstb-0.4.0 → libstb-0.5.0}/src/bindings/python/bind_font.cpp +0 -0
  75. {libstb-0.4.0 → libstb-0.5.0}/src/bindings/python/bind_resizer.cpp +0 -0
  76. {libstb-0.4.0 → libstb-0.5.0}/src/bindings/python/binding.cpp +0 -0
  77. {libstb-0.4.0 → libstb-0.5.0}/src/bindings/python/binding.hpp +0 -0
  78. {libstb-0.4.0 → libstb-0.5.0}/src/bindings/python/libstb/font.py +0 -0
  79. {libstb-0.4.0 → libstb-0.5.0}/src/bindings/python/libstb/image.py +0 -0
  80. {libstb-0.4.0 → libstb-0.5.0}/src/core/file.hpp +0 -0
  81. {libstb-0.4.0 → libstb-0.5.0}/src/core/font.cpp +0 -0
  82. {libstb-0.4.0 → libstb-0.5.0}/src/core/image.cpp +0 -0
  83. {libstb-0.4.0 → libstb-0.5.0}/src/core/resizer.cpp +0 -0
  84. {libstb-0.4.0 → libstb-0.5.0}/src/core/utf8.cpp +0 -0
  85. {libstb-0.4.0 → libstb-0.5.0}/src/third_party/README.md +0 -0
  86. {libstb-0.4.0 → libstb-0.5.0}/src/third_party/stb/stb_image.h +0 -0
  87. {libstb-0.4.0 → libstb-0.5.0}/src/third_party/stb/stb_image_resize2.h +0 -0
  88. {libstb-0.4.0 → libstb-0.5.0}/src/third_party/stb/stb_image_write.h +0 -0
  89. {libstb-0.4.0 → libstb-0.5.0}/src/third_party/stb/stb_rect_pack.h +0 -0
  90. {libstb-0.4.0 → libstb-0.5.0}/src/third_party/stb/stb_truetype.h +0 -0
  91. {libstb-0.4.0 → libstb-0.5.0}/tests/CMakeLists.txt +0 -0
  92. {libstb-0.4.0 → libstb-0.5.0}/tests/cmake/CMakeLists.txt +0 -0
  93. {libstb-0.4.0 → libstb-0.5.0}/tests/cmake/consumer_project/CMakeLists.txt +0 -0
  94. {libstb-0.4.0 → libstb-0.5.0}/tests/cmake/consumer_project/main.cpp +0 -0
  95. {libstb-0.4.0 → libstb-0.5.0}/tests/cmake/run_consumer_test.cmake +0 -0
  96. {libstb-0.4.0 → libstb-0.5.0}/tests/cpp/CMakeLists.txt +0 -0
  97. {libstb-0.4.0 → libstb-0.5.0}/tests/cpp/test_common.hpp +0 -0
  98. {libstb-0.4.0 → libstb-0.5.0}/tests/cpp/test_encode.cpp +0 -0
  99. {libstb-0.4.0 → libstb-0.5.0}/tests/cpp/test_font.cpp +0 -0
  100. {libstb-0.4.0 → libstb-0.5.0}/tests/cpp/test_image.cpp +0 -0
  101. {libstb-0.4.0 → libstb-0.5.0}/tests/cpp/test_resizer.cpp +0 -0
  102. {libstb-0.4.0 → libstb-0.5.0}/tests/cpp/test_utf8.cpp +0 -0
  103. {libstb-0.4.0 → libstb-0.5.0}/tests/data/libstb-test.ttf +0 -0
  104. {libstb-0.4.0 → libstb-0.5.0}/tests/data/make_test_font.py +0 -0
  105. {libstb-0.4.0 → libstb-0.5.0}/tests/python/CMakeLists.txt +0 -0
  106. {libstb-0.4.0 → libstb-0.5.0}/tests/python/tolerances.py +0 -0
  107. {libstb-0.4.0 → libstb-0.5.0}/tests/tools/jpeg_vs_upstream.py +0 -0
  108. {libstb-0.4.0 → libstb-0.5.0}/tests/tools/zlib_fuzz.py +0 -0
  109. {libstb-0.4.0 → libstb-0.5.0}/tests/utest/utest.h +0 -0
  110. {libstb-0.4.0 → libstb-0.5.0}/tests/utest/utest_main.cxx +0 -0
  111. {libstb-0.4.0 → libstb-0.5.0}/version.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: libstb
3
- Version: 0.4.0
3
+ Version: 0.5.0
4
4
  Summary: Python bindings for the stb single-header libraries (image io, resize, fonts). Zero system dependencies.
5
5
  Author-Email: Mohammad Raziei <mohammadraziei1375@gmail.com>
6
6
  License: MIT
@@ -33,8 +33,8 @@ libraries. `pip install libstb` and you have image/font processing with **no
33
33
  system dependencies and no Python dependencies**. The C++ library is usable from
34
34
  CMake too.
35
35
 
36
- numpy is optional: `pip install "libstb[numpy]"` if you want `img.array` /
37
- `img.numpy()` / `libstb.load()`. It is imported only when one of those is first
36
+ numpy is optional: `pip install "libstb[numpy]"` if you want `img.numpy()` /
37
+ `libstb.imread()`. It is imported only when one of those is first
38
38
  used, never by `import libstb`, and without it they raise an `ImportError` that
39
39
  says so. Everything else works without numpy, including `Image(array)` from any
40
40
  buffer (a `memoryview`, `array.array`, a `bytearray`, a PIL-exported buffer...),
@@ -57,6 +57,10 @@ import libstb
57
57
  img = libstb.Image.open("photo.png") # or bytes; also: channels=4, flip=True
58
58
  img.width, img.height, img.channels # 640, 480, 3
59
59
  img.numpy() # uint8 pixels (H, W, C), no copy; np.asarray(img) works too
60
+ np.from_dlpack(img) # DLPack: also torch/jax/cupy.from_dlpack(img), zero-copy
61
+ libstb.Image.from_dlpack(tensor) # and back: a torch/jax/cupy/numpy uint8 array -> Image
62
+ pixels = libstb.imread("photo.png") # just the ndarray (same options as Image.open)
63
+ libstb.imwrite("out.jpg", pixels, quality=80) # an ndarray or an Image; format from the extension
60
64
  libstb.ImageInfo.read("photo.png") # header only: (width, height, channels)
61
65
  libstb.Image(np.zeros((8, 8, 4), np.uint8)) # from your own uint8 array (no copy, see below)
62
66
  img.copy() # an independent image (deep copy)
@@ -78,8 +82,7 @@ font.metrics(32), font.advance("A", 32), font.kerning("A", "V", 32), font.measur
78
82
  font.render_glyph("A", 32) # Glyph(bitmap, x_offset, y_offset, advance)
79
83
  atlas = font.make_atlas("ABCabc123", 32, 256, 256) # Atlas: .image and atlas["A"] -> AtlasGlyph
80
84
 
81
- libstb.load("photo.png") # shortcut: Image.open(...).array
82
- libstb.info("photo.png") # shortcut: ImageInfo.read(...)
85
+ libstb.iminfo("photo.png") # shortcut: ImageInfo.read(...)
83
86
  ```
84
87
 
85
88
  **Encoding.** Every format has a pair of methods with its own settings, all
@@ -91,6 +94,13 @@ truncated file). `write(path)` is the shortcut: it picks the format from the
91
94
  extension (`.png .jpg .jpeg .bmp .tga`, case-insensitive; `ValueError` for
92
95
  anything else) and uses the defaults. For other settings call `write_*`.
93
96
 
97
+ `libstb.imwrite(path, image, *, quality=None, compression=None, rle=None)` is
98
+ the functional form: it takes an `Image` or a uint8 array, picks the format
99
+ from the extension, and passes the options that format has (`quality` for jpg,
100
+ `compression` for png, `rle` for tga). An option the format does not have is a
101
+ `ValueError`, not silently ignored. `libstb.imread(source, *, channels, flip,
102
+ max_bytes)` is its counterpart and returns an ndarray.
103
+
94
104
  **Resize filters by name.** `Image.resize(w, h, x)` and `Resizer(x)` accept a
95
105
  `Resizer.Filter`, or a case-insensitive name (`-` and space count as `_`). Any
96
106
  other option (`edge`, `srgb`, `max_bytes`) is a keyword of `Resizer(...)`.
@@ -123,11 +133,27 @@ exceed `max_bytes` (default 512 MiB) are rejected from the header, before any
123
133
  pixel memory is allocated.
124
134
 
125
135
  `libstb.Image` is `stb::image` itself, not a wrapper: `open`, `resize`, `to_*` and
126
- `write*` are the C++ members, run without the GIL. `img.array` / `np.asarray(img)`
136
+ `write*` are the C++ members, run without the GIL. `img.numpy()` / `np.asarray(img)`
127
137
  are numpy views of its pixels (kept alive by the view); `memoryview(img)` is the
128
138
  same zero-copy view as a plain 3-D `memoryview` (numpy reads it too), and
129
139
  `img.tobytes()` is a copy, both without numpy.
130
140
 
141
+ **DLPack.** `Image` implements `__dlpack__` / `__dlpack_device__`, so
142
+ `np.from_dlpack(img)`, `torch.from_dlpack(img)`, `jax.numpy.from_dlpack(img)`
143
+ and `cupy.from_dlpack(img)` share the pixels with no copy and no framework
144
+ import on libstb's side. The layout is fixed: `uint8`, shape `(height, width,
145
+ channels)`, on the CPU (`dl_device` other than the CPU is a `BufferError`).
146
+ The view keeps the image alive. It is writable with numpy 2.1 or newer (older
147
+ numpy, the last one on Python 3.9 being 2.0.2, imports every DLPack view
148
+ read-only and has no `copy=` argument; `img.numpy()` is always writable).
149
+ Asking for `copy=True` gives an independent copy. The other way round, `libstb.Image.from_dlpack(x)` takes any
150
+ DLPack object holding `uint8` pixels of shape `(H, W)` or `(H, W, 1..4)` (a
151
+ torch, jax, cupy or numpy array, another `Image`): a writable C-contiguous CPU
152
+ array is shared, anything else is copied, and `copy=True` always copies.
153
+ (`Image(x)` accepts the same objects; `from_dlpack` additionally insists on
154
+ `__dlpack__`, so a stray `bytes` is a clear `TypeError`.) For a different layout or dtype (CHW, float32), convert on
155
+ the framework side, e.g. `torch.from_dlpack(img).permute(2, 0, 1).float() / 255`.
156
+
131
157
  Pixels are never copied behind your back. `Image(array)` uses a writable,
132
158
  C-contiguous uint8 array in place, so the image and the array share their
133
159
  pixels (changes show on both sides, and the image keeps the array alive). Any
@@ -5,8 +5,8 @@ libraries. `pip install libstb` and you have image/font processing with **no
5
5
  system dependencies and no Python dependencies**. The C++ library is usable from
6
6
  CMake too.
7
7
 
8
- numpy is optional: `pip install "libstb[numpy]"` if you want `img.array` /
9
- `img.numpy()` / `libstb.load()`. It is imported only when one of those is first
8
+ numpy is optional: `pip install "libstb[numpy]"` if you want `img.numpy()` /
9
+ `libstb.imread()`. It is imported only when one of those is first
10
10
  used, never by `import libstb`, and without it they raise an `ImportError` that
11
11
  says so. Everything else works without numpy, including `Image(array)` from any
12
12
  buffer (a `memoryview`, `array.array`, a `bytearray`, a PIL-exported buffer...),
@@ -29,6 +29,10 @@ import libstb
29
29
  img = libstb.Image.open("photo.png") # or bytes; also: channels=4, flip=True
30
30
  img.width, img.height, img.channels # 640, 480, 3
31
31
  img.numpy() # uint8 pixels (H, W, C), no copy; np.asarray(img) works too
32
+ np.from_dlpack(img) # DLPack: also torch/jax/cupy.from_dlpack(img), zero-copy
33
+ libstb.Image.from_dlpack(tensor) # and back: a torch/jax/cupy/numpy uint8 array -> Image
34
+ pixels = libstb.imread("photo.png") # just the ndarray (same options as Image.open)
35
+ libstb.imwrite("out.jpg", pixels, quality=80) # an ndarray or an Image; format from the extension
32
36
  libstb.ImageInfo.read("photo.png") # header only: (width, height, channels)
33
37
  libstb.Image(np.zeros((8, 8, 4), np.uint8)) # from your own uint8 array (no copy, see below)
34
38
  img.copy() # an independent image (deep copy)
@@ -50,8 +54,7 @@ font.metrics(32), font.advance("A", 32), font.kerning("A", "V", 32), font.measur
50
54
  font.render_glyph("A", 32) # Glyph(bitmap, x_offset, y_offset, advance)
51
55
  atlas = font.make_atlas("ABCabc123", 32, 256, 256) # Atlas: .image and atlas["A"] -> AtlasGlyph
52
56
 
53
- libstb.load("photo.png") # shortcut: Image.open(...).array
54
- libstb.info("photo.png") # shortcut: ImageInfo.read(...)
57
+ libstb.iminfo("photo.png") # shortcut: ImageInfo.read(...)
55
58
  ```
56
59
 
57
60
  **Encoding.** Every format has a pair of methods with its own settings, all
@@ -63,6 +66,13 @@ truncated file). `write(path)` is the shortcut: it picks the format from the
63
66
  extension (`.png .jpg .jpeg .bmp .tga`, case-insensitive; `ValueError` for
64
67
  anything else) and uses the defaults. For other settings call `write_*`.
65
68
 
69
+ `libstb.imwrite(path, image, *, quality=None, compression=None, rle=None)` is
70
+ the functional form: it takes an `Image` or a uint8 array, picks the format
71
+ from the extension, and passes the options that format has (`quality` for jpg,
72
+ `compression` for png, `rle` for tga). An option the format does not have is a
73
+ `ValueError`, not silently ignored. `libstb.imread(source, *, channels, flip,
74
+ max_bytes)` is its counterpart and returns an ndarray.
75
+
66
76
  **Resize filters by name.** `Image.resize(w, h, x)` and `Resizer(x)` accept a
67
77
  `Resizer.Filter`, or a case-insensitive name (`-` and space count as `_`). Any
68
78
  other option (`edge`, `srgb`, `max_bytes`) is a keyword of `Resizer(...)`.
@@ -95,11 +105,27 @@ exceed `max_bytes` (default 512 MiB) are rejected from the header, before any
95
105
  pixel memory is allocated.
96
106
 
97
107
  `libstb.Image` is `stb::image` itself, not a wrapper: `open`, `resize`, `to_*` and
98
- `write*` are the C++ members, run without the GIL. `img.array` / `np.asarray(img)`
108
+ `write*` are the C++ members, run without the GIL. `img.numpy()` / `np.asarray(img)`
99
109
  are numpy views of its pixels (kept alive by the view); `memoryview(img)` is the
100
110
  same zero-copy view as a plain 3-D `memoryview` (numpy reads it too), and
101
111
  `img.tobytes()` is a copy, both without numpy.
102
112
 
113
+ **DLPack.** `Image` implements `__dlpack__` / `__dlpack_device__`, so
114
+ `np.from_dlpack(img)`, `torch.from_dlpack(img)`, `jax.numpy.from_dlpack(img)`
115
+ and `cupy.from_dlpack(img)` share the pixels with no copy and no framework
116
+ import on libstb's side. The layout is fixed: `uint8`, shape `(height, width,
117
+ channels)`, on the CPU (`dl_device` other than the CPU is a `BufferError`).
118
+ The view keeps the image alive. It is writable with numpy 2.1 or newer (older
119
+ numpy, the last one on Python 3.9 being 2.0.2, imports every DLPack view
120
+ read-only and has no `copy=` argument; `img.numpy()` is always writable).
121
+ Asking for `copy=True` gives an independent copy. The other way round, `libstb.Image.from_dlpack(x)` takes any
122
+ DLPack object holding `uint8` pixels of shape `(H, W)` or `(H, W, 1..4)` (a
123
+ torch, jax, cupy or numpy array, another `Image`): a writable C-contiguous CPU
124
+ array is shared, anything else is copied, and `copy=True` always copies.
125
+ (`Image(x)` accepts the same objects; `from_dlpack` additionally insists on
126
+ `__dlpack__`, so a stray `bytes` is a clear `TypeError`.) For a different layout or dtype (CHW, float32), convert on
127
+ the framework side, e.g. `torch.from_dlpack(img).permute(2, 0, 1).float() / 255`.
128
+
103
129
  Pixels are never copied behind your back. `Image(array)` uses a writable,
104
130
  C-contiguous uint8 array in place, so the image and the array share their
105
131
  pixels (changes show on both sides, and the image keeps the array alive). Any
@@ -0,0 +1,8 @@
1
+ build/
2
+ cmake-build-*/
3
+ out/
4
+ output/
5
+ CMakeCache.txt
6
+ CMakeFiles/
7
+ compile_commands.json
8
+ .cache/
@@ -0,0 +1,5 @@
1
+ .ipynb_checkpoints/
2
+ __pycache__/
3
+ *.pyc
4
+ .venv/
5
+ output/
@@ -0,0 +1,210 @@
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "d5505ae5",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Getting started with libstb\n",
9
+ "\n",
10
+ "Install the requirements first: `pip install -r requirements.txt`."
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "code",
15
+ "execution_count": null,
16
+ "id": "eb3cf8df",
17
+ "metadata": {},
18
+ "outputs": [],
19
+ "source": [
20
+ "import numpy as np\n",
21
+ "import matplotlib.pyplot as plt\n",
22
+ "import libstb\n",
23
+ "\n",
24
+ "libstb.__file__"
25
+ ]
26
+ },
27
+ {
28
+ "cell_type": "markdown",
29
+ "id": "27884807",
30
+ "metadata": {},
31
+ "source": [
32
+ "## Make an image\n",
33
+ "\n",
34
+ "`libstb.Image(array)` wraps a writable, C-contiguous `uint8` array without copying it."
35
+ ]
36
+ },
37
+ {
38
+ "cell_type": "code",
39
+ "execution_count": null,
40
+ "id": "7a2400cc",
41
+ "metadata": {},
42
+ "outputs": [],
43
+ "source": [
44
+ "y, x = np.mgrid[0:200, 0:320]\n",
45
+ "r = (x * 255 // 319).astype(np.uint8)\n",
46
+ "g = (y * 255 // 199).astype(np.uint8)\n",
47
+ "b = np.full_like(r, 128)\n",
48
+ "img = libstb.Image(np.dstack([r, g, b]))\n",
49
+ "img.width, img.height, img.channels"
50
+ ]
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "execution_count": null,
55
+ "id": "421600d9",
56
+ "metadata": {},
57
+ "outputs": [],
58
+ "source": [
59
+ "plt.imshow(img.numpy())\n",
60
+ "plt.axis('off');"
61
+ ]
62
+ },
63
+ {
64
+ "cell_type": "markdown",
65
+ "id": "5a6e8385",
66
+ "metadata": {},
67
+ "source": [
68
+ "## Encode in memory\n",
69
+ "\n",
70
+ "`to_png`, `to_jpg`, `to_bmp` and `to_tga` return the file's bytes. Each has its own settings."
71
+ ]
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "execution_count": null,
76
+ "id": "2c5926a4",
77
+ "metadata": {},
78
+ "outputs": [],
79
+ "source": [
80
+ "sizes = {\n",
81
+ " \"png (compression=9)\": len(img.to_png(compression=9)),\n",
82
+ " \"jpg (quality=20)\": len(img.to_jpg(quality=20)),\n",
83
+ " \"jpg (quality=90)\": len(img.to_jpg(quality=90)),\n",
84
+ " \"bmp\": len(img.to_bmp()),\n",
85
+ "}\n",
86
+ "for name, n in sizes.items():\n",
87
+ " print(f\"{name:22s} {n:>8,} bytes\")"
88
+ ]
89
+ },
90
+ {
91
+ "cell_type": "markdown",
92
+ "id": "89331ae7",
93
+ "metadata": {},
94
+ "source": [
95
+ "## Decode again\n",
96
+ "\n",
97
+ "`Image.open` takes a path or bytes. `ImageInfo.read` reads only the header."
98
+ ]
99
+ },
100
+ {
101
+ "cell_type": "code",
102
+ "execution_count": null,
103
+ "id": "dd9c7552",
104
+ "metadata": {},
105
+ "outputs": [],
106
+ "source": [
107
+ "data = img.to_png()\n",
108
+ "print(libstb.ImageInfo.read(data))\n",
109
+ "back = libstb.Image.open(data)\n",
110
+ "print(\"lossless round trip:\", np.array_equal(back.numpy(), img.numpy()))\n",
111
+ "\n",
112
+ "jpg = libstb.Image.open(img.to_jpg(quality=20))\n",
113
+ "fig, axes = plt.subplots(1, 2, figsize=(8, 3))\n",
114
+ "axes[0].imshow(back.numpy()); axes[0].set_title(\"PNG (exact)\")\n",
115
+ "axes[1].imshow(jpg.numpy()); axes[1].set_title(\"JPEG quality 20\")\n",
116
+ "for a in axes: a.axis(\"off\")"
117
+ ]
118
+ },
119
+ {
120
+ "cell_type": "markdown",
121
+ "id": "bce5ca5e",
122
+ "metadata": {},
123
+ "source": [
124
+ "## The functional API\n",
125
+ "\n",
126
+ "`imread` and `imwrite` work with plain numpy arrays: the format comes from the file extension, and options go to the formats that have them."
127
+ ]
128
+ },
129
+ {
130
+ "cell_type": "code",
131
+ "execution_count": null,
132
+ "id": "731bffe0",
133
+ "metadata": {},
134
+ "outputs": [],
135
+ "source": [
136
+ "import tempfile, pathlib\n",
137
+ "tmp = pathlib.Path(tempfile.mkdtemp())\n",
138
+ "\n",
139
+ "libstb.imwrite(tmp / \"pattern.png\", img) # an Image or an array\n",
140
+ "libstb.imwrite(tmp / \"pattern.jpg\", img, quality=30)\n",
141
+ "print(libstb.iminfo(tmp / \"pattern.png\")) # header only\n",
142
+ "pixels = libstb.imread(tmp / \"pattern.png\") # just the ndarray\n",
143
+ "print(pixels.shape, np.array_equal(pixels, img.numpy()))\n",
144
+ "\n",
145
+ "try:\n",
146
+ " libstb.imwrite(tmp / \"bad.png\", img, quality=30) # png has no quality\n",
147
+ "except ValueError as e:\n",
148
+ " print(e)"
149
+ ]
150
+ },
151
+ {
152
+ "cell_type": "markdown",
153
+ "id": "e49803e3",
154
+ "metadata": {},
155
+ "source": [
156
+ "## Channels and flipping\n",
157
+ "\n",
158
+ "Ask for a channel count or a vertical flip while decoding."
159
+ ]
160
+ },
161
+ {
162
+ "cell_type": "code",
163
+ "execution_count": null,
164
+ "id": "e3bcb758",
165
+ "metadata": {},
166
+ "outputs": [],
167
+ "source": [
168
+ "rgba = libstb.Image.open(data, channels=4)\n",
169
+ "flipped = libstb.Image.open(data, flip=True)\n",
170
+ "print(\"rgba channels:\", rgba.channels, \"| alpha:\", rgba.numpy()[0, 0, 3])\n",
171
+ "plt.imshow(flipped.numpy()); plt.axis(\"off\");"
172
+ ]
173
+ },
174
+ {
175
+ "cell_type": "markdown",
176
+ "id": "11d09b6d",
177
+ "metadata": {},
178
+ "source": [
179
+ "## Sharing pixels with other frameworks\n",
180
+ "\n",
181
+ "`Image` speaks DLPack, so numpy, torch, jax and cupy can take the pixels without a copy. The layout is fixed: `uint8`, `(height, width, channels)`, on the CPU."
182
+ ]
183
+ },
184
+ {
185
+ "cell_type": "code",
186
+ "execution_count": null,
187
+ "id": "f3fd39cd",
188
+ "metadata": {},
189
+ "outputs": [],
190
+ "source": [
191
+ "shared = np.from_dlpack(img)\n",
192
+ "print(\"shares memory:\", np.shares_memory(shared, img.numpy()))\n",
193
+ "back = libstb.Image.from_dlpack(shared) # and back to an Image\n",
194
+ "print(\"from_dlpack shares memory:\", np.shares_memory(back.numpy(), shared))\n",
195
+ "# torch.from_dlpack(img) and jax.numpy.from_dlpack(img) work the same way.\n",
196
+ "# For another layout, convert on their side:\n",
197
+ "# torch.from_dlpack(img).permute(2, 0, 1).float() / 255"
198
+ ]
199
+ }
200
+ ],
201
+ "metadata": {
202
+ "kernelspec": {
203
+ "display_name": "Python 3",
204
+ "language": "python",
205
+ "name": "python3"
206
+ }
207
+ },
208
+ "nbformat": 4,
209
+ "nbformat_minor": 5
210
+ }
@@ -0,0 +1,144 @@
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "abd905b1",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Resize filters\n",
9
+ "\n",
10
+ "Compare every resize filter, shrinking and enlarging. Filters are given by name; other options live on `libstb.Resizer`."
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "code",
15
+ "execution_count": null,
16
+ "id": "d790e957",
17
+ "metadata": {},
18
+ "outputs": [],
19
+ "source": [
20
+ "import numpy as np\n",
21
+ "import matplotlib.pyplot as plt\n",
22
+ "import libstb"
23
+ ]
24
+ },
25
+ {
26
+ "cell_type": "code",
27
+ "execution_count": null,
28
+ "id": "c6b0af16",
29
+ "metadata": {},
30
+ "outputs": [],
31
+ "source": [
32
+ "def make_test_image(size=128):\n",
33
+ " \"\"\"Checkerboard over a gradient: sharp edges show off the filters.\"\"\"\n",
34
+ " y, x = np.mgrid[0:size, 0:size]\n",
35
+ " grad = (x * 255 // (size - 1)).astype(np.uint8)\n",
36
+ " checks = ((x // 8 + y // 8) % 2 * 255).astype(np.uint8)\n",
37
+ " return libstb.Image(np.dstack([grad, checks, 255 - grad]))\n",
38
+ "\n",
39
+ "img = make_test_image()\n",
40
+ "plt.imshow(img.numpy()); plt.axis('off'); plt.title('source 128x128');"
41
+ ]
42
+ },
43
+ {
44
+ "cell_type": "markdown",
45
+ "id": "1ed148cb",
46
+ "metadata": {},
47
+ "source": [
48
+ "## Shrinking (128 to 48)"
49
+ ]
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "execution_count": null,
54
+ "id": "9930645f",
55
+ "metadata": {},
56
+ "outputs": [],
57
+ "source": [
58
+ "names = [\"nearest\", \"linear\", \"cubic\", \"bspline\", \"mitchell\", \"box\"]\n",
59
+ "fig, axes = plt.subplots(1, len(names), figsize=(14, 2.8))\n",
60
+ "for ax, name in zip(axes, names):\n",
61
+ " ax.imshow(img.resize(48, 48, name).numpy(), interpolation=\"nearest\")\n",
62
+ " ax.set_title(name); ax.axis(\"off\")"
63
+ ]
64
+ },
65
+ {
66
+ "cell_type": "markdown",
67
+ "id": "cccd1e4d",
68
+ "metadata": {},
69
+ "source": [
70
+ "## Enlarging (128 to 384), zoomed on a corner\n",
71
+ "\n",
72
+ "The top-left 96 pixels show how each filter treats the checkerboard edges."
73
+ ]
74
+ },
75
+ {
76
+ "cell_type": "code",
77
+ "execution_count": null,
78
+ "id": "125813e2",
79
+ "metadata": {},
80
+ "outputs": [],
81
+ "source": [
82
+ "fig, axes = plt.subplots(1, len(names), figsize=(14, 2.8))\n",
83
+ "for ax, name in zip(axes, names):\n",
84
+ " big = img.resize(384, 384, name).numpy()\n",
85
+ " ax.imshow(big[:96, :96], interpolation=\"nearest\")\n",
86
+ " ax.set_title(name); ax.axis(\"off\")"
87
+ ]
88
+ },
89
+ {
90
+ "cell_type": "markdown",
91
+ "id": "eff82c15",
92
+ "metadata": {},
93
+ "source": [
94
+ "## Names accepted\n",
95
+ "\n",
96
+ "Names are case-insensitive. An unknown name raises `ValueError` and lists the valid ones (there is no `lanczos`)."
97
+ ]
98
+ },
99
+ {
100
+ "cell_type": "code",
101
+ "execution_count": null,
102
+ "id": "5126a709",
103
+ "metadata": {},
104
+ "outputs": [],
105
+ "source": [
106
+ "try:\n",
107
+ " img.resize(64, 64, \"lanczos\")\n",
108
+ "except ValueError as e:\n",
109
+ " print(e)"
110
+ ]
111
+ },
112
+ {
113
+ "cell_type": "markdown",
114
+ "id": "0a7a6bfa",
115
+ "metadata": {},
116
+ "source": [
117
+ "## Other options\n",
118
+ "\n",
119
+ "Edge mode and sRGB handling are keywords of `Resizer`."
120
+ ]
121
+ },
122
+ {
123
+ "cell_type": "code",
124
+ "execution_count": null,
125
+ "id": "b26712b8",
126
+ "metadata": {},
127
+ "outputs": [],
128
+ "source": [
129
+ "resizer = libstb.Resizer(libstb.Resizer.Filter.MITCHELL, libstb.Resizer.Edge.WRAP, srgb=False)\n",
130
+ "out = img.resize(64, 64, resizer)\n",
131
+ "plt.imshow(out.numpy(), interpolation=\"nearest\"); plt.axis(\"off\");"
132
+ ]
133
+ }
134
+ ],
135
+ "metadata": {
136
+ "kernelspec": {
137
+ "display_name": "Python 3",
138
+ "language": "python",
139
+ "name": "python3"
140
+ }
141
+ },
142
+ "nbformat": 4,
143
+ "nbformat_minor": 5
144
+ }
@@ -0,0 +1,127 @@
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "7acb877a",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Rendering text\n",
9
+ "\n",
10
+ "This notebook uses the DejaVu Sans font that ships with matplotlib, so nothing else is needed. Only load fonts you trust: stb_truetype does no bounds checking."
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "code",
15
+ "execution_count": null,
16
+ "id": "503a6d8b",
17
+ "metadata": {},
18
+ "outputs": [],
19
+ "source": [
20
+ "from pathlib import Path\n",
21
+ "import matplotlib\n",
22
+ "import matplotlib.pyplot as plt\n",
23
+ "import libstb\n",
24
+ "\n",
25
+ "font_path = Path(matplotlib.get_data_path()) / \"fonts\" / \"ttf\" / \"DejaVuSans.ttf\"\n",
26
+ "font = libstb.Font.open(font_path)\n",
27
+ "size = 40"
28
+ ]
29
+ },
30
+ {
31
+ "cell_type": "markdown",
32
+ "id": "288dd545",
33
+ "metadata": {},
34
+ "source": [
35
+ "## Metrics"
36
+ ]
37
+ },
38
+ {
39
+ "cell_type": "code",
40
+ "execution_count": null,
41
+ "id": "a954565d",
42
+ "metadata": {},
43
+ "outputs": [],
44
+ "source": [
45
+ "print(font.metrics(size))\n",
46
+ "print(\"advance A:\", font.advance(\"A\", size))\n",
47
+ "print(\"kerning A,V:\", font.kerning(\"A\", \"V\", size))\n",
48
+ "print(\"measure:\", font.measure(\"Hello\", size))"
49
+ ]
50
+ },
51
+ {
52
+ "cell_type": "markdown",
53
+ "id": "22c98631",
54
+ "metadata": {},
55
+ "source": [
56
+ "## A text bitmap\n",
57
+ "\n",
58
+ "`render` takes UTF-8 (newlines are fine) and returns a 1-channel coverage image."
59
+ ]
60
+ },
61
+ {
62
+ "cell_type": "code",
63
+ "execution_count": null,
64
+ "id": "fd3ff2bb",
65
+ "metadata": {},
66
+ "outputs": [],
67
+ "source": [
68
+ "text = font.render(\"Hello\\nw\\u00f6rld\", size)\n",
69
+ "print(text.bitmap.width, text.bitmap.height, (text.origin_x, text.origin_y))\n",
70
+ "plt.imshow(text.bitmap.numpy()[:, :, 0], cmap=\"gray_r\"); plt.axis(\"off\");"
71
+ ]
72
+ },
73
+ {
74
+ "cell_type": "markdown",
75
+ "id": "46fc2d24",
76
+ "metadata": {},
77
+ "source": [
78
+ "## Single glyph"
79
+ ]
80
+ },
81
+ {
82
+ "cell_type": "code",
83
+ "execution_count": null,
84
+ "id": "4a223259",
85
+ "metadata": {},
86
+ "outputs": [],
87
+ "source": [
88
+ "g = font.render_glyph(\"A\", 120)\n",
89
+ "print(\"offset\", (g.x_offset, g.y_offset), \"advance\", g.advance)\n",
90
+ "plt.imshow(g.bitmap.numpy()[:, :, 0], cmap=\"gray_r\"); plt.axis(\"off\");"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "id": "247dcd4e",
96
+ "metadata": {},
97
+ "source": [
98
+ "## Glyph atlas\n",
99
+ "\n",
100
+ "A packed sheet of glyphs plus a lookup table, handy for game or GPU text."
101
+ ]
102
+ },
103
+ {
104
+ "cell_type": "code",
105
+ "execution_count": null,
106
+ "id": "dc45361e",
107
+ "metadata": {},
108
+ "outputs": [],
109
+ "source": [
110
+ "atlas = font.make_atlas(\"ABCDEFGabcdefg0123456789\", 32, 256, 128)\n",
111
+ "plt.figure(figsize=(8, 4))\n",
112
+ "plt.imshow(atlas.image.numpy()[:, :, 0], cmap=\"gray_r\"); plt.axis(\"off\")\n",
113
+ "ag = atlas[\"A\"]\n",
114
+ "print(\"A lives at\", (ag.x0, ag.y0, ag.x1, ag.y1))"
115
+ ]
116
+ }
117
+ ],
118
+ "metadata": {
119
+ "kernelspec": {
120
+ "display_name": "Python 3",
121
+ "language": "python",
122
+ "name": "python3"
123
+ }
124
+ },
125
+ "nbformat": 4,
126
+ "nbformat_minor": 5
127
+ }
@@ -0,0 +1,4 @@
1
+ libstb
2
+ numpy
3
+ matplotlib
4
+ jupyterlab
@@ -0,0 +1,4 @@
1
+ output/
2
+ __pycache__/
3
+ *.pyc
4
+ .venv/