'Convert the image to \'P\' mode with the specified number
of colors.
:param colors: The desired number of colors, <= 256
:param method: 0 = median cut
1 = maximum coverage
2 = fast octree
3 = libimagequant
:param kmeans: Integer
:param palette: Quantize to the :py:class:`PIL.ImagingPalette` palette.
:returns: A new image'

def quantize(self, colors=256, method=None, kmeans=0, palette=None):

    self.load()
    if (method is None):
        method = 0
        if (self.mode == 'RGBA'):
            method = 2
    if ((self.mode == 'RGBA') and (method not in (2, 3))):
        raise ValueError(('Fast    Octree    (method    ==    2)    and    libimagequant    (method    ==    3)    ' + 'are    the    only    valid    methods    for    quantizing    RGBA    images'))
    if palette:
        palette.load()
        if (palette.mode != 'P'):
            raise ValueError('bad    mode    for    palette    image')
        if ((self.mode != 'RGB') and (self.mode != 'L')):
            raise ValueError('only    RGB    or    L    mode    images    can    be    quantized    to    a    palette')
        im = self.im.convert('P', 1, palette.im)
        return self._new(im)
    return self._new(self.im.quantize(colors, method, kmeans))
