diff --git a/Tests/test_image_filter.py b/Tests/test_image_filter.py index 5f5eb302cd6..e95881b67a2 100644 --- a/Tests/test_image_filter.py +++ b/Tests/test_image_filter.py @@ -141,6 +141,33 @@ 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: + 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)) + 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( "filter", (ImageFilter.MinFilter, ImageFilter.MedianFilter, ImageFilter.MaxFilter) ) 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 5c0a09d877c..f0a64838288 100644 --- a/src/libImaging/RankFilter.c +++ b/src/libImaging/RankFilter.c @@ -14,6 +14,83 @@ #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. */ + +/* Count the values in the size x size window whose top left is in[0][0] */ +static void +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++) { + RankRowUINT8(imOut->image8[y], &im->image8[y], imOut->xsize, size, rank); + } +} + /* Fast rank algorithm (due to Wirth), based on public domain code by Nicolas Devillard, available at http://ndevilla.free.fr */ @@ -57,7 +134,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 +193,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) {