From 4da5d9a7ef2bad9b9f07f9942aed2bca2d2d81a3 Mon Sep 17 00:00:00 2001 From: Wessel van Nierop <40076995+wesselvannierop@users.noreply.github.com> Date: Tue, 3 Nov 2026 09:54:01 +0100 Subject: [PATCH 1/2] Allow non-looping GIFs and keep exact colors in the shared palette save_to_gif gains a loop argument (None writes no loop extension). Palette entries are the mean of the colors in a bin instead of its center, so pure black stays black. --- tests/test_io_lib.py | 42 +++++++++++++++++++++++++++++++++++++++++- zea/io_lib.py | 34 +++++++++++++++++++++++----------- 2 files changed, 64 insertions(+), 12 deletions(-) diff --git a/tests/test_io_lib.py b/tests/test_io_lib.py index 9abee0889..3ca63808a 100644 --- a/tests/test_io_lib.py +++ b/tests/test_io_lib.py @@ -4,7 +4,14 @@ import pytest from PIL import Image -from zea.io_lib import load_image, load_video, save_image, save_video +from zea.io_lib import ( + compute_global_palette_by_histogram, + load_image, + load_video, + save_image, + save_to_gif, + save_video, +) from . import DEFAULT_TEST_SEED @@ -253,6 +260,39 @@ def test_color_palette(tmp_path): assert loaded_with_palette_gif.shape == (n_frames, height, width) +def test_global_palette_keeps_exact_colors(): + """A histogram bin holding a single color is represented by exactly that color. + + The palette entry is the mean of the colors in the bin, not the bin's center: a + center would round pure black to (4, 4, 4) at the default 5 bits per channel, + which is visibly not black wherever a plot's background is meant to be. + """ + colors = np.array([[0, 0, 0], [255, 255, 255], [130, 40, 200]], dtype=np.uint8) + image = Image.fromarray(np.repeat(colors[None], 4, axis=0)) + + palette = compute_global_palette_by_histogram([image], bits_per_channel=5) + entries = np.array(palette.getpalette(), dtype=np.uint8).reshape(-1, 3) + + for color in colors: + assert (entries == color).all(axis=1).any(), f"{color} is not in the palette" + + +def test_save_to_gif_keeps_black_black(tmp_path): + """A black background survives the shared-palette quantization as exactly 0.""" + rng = np.random.default_rng(DEFAULT_TEST_SEED) + frames = np.zeros((4, 16, 16, 3), dtype=np.uint8) + # Something for the palette to spend its other entries on, so black is not the + # only color and has to survive alongside the rest. + frames[:, 4:12, 4:12] = rng.integers(0, 255, (4, 8, 8, 3), dtype=np.uint8) + + path = tmp_path / "black_background.gif" + save_to_gif(frames, path, fps=10, shared_color_palette=True) + + loaded = load_video(path, mode="RGB") + background = np.concatenate([loaded[:, :4].ravel(), loaded[:, 12:].ravel()]) + assert background.max() == 0 + + def test_animate_images_parameters_without_extent(tmp_path): """animate_images must not raise AttributeError when the parameters object has no extent_imshow attribute (e.g. a minimal or mock Parameters object).""" diff --git a/zea/io_lib.py b/zea/io_lib.py index a0159c745..3c76fdbbc 100644 --- a/zea/io_lib.py +++ b/zea/io_lib.py @@ -179,7 +179,7 @@ def save_video(images, filename, fps=20, **kwargs): raise ValueError(f"Unsupported file extension: {ext}") -def save_to_gif(images, filename, fps=20, shared_color_palette=True, transparent=False): +def save_to_gif(images, filename, fps=20, shared_color_palette=True, transparent=False, loop=0): """Saves a sequence of images to a GIF file. .. note:: @@ -198,6 +198,9 @@ def save_to_gif(images, filename, fps=20, shared_color_palette=True, transparent throughout the GIF. Defaults to True, which is default behavior of PIL.Image.save. Note: True increases speed and shrinks file size for longer sequences. + loop (int, optional): Number of times to repeat after the first play. + Defaults to 0, which loops forever. Pass None to write no loop + extension at all, so the GIF plays once and stops on the last frame. transparent (bool, optional): If True, keeps the alpha channel of RGBA images as GIF transparency. GIF only supports binary transparency, so pixels with alpha < 128 become fully transparent and all others @@ -256,15 +259,18 @@ def save_to_gif(images, filename, fps=20, shared_color_palette=True, transparent pillow_img, *pillow_imgs = pillow_imgs + # Pillow only omits the Netscape loop extension when `loop` is absent entirely + loop_kwarg = {} if loop is None else {"loop": loop} + pillow_img.save( fp=filename, format="GIF", append_images=pillow_imgs, save_all=True, - loop=0, duration=duration, interlace=False, optimize=False, + **loop_kwarg, **transparency_kwargs, ) log.success(f"Successfully saved GIF to -> {log.yellow(filename)}") @@ -428,6 +434,8 @@ def compute_global_palette_by_histogram(pillow_imgs, bits_per_channel=5, palette total_bins = bins_per**3 # counts per bin in the final histogram counts = np.zeros(total_bins, dtype=np.int64) + # per-bin sum of the colors that landed in it, to average into its entry + sums = np.zeros((total_bins, 3), dtype=np.int64) shift = 8 - bits_per_channel # Iterate images, accumulate bin counts @@ -441,6 +449,10 @@ def compute_global_palette_by_histogram(pillow_imgs, bits_per_channel=5, palette # accumulate counts bincount = np.bincount(idx, minlength=total_bins) counts += bincount + for channel in range(3): + sums[:, channel] += np.bincount( + idx, weights=arr[:, channel], minlength=total_bins + ).astype(np.int64) # pick top bins top_idx = np.argpartition(-counts, palette_size - 1)[:palette_size] @@ -448,16 +460,16 @@ def compute_global_palette_by_histogram(pillow_imgs, bits_per_channel=5, palette # sort top bins by frequency top_idx = top_idx[np.argsort(-counts[top_idx])] - # convert bin index back to representative RGB (center of bin) - bins = np.array( - [((i // (bins_per * bins_per)), (i // bins_per) % bins_per, i % bins_per) for i in top_idx] + # Represent each bin by the mean of the colors in it, not by the bin's center: a + # bin holding one exact color is then reproduced exactly, which matters most for + # the flat backgrounds that dominate plots -- a pure black one quantized to the + # center of its bin comes out a visibly non-black (4, 4, 4). + occupied = counts[top_idx] > 0 + mean = np.zeros((len(top_idx), 3), dtype=np.uint8) + mean[occupied] = np.round(sums[top_idx][occupied] / counts[top_idx][occupied, None]).astype( + np.uint8 ) - - # expand bin centers back to 8-bit values - center = ( - (bins * (1 << (8 - bits_per_channel)) + (1 << (7 - bits_per_channel))).clip(0, 255) - ).astype(np.uint8) - palette_colors = center.reshape(-1, 3) # shape (k,3) + palette_colors = mean.reshape(-1, 3) # shape (k,3) # build a PIL 'P' palette image from these colors pal = np.zeros(768, dtype=np.uint8) # 256*3 entries From a6b58cb5711248b59dc4a812ec113d0ece1bfddd Mon Sep 17 00:00:00 2001 From: Wessel van Nierop <40076995+wesselvannierop@users.noreply.github.com> Date: Tue, 3 Nov 2026 11:24:59 +0100 Subject: [PATCH 2/2] Simplify palette comments and tighten GIF palette tests --- tests/test_io_lib.py | 20 +++++++------------- zea/io_lib.py | 16 ++++++---------- 2 files changed, 13 insertions(+), 23 deletions(-) diff --git a/tests/test_io_lib.py b/tests/test_io_lib.py index 3ca63808a..04247ce97 100644 --- a/tests/test_io_lib.py +++ b/tests/test_io_lib.py @@ -261,28 +261,21 @@ def test_color_palette(tmp_path): def test_global_palette_keeps_exact_colors(): - """A histogram bin holding a single color is represented by exactly that color. - - The palette entry is the mean of the colors in the bin, not the bin's center: a - center would round pure black to (4, 4, 4) at the default 5 bits per channel, - which is visibly not black wherever a plot's background is meant to be. - """ + """A histogram bin holding a single color is represented by exactly that color.""" colors = np.array([[0, 0, 0], [255, 255, 255], [130, 40, 200]], dtype=np.uint8) image = Image.fromarray(np.repeat(colors[None], 4, axis=0)) - palette = compute_global_palette_by_histogram([image], bits_per_channel=5) - entries = np.array(palette.getpalette(), dtype=np.uint8).reshape(-1, 3) + palette = compute_global_palette_by_histogram([image], bits_per_channel=5, palette_size=3) + entries = np.array(palette.getpalette(), dtype=np.uint8).reshape(-1, 3)[:3] - for color in colors: - assert (entries == color).all(axis=1).any(), f"{color} is not in the palette" + assert set(map(tuple, entries.tolist())) == set(map(tuple, colors.tolist())) def test_save_to_gif_keeps_black_black(tmp_path): - """A black background survives the shared-palette quantization as exactly 0.""" + """A black background stays exactly black with a shared color palette.""" rng = np.random.default_rng(DEFAULT_TEST_SEED) frames = np.zeros((4, 16, 16, 3), dtype=np.uint8) - # Something for the palette to spend its other entries on, so black is not the - # only color and has to survive alongside the rest. + # random foreground so black is not the only color frames[:, 4:12, 4:12] = rng.integers(0, 255, (4, 8, 8, 3), dtype=np.uint8) path = tmp_path / "black_background.gif" @@ -291,6 +284,7 @@ def test_save_to_gif_keeps_black_black(tmp_path): loaded = load_video(path, mode="RGB") background = np.concatenate([loaded[:, :4].ravel(), loaded[:, 12:].ravel()]) assert background.max() == 0 + assert loaded[:, 4:12, 4:12].max() > 0 def test_animate_images_parameters_without_extent(tmp_path): diff --git a/zea/io_lib.py b/zea/io_lib.py index 3c76fdbbc..1dfb1b538 100644 --- a/zea/io_lib.py +++ b/zea/io_lib.py @@ -434,7 +434,7 @@ def compute_global_palette_by_histogram(pillow_imgs, bits_per_channel=5, palette total_bins = bins_per**3 # counts per bin in the final histogram counts = np.zeros(total_bins, dtype=np.int64) - # per-bin sum of the colors that landed in it, to average into its entry + # sum of the colors per bin sums = np.zeros((total_bins, 3), dtype=np.int64) shift = 8 - bits_per_channel @@ -460,16 +460,12 @@ def compute_global_palette_by_histogram(pillow_imgs, bits_per_channel=5, palette # sort top bins by frequency top_idx = top_idx[np.argsort(-counts[top_idx])] - # Represent each bin by the mean of the colors in it, not by the bin's center: a - # bin holding one exact color is then reproduced exactly, which matters most for - # the flat backgrounds that dominate plots -- a pure black one quantized to the - # center of its bin comes out a visibly non-black (4, 4, 4). + # represent each bin by the mean color in it, so exact colors are preserved occupied = counts[top_idx] > 0 - mean = np.zeros((len(top_idx), 3), dtype=np.uint8) - mean[occupied] = np.round(sums[top_idx][occupied] / counts[top_idx][occupied, None]).astype( - np.uint8 - ) - palette_colors = mean.reshape(-1, 3) # shape (k,3) + palette_colors = np.zeros((len(top_idx), 3), dtype=np.uint8) # shape (k,3) + palette_colors[occupied] = np.round( + sums[top_idx][occupied] / counts[top_idx][occupied, None] + ).astype(np.uint8) # build a PIL 'P' palette image from these colors pal = np.zeros(768, dtype=np.uint8) # 256*3 entries