Python Pillow Colors on an Image (original) (raw)

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:

Creating Images with colors

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:

Return Value: An Image object.

Python3 `

from PIL import Image

color --> "red" or (255,0,0) or #ff0000

img = Image.new('RGB',(200,200),(255,0,0)) img.show()

`

Output:

Converting color string to RGB Color values

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 useImageColor.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:

Returns: (red, green, blue[, alpha])

Python3 `

importing module

from PIL import ImageColor

using getrgb for yellow

img1 = ImageColor.getrgb("yellow") print(img1)

using getrgb for red

img2 = ImageColor.getrgb("red") print(img2)

`

Output:

(255, 255, 0) (255, 0, 0)

Converting color string to Grayscale values

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:

Returns: (graylevel [, alpha]) or (red, green, blue[, alpha])

Python3 `

importing module

from PIL import ImageColor

using getrgb for yellow

img1 = ImageColor.getcolor("yellow",'L') print(img1)

using getrgb for red

img2 = ImageColor.getcolor("red",'L') print(img2)

`

Output:

226 76

Change the color by changing the pixel values

We can also change the color of an image to some other color.

Input Image:

Example:

Python3 `

from PIL import Image

img = Image.open("flower.jpg") img = img.convert("RGB")

d = img.getdata()

new_image = [] for item in d:

# change all white (also shades of whites)
# pixels to yellow
if item[0] in list(range(200, 256)):
    new_image.append((255, 224, 100))
else:
    new_image.append(item)

update image data

img.putdata(new_image)

save new image

img.save("flower_image_altered.jpg")

`