![]() |
VOOZH | about |
In this article, we will learn Colors on an Image using the Pillow module in Python. Let's discuss some concepts:
ImageColor module that contains various formats of representing colors. These formats are as follows:
Here, we will create Images with colors using Image.new() method.
PIL.Image.new() method creates a new image with the given mode and size. Size is given as a (width, height)-tuple, in pixels. The color is given as a single value for single-band images, and a tuple for multi-band images (with one value for each band). We can also use color names. If the color argument is omitted, the image is filled with zero (this usually corresponds to black). If the color is None, the image is not initialized. This can be useful if youβre going to paste or draw things in the image.
Syntax:
PIL.Image.new(mode, size, color)Parameters:
- mode: The mode to use for the new image. (It could be RGB, RGBA)
- size: A 2-tuple containing (width, height) in pixels.
- color: What color to use for the image. Default is black. If given, this should be a single integer or floating point value for single-band modes, and a tuple for multi-band modes.
Return Value: An Image object.
Output:
Using the ImageColor module, we can also convert colors to RGB format(RGB tuple) as RGB is very convenient to perform different operations. To do this we will use ImageColor.getgrb() method. The ImageColor.getrgb() Convert a color string to an RGB tuple. If the string cannot be parsed, this function raises a ValueError exception.
Syntax:
PIL.ImageColor.getrgb(color)Parameters:
- color: A color string
Returns: (red, green, blue[, alpha])
Output:
(255, 255, 0) (255, 0, 0)
The ImageColor.getcolor() Same as getrgb(), but converts the RGB value to a grayscale value if the mode is not color or a palette image. If the string cannot be parsed, this function raises a ValueError exception.
Syntax:
PIL.ImageColor.getcolor(color, mode)Parameters:
- color β A color string
Returns: (graylevel [, alpha]) or (red, green, blue[, alpha])
Output:
226 76
We can also change the color of an image to some other color.
Input Image:
Example:
Output: