Raise ValueError if kmeans is negative

This commit is contained in:
Andrew Murray 2024-03-22 17:36:04 +11:00
parent ca973709a0
commit 171e497e05
3 changed files with 16 additions and 3 deletions

View File

@ -94,6 +94,15 @@ 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()
with pytest.raises(ValueError):
im.quantize(kmeans=-1, method=method)
def test_colors() -> None:
im = hopper()
colors = 2

View File

@ -1141,7 +1141,7 @@ class Image:
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
@ -1184,6 +1184,10 @@ class Image:
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

View File

@ -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
@ -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);
}