From 1795abb992226b74b4d3426bf688856808f4abd5 Mon Sep 17 00:00:00 2001 From: cneuralnetwork Date: Tue, 3 Nov 2026 10:13:19 +0530 Subject: [PATCH 1/2] Use a sliding histogram for 8-bit rank filters Median, min, max and other rank filters on 8-bit images copied the whole size x size window for every output pixel and ran a quickselect on it, costing O(size^2) per pixel. Keep a 256-bin histogram per row instead and update it as the window slides right: one column out, one column in, O(size) per pixel. The output value is tracked with a running count of samples below it, which moves only slightly between neighbouring pixels. Output is byte-identical. On a 1024x1024 L image (Apple M5): MedianFilter(3) 0.102s -> 0.031s MedianFilter(7) 0.724s -> 0.030s MedianFilter(15) 2.868s -> 0.036s MedianFilter(31) 11.434s -> 0.045s INT32 and FLOAT32 images keep the quickselect path. Co-Authored-By: Claude Opus 5.5 --- Tests/test_image_filter.py | 28 ++++++++++++++++++ src/libImaging/RankFilter.c | 57 +++++++++++++++++++++++++++++++++++-- 2 files changed, 83 insertions(+), 2 deletions(-) diff --git a/Tests/test_image_filter.py b/Tests/test_image_filter.py index 5f5eb302cd6..4f8cc82f3d5 100644 --- a/Tests/test_image_filter.py +++ b/Tests/test_image_filter.py @@ -141,6 +141,34 @@ def test_rankfilter( assert (minimum, med, maximum) == expected +@pytest.mark.parametrize("size", (1, 3, 5, 9, 25)) +def test_rankfilter_l_matches_reference(size: int) -> None: + # Compare the 8-bit fast path against a brute-force rank on edge-padded windows + xsize, ysize = 23, 17 + data = [ + (x * 37 + y * 101 + (x * y) % 13) % 256 + for y in range(ysize) + for x in range(xsize) + ] + im = Image.new("L", (xsize, ysize)) + im.putdata(data) + margin = size // 2 + + for rank in {0, size * size // 2, size * size - 1}: + result = im.filter(ImageFilter.RankFilter(size, rank)) + for y in range(ysize): + for x in range(xsize): + window = sorted( + data[ + min(max(y + j, 0), ysize - 1) * xsize + + min(max(x + i, 0), xsize - 1) + ] + for j in range(-margin, margin + 1) + for i in range(-margin, margin + 1) + ) + assert result.getpixel((x, y)) == window[rank] + + @pytest.mark.parametrize( "filter", (ImageFilter.MinFilter, ImageFilter.MedianFilter, ImageFilter.MaxFilter) ) diff --git a/src/libImaging/RankFilter.c b/src/libImaging/RankFilter.c index 5c0a09d877c..d1523b4df59 100644 --- a/src/libImaging/RankFilter.c +++ b/src/libImaging/RankFilter.c @@ -14,6 +14,57 @@ #include "Imaging.h" +/* Sliding histogram rank filter for 8-bit images (Huang, 1979). + Moving the window one pixel to the right removes one column and adds + another, so each step costs O(size) instead of the O(size^2) needed to + copy and select the whole window. "below" counts the window samples + less than v, the current output value, which moves only a little + between neighbouring pixels. */ +static void +RankUINT8(Imaging imOut, Imaging im, int size, int rank) { + int x, y, i, v, below; + int hist[256]; + + if (imOut->xsize <= 0) { + return; + } + + for (y = 0; y < imOut->ysize; y++) { + UINT8 *out = imOut->image8[y]; + UINT8 **in = &im->image8[y]; + + memset(hist, 0, sizeof(hist)); + for (i = 0; i < size; i++) { + for (x = 0; x < size; x++) { + hist[in[i][x]]++; + } + } + v = 0; + below = 0; + while (below + hist[v] <= rank) { + below += hist[v++]; + } + out[0] = (UINT8)v; + + for (x = 1; x < imOut->xsize; x++) { + for (i = 0; i < size; i++) { + UINT8 a = in[i][x - 1]; + UINT8 b = in[i][x + size - 1]; + hist[a]--; + hist[b]++; + below += (b < v) - (a < v); + } + while (below > rank) { + below -= hist[--v]; + } + while (below + hist[v] <= rank) { + below += hist[v++]; + } + out[x] = (UINT8)v; + } + } +} + /* Fast rank algorithm (due to Wirth), based on public domain code by Nicolas Devillard, available at http://ndevilla.free.fr */ @@ -57,7 +108,7 @@ return a[k]; \ } -MakeRankFunction(UINT8) MakeRankFunction(INT32) MakeRankFunction(FLOAT32) +MakeRankFunction(INT32) MakeRankFunction(FLOAT32) Imaging ImagingRankFilter(Imaging im, int size, int rank) { Imaging imOut = NULL; @@ -116,7 +167,9 @@ MakeRankFunction(UINT8) MakeRankFunction(INT32) MakeRankFunction(FLOAT32) } while (0) if (im->image8) { - RANK_BODY(UINT8); + ImagingSectionEnter(&cookie); + RankUINT8(imOut, im, size, rank); + ImagingSectionLeave(&cookie); } else if (im->type == IMAGING_TYPE_INT32) { RANK_BODY(INT32); } else if (im->type == IMAGING_TYPE_FLOAT32) { From f0bc84280051957138b2857e3b425c73fa870958 Mon Sep 17 00:00:00 2001 From: cneuralnetwork Date: Tue, 3 Nov 2026 10:35:30 +0530 Subject: [PATCH 2/2] Split the 8-bit rank filter into smaller functions Break RankUINT8 (cyclomatic complexity 10) into FillHistogram, SlideHistogram, SeekRank and RankRowUINT8, each with a complexity of 3 or less. Move the brute-force reference in the new test into a helper, read pixels with tobytes() so it type-checks, and use get_flattened_data() instead of the deprecated getdata(). Add a release note for the faster rank filters. Output and timings are unchanged. Co-Authored-By: Claude Opus 5.5 --- Tests/test_image_filter.py | 41 ++++++++------- docs/releasenotes/13.1.0.rst | 10 ++++ src/libImaging/RankFilter.c | 96 +++++++++++++++++++++++------------- 3 files changed, 91 insertions(+), 56 deletions(-) diff --git a/Tests/test_image_filter.py b/Tests/test_image_filter.py index 4f8cc82f3d5..e95881b67a2 100644 --- a/Tests/test_image_filter.py +++ b/Tests/test_image_filter.py @@ -141,32 +141,31 @@ def test_rankfilter( assert (minimum, med, maximum) == expected +def reference_rank(im: Image.Image, x: int, y: int, size: int, rank: int) -> int: + # Brute-force rank of the window around (x, y), with edge pixels repeated + margin = size // 2 + data = im.tobytes() + window = [] + for j in range(y - margin, y + margin + 1): + for i in range(x - margin, x + margin + 1): + row = min(max(j, 0), im.height - 1) + column = min(max(i, 0), im.width - 1) + window.append(data[row * im.width + column]) + return sorted(window)[rank] + + @pytest.mark.parametrize("size", (1, 3, 5, 9, 25)) def test_rankfilter_l_matches_reference(size: int) -> None: - # Compare the 8-bit fast path against a brute-force rank on edge-padded windows - xsize, ysize = 23, 17 - data = [ - (x * 37 + y * 101 + (x * y) % 13) % 256 - for y in range(ysize) - for x in range(xsize) - ] - im = Image.new("L", (xsize, ysize)) - im.putdata(data) - margin = size // 2 + im = hopper("L").crop((40, 40, 63, 57)) for rank in {0, size * size // 2, size * size - 1}: result = im.filter(ImageFilter.RankFilter(size, rank)) - for y in range(ysize): - for x in range(xsize): - window = sorted( - data[ - min(max(y + j, 0), ysize - 1) * xsize - + min(max(x + i, 0), xsize - 1) - ] - for j in range(-margin, margin + 1) - for i in range(-margin, margin + 1) - ) - assert result.getpixel((x, y)) == window[rank] + expected = [ + reference_rank(im, x, y, size, rank) + for y in range(im.height) + for x in range(im.width) + ] + assert list(result.get_flattened_data()) == expected @pytest.mark.parametrize( diff --git a/docs/releasenotes/13.1.0.rst b/docs/releasenotes/13.1.0.rst index 9427a607ac1..ffe334e149d 100644 --- a/docs/releasenotes/13.1.0.rst +++ b/docs/releasenotes/13.1.0.rst @@ -49,6 +49,16 @@ TODO Other changes ============= +Faster rank filters for 8-bit images +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:py:class:`~PIL.ImageFilter.RankFilter`, and so +:py:class:`~PIL.ImageFilter.MedianFilter`, :py:class:`~PIL.ImageFilter.MinFilter` +and :py:class:`~PIL.ImageFilter.MaxFilter`, now update a histogram as the window +slides across 8-bit images, instead of selecting from the whole window for every +pixel. The time per pixel now grows with the filter size rather than its square, +so larger filters are many times faster. The output is unchanged. + Writing to read-only images ^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/libImaging/RankFilter.c b/src/libImaging/RankFilter.c index d1523b4df59..f0a64838288 100644 --- a/src/libImaging/RankFilter.c +++ b/src/libImaging/RankFilter.c @@ -20,48 +20,74 @@ copy and select the whole window. "below" counts the window samples less than v, the current output value, which moves only a little between neighbouring pixels. */ + +/* Count the values in the size x size window whose top left is in[0][0] */ static void -RankUINT8(Imaging imOut, Imaging im, int size, int rank) { - int x, y, i, v, below; +FillHistogram(int *hist, UINT8 **in, int size) { + int x, i; + + memset(hist, 0, 256 * sizeof(int)); + for (i = 0; i < size; i++) { + for (x = 0; x < size; x++) { + hist[in[i][x]]++; + } + } +} + +/* Move the window from column x - 1 to column x, and return the change + in the number of samples below v */ +static inline int +SlideHistogram(int *hist, UINT8 **in, int x, int size, int v) { + int i, delta = 0; + + for (i = 0; i < size; i++) { + UINT8 removed = in[i][x - 1]; + UINT8 added = in[i][x + size - 1]; + hist[removed]--; + hist[added]++; + delta += (added < v) - (removed < v); + } + return delta; +} + +/* Starting from v, find the value with exactly rank samples below it, + keeping *below in step */ +static inline int +SeekRank(const int *hist, int rank, int v, int *below) { + while (*below > rank) { + *below -= hist[--v]; + } + while (*below + hist[v] <= rank) { + *below += hist[v++]; + } + return v; +} + +static void +RankRowUINT8(UINT8 *out, UINT8 **in, int xsize, int size, int rank) { + int x, v, below = 0; int hist[256]; + FillHistogram(hist, in, size); + v = SeekRank(hist, rank, 0, &below); + out[0] = (UINT8)v; + + for (x = 1; x < xsize; x++) { + below += SlideHistogram(hist, in, x, size, v); + v = SeekRank(hist, rank, v, &below); + out[x] = (UINT8)v; + } +} + +static void +RankUINT8(Imaging imOut, Imaging im, int size, int rank) { + int y; + if (imOut->xsize <= 0) { return; } - for (y = 0; y < imOut->ysize; y++) { - UINT8 *out = imOut->image8[y]; - UINT8 **in = &im->image8[y]; - - memset(hist, 0, sizeof(hist)); - for (i = 0; i < size; i++) { - for (x = 0; x < size; x++) { - hist[in[i][x]]++; - } - } - v = 0; - below = 0; - while (below + hist[v] <= rank) { - below += hist[v++]; - } - out[0] = (UINT8)v; - - for (x = 1; x < imOut->xsize; x++) { - for (i = 0; i < size; i++) { - UINT8 a = in[i][x - 1]; - UINT8 b = in[i][x + size - 1]; - hist[a]--; - hist[b]++; - below += (b < v) - (a < v); - } - while (below > rank) { - below -= hist[--v]; - } - while (below + hist[v] <= rank) { - below += hist[v++]; - } - out[x] = (UINT8)v; - } + RankRowUINT8(imOut->image8[y], &im->image8[y], imOut->xsize, size, rank); } }