.convert()
Published Jun 7, 2024
Contribute to Docs
In the Pillow library, the .convert()
method converts an image from one mode to another, allowing for efficient processing and manipulation of the image. Here, mode refers to the way the image data is stored and interpreted.
Converting an image to a different mode can be useful for various purposes, such as changing the color space, reducing the number of channels, or converting to a format that is more suitable for a specific operation.
Syntax
Image.convert(mode=None, matrix=None, dither=None, palette=0, ...)
Image
: The image object to be converted.mode
: The string that represents the mode to which the image is to be converted. The available modes depend on the image type and the version of the library being used.matrix
: An optional conversion matrix for color space transformations.dither
: Specifies the dithering method to use during conversion from modeRGB
toP
or fromRGB
orL
to1
. The default isNone
. This parameter is not used when amatrix
is provided.palette
: The palette used when converting from modeRGB
toP
.
Note: The ellipsis (…) indicates that there can be additional optional parameters beyond those listed here.
The most common modes include:
L
: 8-bit grayscale, suitable for black and white images.RGB
: 24-bit true color, ideal for full-color images.RGBA
: 32-bit true color with transparency, for smooth blending.CMYK
: 32-bit color separation, used in printing.YCbCr
: 24-bit color video format, commonly used in video encoding.I
: 32-bit signed integer, provides high precision.F
: 32-bit floating point, offers accuracy and a wide dynamic range.
Example
In this example, the .convert()
method uses the L
mode to convert an image to grayscale:
from PIL import Image# Opening an image fileimage = Image.open("example.jpg")# Converting the image to grayscaleconverted_image = image.convert("L")# Saving the grayscale imageconverted_image.save("example_grayscale.jpg")# Displaying the image modeprint("Mode of the converted image:", converted_image.mode)# Displaying the imagesprint("Original Image:")image.show()print("Converted Image:")converted_image.show()
The above code produces the following output:
Mode of the converted image: L
Original Image:
Converted Image:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.