Python Pillow – Converting Color String to Grayscale Values


Python Pillow – Converting color string to Grayscale values



”;


The ImageColor.getcolor() function in the Python Pillow (PIL) library is same as the ImageColor.getrgb() which allows us to retrieve the color value of a given color name or hexadecimal code.

Syntax

The following is the syntax and parameters as follows −


ImageColor.getcolor(color, mode)

  • color − This is a string representing the color you want to retrieve the value for. It can be a color name (e.g., “red”, “blue”) or a hexadecimal color code (e.g., “#00FF00”) or other color representations that Pillow supports.

  • mode − This parameter specifies the color mode in which we want to retrieve the color value. The default value is “RGB” which means the color value will be returned as an RGB tuple. We can also specify other modes like “RGBA,” “CMYK,” “HSV” etc., depending on our needs.

Example

In this example we use ImageColor.getcolor() to retrieve the RGB value of the color blue and the RGBA value of the color green in RGBA mode. We can adjust the color and mode parameters to suit our specific requirements.


from PIL import ImageColor

#Get the RGB value of the color "blue"
blue_rgb = ImageColor.getcolor("blue", mode = "RGB")

#Get the RGBA value of the color "green" in RGBA mode
green_rgba = ImageColor.getcolor("green", mode="RGBA")
print("Blue (RGB):", blue_rgb)
print("Green (RGBA):", green_rgba)

Output


Blue (RGB): (0, 0, 255)
Green (RGBA): (0, 128, 0, 255)

Example

Here, in this example we are giving the hexadecimal value as the color string argument to the ImageColor.getcolor() method.


from PIL import ImageColor

#Get the RGB value of the color "blue"
blue_rgb = ImageColor.getcolor("#8A2BE2", mode = "RGB")

#Get the RGBA value of the color "green" in RGBA mode
green_rgba = ImageColor.getcolor("#008000", mode="RGB")
print("Violet (RGB):", blue_rgb)
print("Green (RGB):", green_rgba)

Output


Violet (RGB): (138, 43, 226)
Green (RGB): (0, 128, 0)

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *