Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Tests/test_imagestat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
13 changes: 10 additions & 3 deletions src/PIL/ImageStat.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ def sum2(self) -> list[float]:
@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]:
Expand All @@ -141,13 +141,20 @@ def median(self) -> list[int]:
@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
]

Expand Down
Loading