From 6a97bf1646d17750188b45f70bae5390ef0fa37f Mon Sep 17 00:00:00 2001 From: Rodrigo-Palma Date: Sat, 24 Oct 2026 10:42:38 -0300 Subject: [PATCH 1/2] Return zero median from ImageStat when there are no pixels --- Tests/test_imagestat.py | 1 + src/PIL/ImageStat.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Tests/test_imagestat.py b/Tests/test_imagestat.py index 47e534696aa..014b642a632 100644 --- a/Tests/test_imagestat.py +++ b/Tests/test_imagestat.py @@ -65,6 +65,7 @@ def test_zero_count() -> None: st = ImageStat.Stat(im) assert st.mean == [0] + assert st.median == [0] assert st.rms == [0] assert st.var == [0] diff --git a/src/PIL/ImageStat.py b/src/PIL/ImageStat.py index 769c035b79b..d003eb35b57 100644 --- a/src/PIL/ImageStat.py +++ b/src/PIL/ImageStat.py @@ -137,7 +137,7 @@ def median(self) -> list[int]: s = s + self.h[b + j] if s > half: break - v.append(j) + v.append(j if self.count[i] else 0) return v @cached_property From a997f2897b936aa264727115022156f0464c66af Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sun, 25 Oct 2026 01:11:15 +1100 Subject: [PATCH 2/2] Do not run all of range(256) loop --- src/PIL/ImageStat.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/PIL/ImageStat.py b/src/PIL/ImageStat.py index d003eb35b57..2f818adc937 100644 --- a/src/PIL/ImageStat.py +++ b/src/PIL/ImageStat.py @@ -131,13 +131,13 @@ def median(self) -> list[int]: v = [] for i in self.bands: s = 0 - half = self.count[i] // 2 + half = self.count[i] // 2 if self.count[i] else -1 b = i * 256 for j in range(256): s = s + self.h[b + j] if s > half: break - v.append(j if self.count[i] else 0) + v.append(j) return v @cached_property