Skip to content

Commit

Permalink
Merge pull request #7891 from radarhere/kmeans
Browse files Browse the repository at this point in the history
Raise ValueError if kmeans is negative
  • Loading branch information
mergify[bot] authored Mar 22, 2024
2 parents 0c73db3 + 47040c7 commit 759630f
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
13 changes: 13 additions & 0 deletions Tests/test_image_quantize.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,19 @@ def test_quantize_dither_diff() -> None:
assert dither.tobytes() != nodither.tobytes()


@pytest.mark.parametrize(
"method", (Image.Quantize.MEDIANCUT, Image.Quantize.MAXCOVERAGE)
)
def test_quantize_kmeans(method) -> None:
im = hopper()
no_kmeans = im.quantize(kmeans=0, method=method)
kmeans = im.quantize(kmeans=1, method=method)
assert kmeans.tobytes() != no_kmeans.tobytes()

with pytest.raises(ValueError):
im.quantize(kmeans=-1, method=method)


def test_colors() -> None:
im = hopper()
colors = 2
Expand Down
6 changes: 5 additions & 1 deletion src/PIL/Image.py
Original file line number Diff line number Diff line change
Expand Up @@ -1141,7 +1141,7 @@ def quantize(
The exception to this is RGBA images. :data:`Quantize.MEDIANCUT`
and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so
:data:`Quantize.FASTOCTREE` is used by default instead.
:param kmeans: Integer
:param kmeans: Integer greater than or equal to zero.
:param palette: Quantize to the palette of given
:py:class:`PIL.Image.Image`.
:param dither: Dithering method, used when converting from
Expand Down Expand Up @@ -1184,6 +1184,10 @@ def quantize(
new_im.palette = palette.palette.copy()
return new_im

if kmeans < 0:
msg = "kmeans must not be negative"
raise ValueError(msg)

im = self._new(self.im.quantize(colors, method, kmeans))

from . import ImagePalette
Expand Down
4 changes: 2 additions & 2 deletions src/libImaging/Quant.c
Original file line number Diff line number Diff line change
Expand Up @@ -1471,7 +1471,7 @@ quantize(
fflush(stdout);
timer = clock();
#endif
if (kmeans) {
if (kmeans > 0) {
k_means(pixelData, nPixels, p, nPaletteEntries, qp, kmeans - 1);
}
#ifndef NO_OUTPUT
Expand Down Expand Up @@ -1627,7 +1627,7 @@ quantize2(
pixelData, nPixels, p, nQuantPixels, avgDist, avgDistSortKey, qp)) {
goto error_4;
}
if (kmeans) {
if (kmeans > 0) {
k_means(pixelData, nPixels, p, nQuantPixels, qp, kmeans - 1);
}

Expand Down

0 comments on commit 759630f

Please sign in to comment.