diff --git a/Tests/test_imagestat.py b/Tests/test_imagestat.py index 0dfbc5a2a..0baab7ce2 100644 --- a/Tests/test_imagestat.py +++ b/Tests/test_imagestat.py @@ -57,3 +57,13 @@ def test_constant() -> None: assert st.rms[0] == 128 assert st.var[0] == 0 assert st.stddev[0] == 0 + + +def test_zero_count() -> None: + im = Image.new("L", (0, 0)) + + st = ImageStat.Stat(im) + + assert st.mean == [0] + assert st.rms == [0] + assert st.var == [0] diff --git a/src/PIL/ImageStat.py b/src/PIL/ImageStat.py index 8bc504526..3a1044ba4 100644 --- a/src/PIL/ImageStat.py +++ b/src/PIL/ImageStat.py @@ -120,7 +120,7 @@ class Stat: @cached_property def mean(self) -> list[float]: """Average (arithmetic mean) pixel level for each band in the image.""" - return [self.sum[i] / self.count[i] for i in self.bands] + return [self.sum[i] / self.count[i] if self.count[i] else 0 for i in self.bands] @cached_property def median(self) -> list[int]: @@ -141,13 +141,20 @@ class Stat: @cached_property def rms(self) -> list[float]: """RMS (root-mean-square) for each band in the image.""" - return [math.sqrt(self.sum2[i] / self.count[i]) for i in self.bands] + return [ + math.sqrt(self.sum2[i] / self.count[i]) if self.count[i] else 0 + for i in self.bands + ] @cached_property def var(self) -> list[float]: """Variance for each band in the image.""" return [ - (self.sum2[i] - (self.sum[i] ** 2.0) / self.count[i]) / self.count[i] + ( + (self.sum2[i] - (self.sum[i] ** 2.0) / self.count[i]) / self.count[i] + if self.count[i] + else 0 + ) for i in self.bands ]