pixelplotlib 0.1.0__py3-none-any.whl

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.
pixelplotlib/canvas.py ADDED
@@ -0,0 +1,369 @@
1
+ """A tiny raster canvas with pixel-exact drawing primitives."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator, Sequence
6
+ from contextlib import contextmanager
7
+
8
+ import numpy as np
9
+
10
+ from .dither import BAYER4, threshold_map
11
+ from .fonts import BitmapFont
12
+
13
+ Color = Sequence[int]
14
+
15
+ DASH_PATTERNS: dict[str, tuple[int, ...] | None] = {
16
+ "-": None,
17
+ "solid": None,
18
+ "--": (1, 1, 1, 1, 0, 0, 0),
19
+ "dashed": (1, 1, 1, 1, 0, 0, 0),
20
+ ":": (1, 0),
21
+ "dotted": (1, 0),
22
+ "-.": (1, 1, 1, 1, 0, 0, 1, 0, 0),
23
+ "dashdot": (1, 1, 1, 1, 0, 0, 1, 0, 0),
24
+ "none": (0,),
25
+ "": (0,),
26
+ }
27
+
28
+
29
+ def dash_pattern(style) -> tuple[int, ...] | None:
30
+ if style is None:
31
+ return None
32
+ if isinstance(style, str):
33
+ try:
34
+ return DASH_PATTERNS[style]
35
+ except KeyError:
36
+ raise ValueError(f"unknown linestyle {style!r}") from None
37
+ return tuple(int(bool(v)) for v in style)
38
+
39
+
40
+ def _round(v: np.ndarray) -> np.ndarray:
41
+ return np.floor(np.asarray(v, dtype=np.float64) + 0.5).astype(np.int64)
42
+
43
+
44
+ class Canvas:
45
+ """An RGB pixel buffer with a clip rectangle.
46
+
47
+ Coordinates are integer pixel positions; ``(0, 0)`` is the top-left pixel.
48
+ Rectangles are given as ``(x0, y0, x1, y1)`` with exclusive ``x1``/``y1``.
49
+ """
50
+
51
+ def __init__(self, width: int, height: int, color: Color = (0, 0, 0)):
52
+ self.width = int(width)
53
+ self.height = int(height)
54
+ self.pixels = np.empty((self.height, self.width, 3), dtype=np.uint8)
55
+ self.pixels[:] = color
56
+ self._clip = (0, 0, self.width, self.height)
57
+
58
+ # ------------------------------------------------------------------ clipping
59
+ @contextmanager
60
+ def clip(self, x0: int, y0: int, x1: int, y1: int) -> Iterator[None]:
61
+ """Temporarily restrict drawing to a rectangle (intersected with the current clip)."""
62
+ old = self._clip
63
+ self._clip = (max(old[0], x0), max(old[1], y0), min(old[2], x1), min(old[3], y1))
64
+ try:
65
+ yield
66
+ finally:
67
+ self._clip = old
68
+
69
+ def _visible(self, xs: np.ndarray, ys: np.ndarray) -> np.ndarray:
70
+ cx0, cy0, cx1, cy1 = self._clip
71
+ return (xs >= cx0) & (xs < cx1) & (ys >= cy0) & (ys < cy1)
72
+
73
+ # ------------------------------------------------------------------ points
74
+ def put(self, xs, ys, color: Color, alpha: float = 1.0) -> None:
75
+ """Set individual pixels (vectorized)."""
76
+ xs = np.asarray(xs, dtype=np.int64).ravel()
77
+ ys = np.asarray(ys, dtype=np.int64).ravel()
78
+ keep = self._visible(xs, ys)
79
+ if alpha < 1.0:
80
+ keep &= _thresh_at(xs, ys) < alpha
81
+ self.pixels[ys[keep], xs[keep]] = color
82
+
83
+ def put_rgb(self, xs, ys, rgb: np.ndarray) -> None:
84
+ """Set pixels to per-pixel colors."""
85
+ xs = np.asarray(xs, dtype=np.int64).ravel()
86
+ ys = np.asarray(ys, dtype=np.int64).ravel()
87
+ rgb = np.asarray(rgb, dtype=np.uint8).reshape(-1, 3)
88
+ keep = self._visible(xs, ys)
89
+ self.pixels[ys[keep], xs[keep]] = rgb[keep]
90
+
91
+ # ------------------------------------------------------------------ rectangles
92
+ def _clip_rect(self, x0, y0, x1, y1) -> tuple[int, int, int, int]:
93
+ cx0, cy0, cx1, cy1 = self._clip
94
+ return max(int(x0), cx0), max(int(y0), cy0), min(int(x1), cx1), min(int(y1), cy1)
95
+
96
+ def fill_rect(self, x0, y0, x1, y1, color: Color, alpha: float = 1.0) -> None:
97
+ """Fill ``[x0, x1) x [y0, y1)``; ``alpha < 1`` uses an ordered dither pattern."""
98
+ if x1 < x0:
99
+ x0, x1 = x1, x0
100
+ if y1 < y0:
101
+ y0, y1 = y1, y0
102
+ x0, y0, x1, y1 = self._clip_rect(x0, y0, x1, y1)
103
+ if x1 <= x0 or y1 <= y0:
104
+ return
105
+ if alpha >= 1.0:
106
+ self.pixels[y0:y1, x0:x1] = color
107
+ elif alpha > 0:
108
+ mask = threshold_map((y1 - y0, x1 - x0), x0, y0) < alpha
109
+ self.pixels[y0:y1, x0:x1][mask] = color
110
+
111
+ def fill_mask(self, mask: np.ndarray, x: int, y: int, color: Color, alpha: float = 1.0):
112
+ """Paint ``color`` wherever the boolean ``mask`` (placed at top-left ``x, y``) is set."""
113
+ mask = np.asarray(mask, dtype=bool)
114
+ h, w = mask.shape
115
+ x0, y0, x1, y1 = self._clip_rect(x, y, x + w, y + h)
116
+ if x1 <= x0 or y1 <= y0:
117
+ return
118
+ sub = mask[y0 - y : y1 - y, x0 - x : x1 - x]
119
+ if alpha < 1.0:
120
+ sub = sub & (threshold_map(sub.shape, x0, y0) < alpha)
121
+ self.pixels[y0:y1, x0:x1][sub] = color
122
+
123
+ def blit(self, image: np.ndarray, x: int, y: int, mask: np.ndarray | None = None) -> None:
124
+ """Copy an ``(h, w, 3)`` image with its top-left corner at ``(x, y)``."""
125
+ h, w = image.shape[:2]
126
+ x0, y0, x1, y1 = self._clip_rect(x, y, x + w, y + h)
127
+ if x1 <= x0 or y1 <= y0:
128
+ return
129
+ src = image[y0 - y : y1 - y, x0 - x : x1 - x]
130
+ if mask is None:
131
+ self.pixels[y0:y1, x0:x1] = src
132
+ else:
133
+ m = mask[y0 - y : y1 - y, x0 - x : x1 - x]
134
+ self.pixels[y0:y1, x0:x1][m] = src[m]
135
+
136
+ def rect(self, x0, y0, x1, y1, color: Color) -> None:
137
+ """1px outline of the rectangle ``[x0, x1) x [y0, y1)``."""
138
+ self.fill_rect(x0, y0, x1, y0 + 1, color)
139
+ self.fill_rect(x0, y1 - 1, x1, y1, color)
140
+ self.fill_rect(x0, y0, x0 + 1, y1, color)
141
+ self.fill_rect(x1 - 1, y0, x1, y1, color)
142
+
143
+ def hline(self, x0, x1, y, color: Color, dash=None) -> None:
144
+ self.polyline([x0, x1], [y, y], color, dash=dash)
145
+
146
+ def vline(self, x, y0, y1, color: Color, dash=None) -> None:
147
+ self.polyline([x, x], [y0, y1], color, dash=dash)
148
+
149
+ # ------------------------------------------------------------------ lines
150
+ def line(self, x0, y0, x1, y1, color: Color, width: int = 1, dash=None) -> None:
151
+ self.polyline([x0, x1], [y0, y1], color, width=width, dash=dash)
152
+
153
+ def polyline(
154
+ self,
155
+ xs,
156
+ ys,
157
+ color: Color,
158
+ width: int = 1,
159
+ dash=None,
160
+ alpha: float = 1.0,
161
+ ) -> None:
162
+ """Draw connected line segments through float pixel coordinates.
163
+
164
+ Non-finite coordinates break the line. Segments are clipped analytically
165
+ before rasterization, so far off-screen points are cheap.
166
+ """
167
+ xs = np.asarray(xs, dtype=np.float64).ravel()
168
+ ys = np.asarray(ys, dtype=np.float64).ravel()
169
+ if xs.size == 0:
170
+ return
171
+ pattern = dash_pattern(dash)
172
+ if xs.size == 1:
173
+ xs = np.repeat(xs, 2)
174
+ ys = np.repeat(ys, 2)
175
+ ax0, ay0, ax1, ay1 = xs[:-1], ys[:-1], xs[1:], ys[1:]
176
+ finite = np.isfinite(ax0) & np.isfinite(ay0) & np.isfinite(ax1) & np.isfinite(ay1)
177
+ # pixel offset of each segment start along the whole polyline (keeps dashes continuous)
178
+ steps = np.where(finite, np.maximum(np.abs(ax1 - ax0), np.abs(ay1 - ay0)), 0)
179
+ seg_offset = np.concatenate([[0.0], np.cumsum(steps)[:-1]])
180
+
181
+ pad = width + 1
182
+ cx0, cy0, cx1, cy1 = self._clip
183
+ t0, t1 = _liang_barsky(
184
+ np.where(finite, ax0, 0), np.where(finite, ay0, 0),
185
+ np.where(finite, ax1, 0), np.where(finite, ay1, 0),
186
+ cx0 - pad, cy0 - pad, cx1 + pad, cy1 + pad,
187
+ )
188
+ keep = finite & (t0 <= t1)
189
+ if not keep.any():
190
+ return
191
+ dx, dy = ax1 - ax0, ay1 - ay0
192
+ sx0 = _round(ax0[keep] + t0[keep] * dx[keep])
193
+ sy0 = _round(ay0[keep] + t0[keep] * dy[keep])
194
+ sx1 = _round(ax0[keep] + t1[keep] * dx[keep])
195
+ sy1 = _round(ay0[keep] + t1[keep] * dy[keep])
196
+ offs = _round(seg_offset[keep] + t0[keep] * steps[keep])
197
+
198
+ px, py, idx = _rasterize_segments(sx0, sy0, sx1, sy1, offs)
199
+ if pattern is not None:
200
+ on = np.asarray(pattern, dtype=bool)[idx % len(pattern)]
201
+ px, py = px[on], py[on]
202
+ self._stamp(px, py, color, width, alpha)
203
+
204
+ def _stamp(self, px, py, color, width: int, alpha: float = 1.0) -> None:
205
+ if width <= 1:
206
+ self.put(px, py, color, alpha)
207
+ return
208
+ lo = -((width - 1) // 2)
209
+ offs = np.arange(lo, lo + width)
210
+ ox, oy = np.meshgrid(offs, offs)
211
+ self.put(
212
+ (px[:, None] + ox.ravel()[None, :]).ravel(),
213
+ (py[:, None] + oy.ravel()[None, :]).ravel(),
214
+ color,
215
+ alpha,
216
+ )
217
+
218
+ # ------------------------------------------------------------------ polygons
219
+ def polygon_mask(self, xs, ys) -> tuple[np.ndarray, int, int]:
220
+ """Even-odd scanline coverage of a polygon; returns ``(mask, x0, y0)``."""
221
+ xs = np.asarray(xs, dtype=np.float64).ravel()
222
+ ys = np.asarray(ys, dtype=np.float64).ravel()
223
+ ok = np.isfinite(xs) & np.isfinite(ys)
224
+ xs, ys = xs[ok], ys[ok]
225
+ cx0, cy0, cx1, cy1 = self._clip
226
+ if xs.size < 3:
227
+ return np.zeros((0, 0), bool), cx0, cy0
228
+ ymin = max(int(np.ceil(ys.min())), cy0)
229
+ ymax = min(int(np.floor(ys.max())), cy1 - 1)
230
+ if ymax < ymin:
231
+ return np.zeros((0, 0), bool), cx0, cy0
232
+ xa, ya = xs, ys
233
+ xb, yb = np.roll(xs, -1), np.roll(ys, -1)
234
+ rows = np.arange(ymin, ymax + 1, dtype=np.float64)[:, None]
235
+ crosses = ((ya <= rows) & (yb > rows)) | ((yb <= rows) & (ya > rows))
236
+ with np.errstate(divide="ignore", invalid="ignore"):
237
+ xi = xa + (rows - ya) * (xb - xa) / (yb - ya)
238
+ width = cx1 - cx0
239
+ cols = np.clip(np.ceil(xi - 1e-9).astype(np.int64) - cx0, 0, width)
240
+ acc = np.zeros((rows.shape[0], width + 1), dtype=np.int32)
241
+ r_idx = np.broadcast_to(np.arange(rows.shape[0])[:, None], cols.shape)
242
+ np.add.at(acc, (r_idx[crosses], cols[crosses]), 1)
243
+ mask = (np.cumsum(acc, axis=1)[:, :width] % 2).astype(bool)
244
+ return mask, cx0, ymin
245
+
246
+ def fill_polygon(self, xs, ys, color: Color, alpha: float = 1.0) -> None:
247
+ mask, x0, y0 = self.polygon_mask(xs, ys)
248
+ if mask.size:
249
+ self.fill_mask(mask, x0, y0, color, alpha)
250
+
251
+ # ------------------------------------------------------------------ circles
252
+ @staticmethod
253
+ def disc_mask(r: float) -> np.ndarray:
254
+ """Boolean mask of a filled pixel disc with radius ``r`` (odd-sized, centered)."""
255
+ n = int(np.ceil(r))
256
+ yy, xx = np.mgrid[-n : n + 1, -n : n + 1]
257
+ return xx * xx + yy * yy <= r * r + r * 0.8
258
+
259
+ def circle(self, cx, cy, r: float, color: Color, fill: bool = False, alpha: float = 1.0):
260
+ m = self.disc_mask(r)
261
+ if not fill:
262
+ m = m & ~_erode(m)
263
+ n = m.shape[0] // 2
264
+ self.fill_mask(m, int(round(cx)) - n, int(round(cy)) - n, color, alpha)
265
+
266
+ # ------------------------------------------------------------------ text
267
+ def text(
268
+ self,
269
+ x: int,
270
+ y: int,
271
+ text: str,
272
+ font: BitmapFont,
273
+ color: Color,
274
+ ha: str = "left",
275
+ va: str = "top",
276
+ rotation: int = 0,
277
+ shadow: Color | None = None,
278
+ align: str | None = None,
279
+ ) -> tuple[int, int, int, int]:
280
+ """Draw text anchored at ``(x, y)``; returns the bounding box ``(x0, y0, x1, y1)``.
281
+
282
+ ``va="center"`` centers on the capital letters (ignores descenders).
283
+ ``rotation`` may be 0, 90 (reads bottom-to-top) or 270.
284
+ """
285
+ if text is None or str(text) == "":
286
+ return (x, y, x, y)
287
+ align = align or {"right": "right", "center": "center"}.get(ha, "left")
288
+ mask = font.render(str(text), align)
289
+ if rotation % 360:
290
+ mask = np.rot90(mask, k=(rotation // 90) % 4)
291
+ h, w = mask.shape
292
+ if rotation % 360 == 0:
293
+ cap_h = h - font.descent
294
+ vy = {"top": 0, "center": cap_h // 2, "baseline": cap_h - 1,
295
+ "bottom": h - 1}[va]
296
+ else:
297
+ vy = {"top": 0, "center": h // 2, "bottom": h - 1, "baseline": h - 1}[va]
298
+ hx = {"left": 0, "center": w // 2, "right": w - 1}[ha]
299
+ x0, y0 = int(x) - hx, int(y) - vy
300
+ if shadow is not None:
301
+ self.fill_mask(mask, x0 + 1, y0 + 1, shadow)
302
+ self.fill_mask(mask, x0, y0, color)
303
+ return (x0, y0, x0 + w, y0 + h)
304
+
305
+ # ------------------------------------------------------------------ export
306
+ def to_array(self, scale: int = 1) -> np.ndarray:
307
+ """Return the pixels, upscaled with nearest-neighbour by an integer factor."""
308
+ if scale == 1:
309
+ return self.pixels.copy()
310
+ return np.repeat(np.repeat(self.pixels, scale, axis=0), scale, axis=1)
311
+
312
+
313
+ def _thresh_at(xs: np.ndarray, ys: np.ndarray) -> np.ndarray:
314
+ return BAYER4[ys % 4, xs % 4]
315
+
316
+
317
+ def _erode(m: np.ndarray) -> np.ndarray:
318
+ p = np.pad(m, 1)
319
+ return p[1:-1, 1:-1] & p[:-2, 1:-1] & p[2:, 1:-1] & p[1:-1, :-2] & p[1:-1, 2:]
320
+
321
+
322
+ def dilate(m: np.ndarray, diagonal: bool = False) -> np.ndarray:
323
+ """Grow a boolean mask by one pixel (output is 2px larger in each dimension)."""
324
+ p = np.pad(m, 2)
325
+ out = p[1:-1, 1:-1] | p[:-2, 1:-1] | p[2:, 1:-1] | p[1:-1, :-2] | p[1:-1, 2:]
326
+ if diagonal:
327
+ out |= p[:-2, :-2] | p[:-2, 2:] | p[2:, :-2] | p[2:, 2:]
328
+ return out
329
+
330
+
331
+ def _liang_barsky(x0, y0, x1, y1, xmin, ymin, xmax, ymax):
332
+ dx = x1 - x0
333
+ dy = y1 - y0
334
+ t0 = np.zeros_like(x0)
335
+ t1 = np.ones_like(x0)
336
+ for p, q in ((-dx, x0 - xmin), (dx, xmax - x0), (-dy, y0 - ymin), (dy, ymax - y0)):
337
+ with np.errstate(divide="ignore", invalid="ignore"):
338
+ r = q / p
339
+ neg = p < 0
340
+ pos = p > 0
341
+ t0 = np.where(neg, np.maximum(t0, r), t0)
342
+ t1 = np.where(pos, np.minimum(t1, r), t1)
343
+ # parallel and outside: reject
344
+ t1 = np.where((p == 0) & (q < 0), -1.0, t1)
345
+ return t0, t1
346
+
347
+
348
+ def _rasterize_segments(x0, y0, x1, y1, offsets):
349
+ """DDA rasterization of many integer segments at once.
350
+
351
+ Returns pixel x, y and the running pixel index (for dash patterns).
352
+ """
353
+ dx = x1 - x0
354
+ dy = y1 - y0
355
+ n = np.maximum(np.abs(dx), np.abs(dy))
356
+ count = n + 1
357
+ seg = np.repeat(np.arange(len(n)), count)
358
+ starts = np.cumsum(count) - count
359
+ k = np.arange(count.sum()) - np.repeat(starts, count)
360
+ denom = np.maximum(n[seg], 1)
361
+ px = x0[seg] + _round_div(dx[seg] * k, denom)
362
+ py = y0[seg] + _round_div(dy[seg] * k, denom)
363
+ return px, py, offsets[seg] + k
364
+
365
+
366
+ def _round_div(a: np.ndarray, b: np.ndarray) -> np.ndarray:
367
+ """Integer division rounding half away from zero (symmetric for both directions)."""
368
+ q = (2 * np.abs(a) + b) // (2 * b)
369
+ return np.sign(a) * q
@@ -0,0 +1,163 @@
1
+ """Colormaps and palette-aware color ramps."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+
7
+ import numpy as np
8
+
9
+ from .colors import ColorLike, ColorSystem, luminance, parse_color
10
+ from .dither import threshold_map
11
+
12
+
13
+ class Colormap:
14
+ """Piecewise-linear colormap defined by anchor colors."""
15
+
16
+ def __init__(
17
+ self,
18
+ name: str,
19
+ colors: Sequence[ColorLike],
20
+ positions: Sequence[float] | None = None,
21
+ explicit: bool = False,
22
+ ):
23
+ self.name = name
24
+ self.colors = np.array([parse_color(c) for c in colors], dtype=np.float64)
25
+ if positions is None:
26
+ positions = np.linspace(0.0, 1.0, len(self.colors))
27
+ self.positions = np.asarray(positions, dtype=np.float64)
28
+ # explicit colormaps are user-provided color lists that should be used verbatim
29
+ self.explicit = explicit
30
+
31
+ def __call__(self, t) -> np.ndarray:
32
+ """Map values in ``[0, 1]`` to float RGB in ``[0, 255]``."""
33
+ t = np.clip(np.asarray(t, dtype=np.float64), 0.0, 1.0)
34
+ return np.stack(
35
+ [np.interp(t, self.positions, self.colors[:, k]) for k in range(3)], axis=-1
36
+ )
37
+
38
+ def reversed(self) -> Colormap:
39
+ name = self.name[:-2] if self.name.endswith("_r") else self.name + "_r"
40
+ return Colormap(name, self.colors[::-1], 1.0 - self.positions[::-1], self.explicit)
41
+
42
+ def __repr__(self) -> str:
43
+ return f"Colormap({self.name!r})"
44
+
45
+
46
+ _CMAP_DATA: dict[str, list[str]] = {
47
+ "viridis": ["#440154", "#472D7B", "#3B528B", "#2C728E", "#21918C",
48
+ "#27AD81", "#5EC962", "#AADC32", "#FDE725"],
49
+ "magma": ["#000004", "#1C1044", "#4F127B", "#812581", "#B5367A",
50
+ "#E55064", "#FB8761", "#FEC287", "#FCFDBF"],
51
+ "inferno": ["#000004", "#1F0C48", "#550F6D", "#88226A", "#BA3655",
52
+ "#E35933", "#F98C0A", "#F9C932", "#FCFFA4"],
53
+ "plasma": ["#0D0887", "#4C02A1", "#7E03A8", "#A92395", "#CC4778",
54
+ "#E56B5D", "#F89441", "#FDC328", "#F0F921"],
55
+ "coolwarm": ["#3B4CC0", "#8DB0FE", "#DDDDDD", "#F49A7B", "#B40426"],
56
+ "fire": ["#000000", "#C00000", "#FFA000", "#FFFFFF"],
57
+ "ice": ["#000000", "#0030A0", "#20C0F0", "#FFFFFF"],
58
+ "gray": ["#000000", "#FFFFFF"],
59
+ "rainbow": ["#6E40AA", "#2060FF", "#00C8E0", "#20D040", "#F8E000", "#FF8000", "#E01010"],
60
+ "terrain": ["#333399", "#0099FF", "#00CC66", "#FFFF99", "#805C54", "#FFFFFF"],
61
+ "ocean": ["#002010", "#003060", "#1060A0", "#40A0D0", "#C0F0FF"],
62
+ "gameboy": ["#0F380F", "#306230", "#8BAC0F", "#9BBC0F"],
63
+ "pico": ["#000000", "#1D2B53", "#7E2553", "#AB5236", "#FF004D",
64
+ "#FFA300", "#FFEC27", "#FFF1E8"],
65
+ }
66
+ _CMAP_POSITIONS: dict[str, list[float]] = {
67
+ "terrain": [0.0, 0.15, 0.25, 0.5, 0.75, 1.0],
68
+ }
69
+
70
+ COLORMAPS: dict[str, Colormap] = {
71
+ name: Colormap(name, cols, _CMAP_POSITIONS.get(name)) for name, cols in _CMAP_DATA.items()
72
+ }
73
+ COLORMAPS["grey"] = COLORMAPS["gray"]
74
+
75
+ CmapLike = str | Colormap | Sequence[ColorLike]
76
+
77
+
78
+ def get_cmap(cmap: CmapLike) -> Colormap:
79
+ """Look up a colormap by name (``"_r"`` suffix reverses it) or build one from colors."""
80
+ if isinstance(cmap, Colormap):
81
+ return cmap
82
+ if isinstance(cmap, str):
83
+ name = cmap.lower()
84
+ if name in COLORMAPS:
85
+ return COLORMAPS[name]
86
+ if name.endswith("_r") and name[:-2] in COLORMAPS:
87
+ return COLORMAPS[name[:-2]].reversed()
88
+ raise ValueError(f"unknown colormap {cmap!r}; choose from {sorted(COLORMAPS)}")
89
+ return Colormap("custom", list(cmap), explicit=True)
90
+
91
+
92
+ def register_cmap(name: str, colors: Sequence[ColorLike], positions=None) -> Colormap:
93
+ """Register a new named colormap."""
94
+ cm = Colormap(name, colors, positions)
95
+ COLORMAPS[name.lower()] = cm
96
+ return cm
97
+
98
+
99
+ class Ramp:
100
+ """A short list of displayable colors at positions in ``[0, 1]``.
101
+
102
+ Values in between two ramp entries are rendered with ordered dithering,
103
+ which is how 8/16-bit hardware faked smooth gradients.
104
+ """
105
+
106
+ def __init__(self, positions: np.ndarray, colors: np.ndarray):
107
+ self.positions = np.asarray(positions, dtype=np.float64)
108
+ self.colors = np.asarray(colors, dtype=np.uint8)
109
+
110
+ def __len__(self) -> int:
111
+ return len(self.colors)
112
+
113
+ def map(self, t: np.ndarray, dither: bool = True, x0: int = 0, y0: int = 0) -> np.ndarray:
114
+ """Map a 2-D array of values in ``[0, 1]`` to an RGB image."""
115
+ t = np.clip(np.nan_to_num(np.asarray(t, dtype=np.float64), nan=0.0), 0.0, 1.0)
116
+ if len(self.colors) == 1:
117
+ return np.broadcast_to(self.colors[0], t.shape + (3,)).copy()
118
+ pos = self.positions
119
+ idx = np.clip(np.searchsorted(pos, t, side="right") - 1, 0, len(pos) - 2)
120
+ frac = (t - pos[idx]) / np.maximum(pos[idx + 1] - pos[idx], 1e-12)
121
+ if t.ndim == 2:
122
+ thresh = threshold_map(t.shape, x0, y0) if dither else 0.5
123
+ else:
124
+ thresh = 0.5
125
+ idx = idx + (frac > thresh)
126
+ return self.colors[idx]
127
+
128
+ def color_at(self, t: float) -> tuple[int, int, int]:
129
+ """Nearest (undithered) ramp color for a scalar value."""
130
+ rgb = self.map(np.array([[t]]), dither=False)[0, 0]
131
+ return tuple(int(v) for v in rgb) # type: ignore[return-value]
132
+
133
+
134
+ def build_ramp(cmap: CmapLike, colors: ColorSystem, levels: int = 16) -> Ramp:
135
+ """Build a displayable :class:`Ramp` for ``cmap`` under the given color system."""
136
+ cm = get_cmap(cmap)
137
+ if cm.explicit:
138
+ snapped = colors.snap_array(np.round(cm.colors).astype(np.uint8))
139
+ return Ramp(np.linspace(0, 1, len(snapped)), snapped)
140
+
141
+ pal = colors.palette
142
+ if pal is not None and len(pal) <= 4:
143
+ # tiny palettes: use every shade ordered by brightness
144
+ order = np.argsort([luminance(c) for c in pal])
145
+ ramp_cols = pal[order]
146
+ if luminance(cm(0.0)) > luminance(cm(1.0)):
147
+ ramp_cols = ramp_cols[::-1]
148
+ return Ramp(np.linspace(0, 1, len(ramp_cols)), ramp_cols)
149
+
150
+ t = np.linspace(0.0, 1.0, levels)
151
+ samples = colors.snap_array(np.round(cm(t)).astype(np.uint8))
152
+ # collapse runs of identical colors, placing each at the center of its run
153
+ positions, cols = [], []
154
+ start = 0
155
+ for i in range(1, levels + 1):
156
+ if i == levels or not np.array_equal(samples[i], samples[start]):
157
+ positions.append(t[start:i].mean())
158
+ cols.append(samples[start])
159
+ start = i
160
+ positions[0], positions[-1] = 0.0, 1.0
161
+ if len(cols) == 1:
162
+ positions = [0.0]
163
+ return Ramp(np.array(positions), np.array(cols))
pixelplotlib/colors.py ADDED
@@ -0,0 +1,143 @@
1
+ """Color parsing, palette snapping and bit-depth quantization."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+
7
+ import numpy as np
8
+
9
+ RGB = tuple[int, int, int]
10
+ ColorLike = str | Sequence[float] | Sequence[int] | RGB
11
+
12
+ NAMED_COLORS: dict[str, RGB] = {
13
+ "black": (0, 0, 0),
14
+ "white": (255, 255, 255),
15
+ "red": (228, 32, 32),
16
+ "green": (32, 192, 48),
17
+ "blue": (32, 80, 240),
18
+ "yellow": (248, 216, 32),
19
+ "cyan": (32, 216, 232),
20
+ "magenta": (224, 48, 224),
21
+ "orange": (248, 136, 24),
22
+ "purple": (128, 48, 200),
23
+ "pink": (248, 128, 176),
24
+ "brown": (136, 80, 24),
25
+ "gray": (128, 128, 128),
26
+ "grey": (128, 128, 128),
27
+ "lightgray": (192, 192, 192),
28
+ "lightgrey": (192, 192, 192),
29
+ "darkgray": (72, 72, 72),
30
+ "darkgrey": (72, 72, 72),
31
+ "navy": (16, 24, 112),
32
+ "teal": (0, 136, 136),
33
+ "lime": (152, 248, 24),
34
+ "olive": (128, 128, 0),
35
+ "maroon": (128, 16, 16),
36
+ "gold": (248, 184, 0),
37
+ "sky": (60, 188, 252),
38
+ }
39
+
40
+
41
+ def parse_color(color: ColorLike) -> RGB:
42
+ """Convert a color specification to an ``(r, g, b)`` tuple of ints.
43
+
44
+ Accepts ``"#rgb"``/``"#rrggbb"`` hex strings, named colors and sequences of
45
+ three numbers (floats in ``[0, 1]`` or ints in ``[0, 255]``).
46
+ """
47
+ if isinstance(color, str):
48
+ s = color.strip().lower()
49
+ if s.startswith("#"):
50
+ h = s[1:]
51
+ if len(h) == 3:
52
+ h = "".join(ch * 2 for ch in h)
53
+ if len(h) != 6:
54
+ raise ValueError(f"invalid hex color {color!r}")
55
+ return (int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16))
56
+ key = s.replace(" ", "").replace("_", "")
57
+ if key in NAMED_COLORS:
58
+ return NAMED_COLORS[key]
59
+ raise ValueError(f"unknown color {color!r}")
60
+ vals = list(color)
61
+ if len(vals) not in (3, 4):
62
+ raise ValueError(f"invalid color {color!r}")
63
+ vals = vals[:3]
64
+ if all(isinstance(v, (float, np.floating)) for v in vals) and max(vals) <= 1.0:
65
+ vals = [round(v * 255) for v in vals]
66
+ return tuple(int(np.clip(v, 0, 255)) for v in vals) # type: ignore[return-value]
67
+
68
+
69
+ def luminance(rgb: Sequence[float]) -> float:
70
+ r, g, b = rgb[:3]
71
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b
72
+
73
+
74
+ def mix(a: Sequence[int], b: Sequence[int], t: float) -> RGB:
75
+ """Linearly interpolate between colors ``a`` and ``b``."""
76
+ return tuple(int(round(float(x) + (float(y) - float(x)) * t)) # type: ignore
77
+ for x, y in zip(a[:3], b[:3]))
78
+
79
+
80
+ def shade(rgb: Sequence[int], amount: float) -> RGB:
81
+ """Lighten (``amount > 0``) or darken (``amount < 0``) a color."""
82
+ if amount >= 0:
83
+ return mix(rgb, (255, 255, 255), amount)
84
+ return mix(rgb, (0, 0, 0), -amount)
85
+
86
+
87
+ def _redmean_dist(a: np.ndarray, b: np.ndarray) -> np.ndarray:
88
+ """Cheap perceptual color distance (squared), broadcasting over leading dims."""
89
+ a = a.astype(np.float64)
90
+ b = b.astype(np.float64)
91
+ rmean = (a[..., 0] + b[..., 0]) / 2.0
92
+ d = a - b
93
+ return (
94
+ (2.0 + rmean / 256.0) * d[..., 0] ** 2
95
+ + 4.0 * d[..., 1] ** 2
96
+ + (2.0 + (255.0 - rmean) / 256.0) * d[..., 2] ** 2
97
+ )
98
+
99
+
100
+ class ColorSystem:
101
+ """Restricts colors to a hardware palette or to a per-channel bit depth.
102
+
103
+ Parameters
104
+ ----------
105
+ palette:
106
+ Allowed colors. Arbitrary colors are snapped to the nearest entry.
107
+ bits:
108
+ Bits per channel when no palette is given (5 bits = 15-bit "16-bit era" color).
109
+ """
110
+
111
+ def __init__(self, palette: Sequence[ColorLike] | None = None, bits: int | None = None):
112
+ self.palette = None if palette is None else np.array(
113
+ [parse_color(c) for c in palette], dtype=np.uint8
114
+ )
115
+ self.bits = bits
116
+
117
+ def snap(self, color: ColorLike) -> RGB:
118
+ rgb = np.array(parse_color(color), dtype=np.uint8)
119
+ return tuple(int(v) for v in self.snap_array(rgb[None, :])[0]) # type: ignore
120
+
121
+ def snap_array(self, arr: np.ndarray) -> np.ndarray:
122
+ """Snap an ``(..., 3)`` uint8 array of colors."""
123
+ arr = np.asarray(arr)
124
+ if self.palette is not None:
125
+ flat = arr.reshape(-1, 3)
126
+ out = np.empty_like(flat, dtype=np.uint8)
127
+ # chunk to keep memory bounded for large images
128
+ for start in range(0, len(flat), 65536):
129
+ chunk = flat[start : start + 65536]
130
+ d = _redmean_dist(chunk[:, None, :], self.palette[None, :, :])
131
+ out[start : start + 65536] = self.palette[np.argmin(d, axis=1)]
132
+ return out.reshape(arr.shape)
133
+ if self.bits is not None and self.bits < 8:
134
+ return quantize_bits(arr, self.bits)
135
+ return arr.astype(np.uint8)
136
+
137
+
138
+ def quantize_bits(arr: np.ndarray, bits: int) -> np.ndarray:
139
+ """Reduce channels to ``bits`` bits, then expand back to the full 8-bit range."""
140
+ arr = np.asarray(arr, dtype=np.uint8)
141
+ levels = (1 << bits) - 1
142
+ q = arr.astype(np.uint16) >> (8 - bits)
143
+ return ((q * 255 + levels // 2) // levels).astype(np.uint8)