Skip to content

Commit 42e3888

Browse files
committed
Fixed ZeroDivisionError
1 parent d560320 commit 42e3888

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

Tests/test_imagestat.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,3 +57,13 @@ def test_constant() -> None:
5757
assert st.rms[0] == 128
5858
assert st.var[0] == 0
5959
assert st.stddev[0] == 0
60+
61+
62+
def test_zero_count() -> None:
63+
im = Image.new("L", (0, 0))
64+
65+
st = ImageStat.Stat(im)
66+
67+
assert st.mean == [0]
68+
assert st.rms == [0]
69+
assert st.var == [0]

src/PIL/ImageStat.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ def sum2(self) -> list[float]:
120120
@cached_property
121121
def mean(self) -> list[float]:
122122
"""Average (arithmetic mean) pixel level for each band in the image."""
123-
return [self.sum[i] / self.count[i] for i in self.bands]
123+
return [self.sum[i] / self.count[i] if self.count[i] else 0 for i in self.bands]
124124

125125
@cached_property
126126
def median(self) -> list[int]:
@@ -141,13 +141,20 @@ def median(self) -> list[int]:
141141
@cached_property
142142
def rms(self) -> list[float]:
143143
"""RMS (root-mean-square) for each band in the image."""
144-
return [math.sqrt(self.sum2[i] / self.count[i]) for i in self.bands]
144+
return [
145+
math.sqrt(self.sum2[i] / self.count[i]) if self.count[i] else 0
146+
for i in self.bands
147+
]
145148

146149
@cached_property
147150
def var(self) -> list[float]:
148151
"""Variance for each band in the image."""
149152
return [
150-
(self.sum2[i] - (self.sum[i] ** 2.0) / self.count[i]) / self.count[i]
153+
(
154+
(self.sum2[i] - (self.sum[i] ** 2.0) / self.count[i]) / self.count[i]
155+
if self.count[i]
156+
else 0
157+
)
151158
for i in self.bands
152159
]
153160

0 commit comments

Comments
 (0)