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/dither.py ADDED
@@ -0,0 +1,89 @@
1
+ """Ordered (Bayer) dithering helpers."""
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
10
+
11
+
12
+ def bayer_matrix(n: int = 4) -> np.ndarray:
13
+ """Return an ``n x n`` Bayer threshold matrix with values in ``(0, 1)``."""
14
+ if n < 2 or n & (n - 1):
15
+ raise ValueError("n must be a power of two >= 2")
16
+ m = np.array([[0, 2], [3, 1]])
17
+ while m.shape[0] < n:
18
+ m = np.block([[4 * m, 4 * m + 2], [4 * m + 3, 4 * m + 1]])
19
+ return (m + 0.5) / m.size
20
+
21
+
22
+ BAYER4 = bayer_matrix(4)
23
+
24
+
25
+ def threshold_map(shape: tuple[int, int], x0: int = 0, y0: int = 0, n: int = 4) -> np.ndarray:
26
+ """Tile the Bayer matrix over ``shape``, anchored at absolute canvas position ``(x0, y0)``.
27
+
28
+ Anchoring at absolute coordinates keeps patterns seamless between adjacent regions.
29
+ """
30
+ m = BAYER4 if n == 4 else bayer_matrix(n)
31
+ h, w = shape
32
+ ys = (np.arange(h) + y0) % m.shape[0]
33
+ xs = (np.arange(w) + x0) % m.shape[1]
34
+ return m[ys[:, None], xs[None, :]]
35
+
36
+
37
+ def dither_mask(shape: tuple[int, int], level: float, x0: int = 0, y0: int = 0) -> np.ndarray:
38
+ """Boolean mask whose density of ``True`` pixels approximates ``level`` in ``[0, 1]``."""
39
+ return threshold_map(shape, x0, y0) < level
40
+
41
+
42
+ def pixelate(
43
+ image: np.ndarray,
44
+ palette: Sequence[ColorLike] | None = None,
45
+ size: tuple[int, int] | None = None,
46
+ dither: bool = True,
47
+ bits: int | None = None,
48
+ strength: float | None = None,
49
+ ) -> np.ndarray:
50
+ """Turn an RGB image into pixel art.
51
+
52
+ Parameters
53
+ ----------
54
+ image:
55
+ ``(H, W, 3)`` array, uint8 or float in ``[0, 1]``.
56
+ palette:
57
+ Target palette (list of colors). If ``None``, ``bits`` per channel is used.
58
+ size:
59
+ Optional output ``(width, height)``; nearest-neighbour downsampling is used.
60
+ dither:
61
+ Apply ordered dithering before snapping colors.
62
+ bits:
63
+ Bits per channel when no palette is given (default 5).
64
+ strength:
65
+ Dither amplitude in 8-bit units; defaults to a value derived from the palette.
66
+ """
67
+ img = np.asarray(image)
68
+ if img.ndim == 2:
69
+ img = np.repeat(img[..., None], 3, axis=2)
70
+ img = img[..., :3]
71
+ if img.dtype.kind == "f":
72
+ img = np.clip(img * 255.0, 0, 255)
73
+ img = img.astype(np.float64)
74
+ if size is not None:
75
+ w, h = size
76
+ ys = (np.arange(h) * img.shape[0] / h).astype(int)
77
+ xs = (np.arange(w) * img.shape[1] / w).astype(int)
78
+ img = img[ys[:, None], xs[None, :]]
79
+ system = ColorSystem(palette=palette, bits=None if palette is not None else (bits or 5))
80
+ if dither:
81
+ if strength is None:
82
+ if system.palette is not None:
83
+ strength = 256.0 / max(np.cbrt(len(system.palette)), 1.0)
84
+ else:
85
+ strength = 256.0 / (1 << system.bits)
86
+ t = threshold_map(img.shape[:2]) - 0.5
87
+ img = img + t[..., None] * strength
88
+ img = np.clip(np.round(img), 0, 255).astype(np.uint8)
89
+ return system.snap_array(img)
pixelplotlib/figure.py ADDED
@@ -0,0 +1,259 @@
1
+ """Figures: canvas size, subplot layout and image export."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import os
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+
11
+ from .axes import Axes, fill_area
12
+ from .canvas import Canvas
13
+ from .styles import Style, get_style
14
+
15
+
16
+ class Figure:
17
+ """A pixel canvas holding one or more :class:`Axes`.
18
+
19
+ Parameters
20
+ ----------
21
+ size:
22
+ ``(width, height)`` in *logical* pixels. Defaults to the style's native resolution.
23
+ style:
24
+ Style name or :class:`Style` (see :func:`pixelplotlib.styles.available`).
25
+ scale:
26
+ Integer upscaling factor used when saving/showing.
27
+ """
28
+
29
+ def __init__(self, size: tuple[int, int] | None = None, style: str | Style | None = None,
30
+ scale: int | None = None):
31
+ self.style = get_style(style)
32
+ w, h = size or self.style.size
33
+ self.size = (int(w), int(h))
34
+ self.scale = int(scale or self.style.scale)
35
+ self.axes: list[Axes] = []
36
+ self._suptitle: str | None = None
37
+ self._gca: Axes | None = None
38
+
39
+ @property
40
+ def width(self) -> int:
41
+ return self.size[0]
42
+
43
+ @property
44
+ def height(self) -> int:
45
+ return self.size[1]
46
+
47
+ # ------------------------------------------------------------------ layout
48
+ def add_subplot(self, nrows: int = 1, ncols: int = 1, index: int | tuple[int, int] = 1) -> Axes:
49
+ """Add axes in a grid cell (1-based ``index``; a ``(first, last)`` tuple spans cells)."""
50
+ first, last = (index, index) if isinstance(index, int) else index
51
+ if not (1 <= first <= nrows * ncols and 1 <= last <= nrows * ncols):
52
+ raise ValueError("subplot index out of range")
53
+ r0, c0 = divmod(first - 1, ncols)
54
+ r1, c1 = divmod(last - 1, ncols)
55
+ ax = Axes(self, ("grid", nrows, ncols, min(r0, r1), max(r0, r1), min(c0, c1),
56
+ max(c0, c1)))
57
+ self.axes.append(ax)
58
+ self._gca = ax
59
+ return ax
60
+
61
+ def add_axes(self, rect: tuple[float, float, float, float]) -> Axes:
62
+ """Add axes at ``(left, bottom, width, height)`` in figure fractions."""
63
+ ax = Axes(self, ("rect", *rect))
64
+ self.axes.append(ax)
65
+ self._gca = ax
66
+ return ax
67
+
68
+ def subplots(self, nrows: int = 1, ncols: int = 1, squeeze: bool = True):
69
+ """Create a grid of axes; returns one Axes or a numpy array of them."""
70
+ arr = np.empty((nrows, ncols), dtype=object)
71
+ for r in range(nrows):
72
+ for c in range(ncols):
73
+ arr[r, c] = self.add_subplot(nrows, ncols, r * ncols + c + 1)
74
+ if squeeze:
75
+ if arr.size == 1:
76
+ return arr[0, 0]
77
+ if nrows == 1 or ncols == 1:
78
+ return arr.ravel()
79
+ return arr
80
+
81
+ def gca(self) -> Axes:
82
+ if self._gca is None:
83
+ return self.add_subplot()
84
+ return self._gca
85
+
86
+ def sca(self, ax: Axes) -> None:
87
+ self._gca = ax
88
+
89
+ def suptitle(self, title: str | None) -> Figure:
90
+ self._suptitle = title
91
+ return self
92
+
93
+ def colorbar(self, mappable=None, ax: Axes | None = None, label: str | None = None,
94
+ ticks=None):
95
+ """Add a colorbar next to ``ax`` (defaults to the axes owning ``mappable``)."""
96
+ if ax is None:
97
+ ax = next((a for a in self.axes if mappable in a.artists), None) or self.gca()
98
+ return ax.colorbar(mappable, label=label, ticks=ticks)
99
+
100
+ def _cell(self, ax: Axes, area) -> tuple[int, int, int, int]:
101
+ gx0, gy0, gx1, gy1 = area
102
+ spec = ax._spec
103
+ if spec[0] == "rect":
104
+ _, l, b, w, h = spec
105
+ x0 = int(round(l * self.width))
106
+ x1 = int(round((l + w) * self.width))
107
+ y1 = int(round((1 - b) * self.height))
108
+ y0 = int(round((1 - b - h) * self.height))
109
+ return x0, y0, x1, y1
110
+ _, nrows, ncols, r0, r1, c0, c1 = spec
111
+ gap = 2 if self.style.panel else 4
112
+ cw = (gx1 - gx0 - (ncols - 1) * gap) / ncols
113
+ ch = (gy1 - gy0 - (nrows - 1) * gap) / nrows
114
+ x0 = gx0 + c0 * (cw + gap)
115
+ x1 = gx0 + (c1 + 1) * cw + c1 * gap
116
+ y0 = gy0 + r0 * (ch + gap)
117
+ y1 = gy0 + (r1 + 1) * ch + r1 * gap
118
+ return int(round(x0)), int(round(y0)), int(round(x1)), int(round(y1))
119
+
120
+ # ------------------------------------------------------------------ rendering
121
+ def render(self, size: tuple[int, int] | None = None) -> Canvas:
122
+ """Rasterize the figure at its logical resolution.
123
+
124
+ ``size`` lays the figure out at a different ``(width, height)`` for this call only,
125
+ which is how terminal front-ends fit a figure to the space they have.
126
+ """
127
+ if size is not None and tuple(size) != self.size:
128
+ saved, self.size = self.size, (max(int(size[0]), 1), max(int(size[1]), 1))
129
+ try:
130
+ return self._render()
131
+ finally:
132
+ self.size = saved
133
+ return self._render()
134
+
135
+ def _render(self) -> Canvas:
136
+ st = self.style
137
+ canvas = Canvas(self.width, self.height)
138
+ fill_area(canvas, st, (0, 0, self.width, self.height), st.background)
139
+ margin = 2
140
+ top = margin
141
+ if self._suptitle:
142
+ font = st.get_font()
143
+ text = st.text(self._suptitle)
144
+ shadow = st.color(st.text_shadow) if st.text_shadow is not None else None
145
+ canvas.text(self.width // 2, top + 1, text, font,
146
+ st.color(st.title_color, st.foreground), "center", "top", shadow=shadow)
147
+ top += font.measure(text)[1] + 3
148
+ area = (margin, top, self.width - margin, self.height - margin)
149
+ for ax in self.axes:
150
+ ax.render(canvas, self._cell(ax, area))
151
+ return canvas
152
+
153
+ def to_array(self, scale: int | None = None,
154
+ size: tuple[int, int] | None = None) -> np.ndarray:
155
+ """Return the rendered figure as an ``(H, W, 3)`` uint8 array.
156
+
157
+ ``size`` renders at a different logical ``(width, height)`` (see :meth:`render`).
158
+ """
159
+ return self.render(size).to_array(scale or 1)
160
+
161
+ def to_image(self, scale: int | None = None, scanlines: bool = False):
162
+ """Return a :class:`PIL.Image.Image` upscaled with nearest-neighbour."""
163
+ from PIL import Image
164
+
165
+ s = scale or self.scale
166
+ arr = self.render().to_array(s)
167
+ if scanlines and s >= 2:
168
+ arr = apply_scanlines(arr, s)
169
+ return Image.fromarray(arr, "RGB")
170
+
171
+ def save(self, path: str | os.PathLike | Any, scale: int | None = None,
172
+ scanlines: bool = False, **kwargs) -> None:
173
+ """Save to an image file (format from the extension; PNG recommended).
174
+
175
+ ``scanlines=True`` darkens every ``scale``-th row for a CRT look.
176
+ """
177
+ img = self.to_image(scale, scanlines)
178
+ img.save(path, **kwargs)
179
+
180
+ savefig = save
181
+
182
+ def _repr_png_(self) -> bytes:
183
+ buf = io.BytesIO()
184
+ self.to_image().save(buf, format="PNG")
185
+ return buf.getvalue()
186
+
187
+ def to_sixel(self, scale: int | None = None, scanlines: bool = False) -> str:
188
+ """Return the figure as a sixel escape sequence; ``print()`` it in a sixel terminal."""
189
+ from .sixel import encode
190
+
191
+ return encode(self.to_image(scale, scanlines))
192
+
193
+ def show(self, scale: int | None = None, backend: str = "auto",
194
+ scanlines: bool = False) -> None:
195
+ """Display the figure.
196
+
197
+ ``backend`` is ``"inline"`` (Jupyter), ``"sixel"`` (graphics in the terminal),
198
+ ``"viewer"`` (the system image viewer) or ``"auto"``, which picks the first of those
199
+ that is available. Sixel output is used when stdout is a terminal that reports sixel
200
+ support; set ``PIXELPLOTLIB_SIXEL=1`` (or ``0``) to force it on (or off).
201
+ """
202
+ if backend not in ("auto", "inline", "sixel", "viewer"):
203
+ raise ValueError(f"unknown backend {backend!r}")
204
+ img = self.to_image(scale, scanlines)
205
+ if backend in ("auto", "inline") and _show_inline(img):
206
+ return
207
+ if backend == "inline":
208
+ raise RuntimeError("inline display requires a running IPython kernel")
209
+ if backend == "sixel" or backend == "auto" and _sixel_available():
210
+ from .sixel import write
211
+
212
+ write(img)
213
+ return
214
+ img.show()
215
+
216
+ def __rich_console__(self, console, options):
217
+ from .rich import Plot
218
+
219
+ yield Plot(self)
220
+
221
+ def __rich_measure__(self, console, options):
222
+ from .rich import Plot
223
+
224
+ return Plot(self).__rich_measure__(console, options)
225
+
226
+ def __repr__(self) -> str:
227
+ return (f"<Figure {self.width}x{self.height} style={self.style.name!r} "
228
+ f"axes={len(self.axes)}>")
229
+
230
+
231
+ def _show_inline(img) -> bool:
232
+ """Display ``img`` in a running IPython kernel; return ``False`` if there is none."""
233
+ try:
234
+ from IPython import get_ipython
235
+ from IPython.display import Image as IPImage
236
+ from IPython.display import display
237
+ except ImportError:
238
+ return False
239
+ ip = get_ipython()
240
+ if ip is None or getattr(ip, "kernel", None) is None:
241
+ return False
242
+ buf = io.BytesIO()
243
+ img.save(buf, format="PNG")
244
+ display(IPImage(data=buf.getvalue()))
245
+ return True
246
+
247
+
248
+ def _sixel_available() -> bool:
249
+ from .sixel import terminal_supports_sixel
250
+
251
+ return terminal_supports_sixel()
252
+
253
+
254
+ def apply_scanlines(arr: np.ndarray, scale: int, strength: float = 0.35) -> np.ndarray:
255
+ """Darken the last row of every ``scale``-tall pixel row (CRT effect)."""
256
+ out = arr.copy()
257
+ rows = np.arange(out.shape[0]) % scale == scale - 1
258
+ out[rows] = (out[rows].astype(np.float32) * (1 - strength)).astype(np.uint8)
259
+ return out