Skip to content

Commit 759630f

Browse files
authored
Merge pull request #7891 from radarhere/kmeans
Raise ValueError if kmeans is negative
2 parents 0c73db3 + 47040c7 commit 759630f

File tree

3 files changed

+20
-3
lines changed

3 files changed

+20
-3
lines changed

Tests/test_image_quantize.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,19 @@ def test_quantize_dither_diff() -> None:
9494
assert dither.tobytes() != nodither.tobytes()
9595

9696

97+
@pytest.mark.parametrize(
98+
"method", (Image.Quantize.MEDIANCUT, Image.Quantize.MAXCOVERAGE)
99+
)
100+
def test_quantize_kmeans(method) -> None:
101+
im = hopper()
102+
no_kmeans = im.quantize(kmeans=0, method=method)
103+
kmeans = im.quantize(kmeans=1, method=method)
104+
assert kmeans.tobytes() != no_kmeans.tobytes()
105+
106+
with pytest.raises(ValueError):
107+
im.quantize(kmeans=-1, method=method)
108+
109+
97110
def test_colors() -> None:
98111
im = hopper()
99112
colors = 2

src/PIL/Image.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1141,7 +1141,7 @@ def quantize(
11411141
The exception to this is RGBA images. :data:`Quantize.MEDIANCUT`
11421142
and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so
11431143
:data:`Quantize.FASTOCTREE` is used by default instead.
1144-
:param kmeans: Integer
1144+
:param kmeans: Integer greater than or equal to zero.
11451145
:param palette: Quantize to the palette of given
11461146
:py:class:`PIL.Image.Image`.
11471147
:param dither: Dithering method, used when converting from
@@ -1184,6 +1184,10 @@ def quantize(
11841184
new_im.palette = palette.palette.copy()
11851185
return new_im
11861186

1187+
if kmeans < 0:
1188+
msg = "kmeans must not be negative"
1189+
raise ValueError(msg)
1190+
11871191
im = self._new(self.im.quantize(colors, method, kmeans))
11881192

11891193
from . import ImagePalette

src/libImaging/Quant.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1471,7 +1471,7 @@ quantize(
14711471
fflush(stdout);
14721472
timer = clock();
14731473
#endif
1474-
if (kmeans) {
1474+
if (kmeans > 0) {
14751475
k_means(pixelData, nPixels, p, nPaletteEntries, qp, kmeans - 1);
14761476
}
14771477
#ifndef NO_OUTPUT
@@ -1627,7 +1627,7 @@ quantize2(
16271627
pixelData, nPixels, p, nQuantPixels, avgDist, avgDistSortKey, qp)) {
16281628
goto error_4;
16291629
}
1630-
if (kmeans) {
1630+
if (kmeans > 0) {
16311631
k_means(pixelData, nPixels, p, nQuantPixels, qp, kmeans - 1);
16321632
}
16331633

0 commit comments

Comments
 (0)