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
6 changes: 6 additions & 0 deletions Tests/test_imagestat.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,9 @@ def test_zero_count() -> None:
assert st.mean == [0]
assert st.rms == [0]
assert st.var == [0]


def test_variance_rounding() -> None:
im = Image.new("L", (919, 405), 255)
st = ImageStat.Stat(im)
assert st.var == [0.0]
6 changes: 6 additions & 0 deletions docs/releasenotes/13.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -139,3 +139,9 @@ Fixed ImageChops.offset() for 16-bit images
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

:py:meth:`~PIL.ImageChops.offset` now works correctly for 16-bit-per-channel images.

Fixed ImageStat variance rounding
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Fixed a floating-point rounding error that may have produced a negative variance in
:py:attr:`~PIL.ImageStat.Stat.var`.
12 changes: 6 additions & 6 deletions src/PIL/ImageStat.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,26 +96,26 @@ def count(self) -> list[int]:
return [sum(self.h[i : i + 256]) for i in range(0, len(self.h), 256)]

@cached_property
def sum(self) -> list[float]:
def sum(self) -> list[int]:
"""Sum of all pixels for each band in the image."""

v = []
for i in range(0, len(self.h), 256):
layer_sum = 0.0
layer_sum = 0
for j in range(256):
layer_sum += j * self.h[i + j]
v.append(layer_sum)
return v

@cached_property
def sum2(self) -> list[float]:
def sum2(self) -> list[int]:
"""Squared sum of all pixels for each band in the image."""

v = []
for i in range(0, len(self.h), 256):
sum2 = 0.0
sum2 = 0
for j in range(256):
sum2 += (j**2) * float(self.h[i + j])
sum2 += (j**2) * self.h[i + j]
v.append(sum2)
return v

Expand Down Expand Up @@ -153,7 +153,7 @@ 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) / self.count[i]) / self.count[i]
if self.count[i]
else 0
)
Expand Down