Python Pillow – Converting color string to Grayscale values ”; Previous Next 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) Print Page Previous Next Advertisements ”;
Category: python Pillow
Python Pillow – Changing Image Modes ”; Previous Next What is Changing Image Modes? In Pillow changing image modes refers to the process of converting an image from one color representation to another. Each mode represents a different way of encoding and interpreting color information in an image. Changing image modes is useful for various purposes such as preparing images for specific applications like printing, display or analysis. It allows us to adapt the color representation of an image to better suit our needs. In Pillow the Image class provides a method called convert() that allows us to change the mode of an image. The mode of an image determines the type and depth of pixel values it can contain. The following is the syntax and parameters of the convert() method of the Image class. original_image.convert(mode) Where, original_image This is the source image whose mode we want to change. mode This is a string specifying the desired mode for the new image. The below are the common changing Image modes. L − 8-bit pixels represent black and white RGB − 3×8-bit pixels represent true color RGBA − 4×8-bit pixels represent true color with transparency CMYK − 4×8-bit pixels represent color separation HSV − Hue, saturation, value color space 1 − 1-bit pixels, black and white which stored with one pixel per byte Following is the input image used in all the examples of this chapter. Example In this example we are changing the image mode into black and white by passing the mode argument as L to the convert() method. from PIL import Image #Open an image original_image = Image.open(“Images/rose.jpg”) #Convert the image to grayscale (mode ”L”) grayscale_image = original_image.convert(“L”) #Save the resulting image grayscale_image.save(“output Image/output_grayscale.jpg”) grayscale_image.show() Output Example Here is the another example of changing the image mode to 1 by using the convert() method. from PIL import Image #Open an image original_image = Image.open(“Images/rose.jpg”) #Convert the image to RGBA mode single_image = original_image.convert(“1”) #Save the resulting image single_image.save(“output Image/output_single_image.jpg”) single_image.show() Output Print Page Previous Next Advertisements ”;
Python Pillow – Edge Detection ”; Previous Next Edge detection is the process of identifying these boundaries or contours in an image using mathematical algorithms. The edge detection aims to locate the points in the image where the intensity changes suddenly, which usually corresponds to an edge or a boundary between two regions. In general, an edge defined as a boundary or a contour between two distinct regions in an image. These regions can differ in intensity, color, texture, or any other visual feature. Edges can represent important features in an image, such as object boundaries, shapes, and textures. Edge detection is an essential step in many image-processing applications, such as object recognition, segmentation, tracking, and enhancement. In this tutorial, we will see different approaches to detect edges in an image using the Python pillow library. Applying Edge Detection Filter to an Image Detecting edges in an image can be done by using the ImageFilter.FIND_EDGES filter, which is one of the built-in filter options available in the current version of the Pillow library to detect edges in the image. Following are the steps for detecting the edges in the image − Load the input image using the Image.open() function. Apply the filter() function to the loaded Image object and provide ImageFilter.FIND_EDGES as an argument to the function. The function will return the Output detected edges as a PIL.Image.Image object. Example The following example demonstrates how to use the ImageFilter.FIND_EDGES filter kernel with the filter() method to detect the edges in an image. from PIL import Image, ImageFilter # Open the image image = Image.open(”Images/compass.jpg”) # Apply edge detection filter edges = image.filter(ImageFilter.FIND_EDGES) # Display the original image image.show() # Display the edges-detected image edges.show() Input Image Output Image Output detected edges − Example Here is an example that uses the ImageFilter.FIND_EDGES filter kernel to detect edges in the image. And then it applies ImageFilter.MaxFilter() class to flatten the detected edges. import matplotlib.pyplot as plt from PIL import Image, ImageFilter # Open the image and convert it to grayscale im = Image.open(”Images/compass.jpg”).convert(”L”) # Detect edges edges = im.filter(ImageFilter.FIND_EDGES) # Make fatter edges fatEdges = edges.filter(ImageFilter.MaxFilter) # Make very fat edges veryFatEdges = edges.filter(ImageFilter.MaxFilter(7)) # Create subplots for displaying the images fig, axes = plt.subplots(2, 2, figsize=(12, 10)) ax = axes.ravel() # Original image ax[0].imshow(im, cmap=”gray”) ax[0].set_title(”Original”) # Detected edges ax[1].imshow(edges, cmap=”gray”) ax[1].set_title(”Edges”) # Fatter edges ax[2].imshow(fatEdges, cmap=”gray”) ax[2].set_title(”Fatter Edges”) # Very fat edges ax[3].imshow(veryFatEdges, cmap=”gray”) ax[3].set_title(”Very Fat Edges”) for ax in axes.flatten(): ax.axis(”off”) # Display the images plt.tight_layout() plt.show() Output Image Detecting Edges using the ImageFilter.Kernel() Class This class is used to create a convolution kernel. In this approach we will define a 3X3 convolution kernel with some specified kernel values (-1, -1, -1, -1, 8, -1, -1, -1, -1). We will perform edge detection on an image. Example The following example demonstrates how to perform edge detection on an image using the convolution matrix and the ImageFilter.kernel() class. from PIL import Image, ImageFilter # Open the image and convert it to grayscale image = Image.open(”Images/compass.jpg”).convert(”L”) # Calculate edges using a convolution matrix kernel = ImageFilter.Kernel((3, 3), (-1, -1, -1, -1, 8, -1, -1, -1, -1), scale=1, offset=0) edges = image.filter(kernel) # Display the original image image.show() # Display the edges edges.show() Input Image Output Image Output detected edges − Print Page Previous Next Advertisements ”;
Python Pillow – Reducing Noise ”; Previous Next Reducing noise in Pillow refers to the process of applying various techniques and filters to an image to remove or decrease unwanted artifacts or irregularities that can degrade the image quality. Image noise is random variations in brightness or color in images typically caused by factors such as low light conditions, electronic interference or imperfections in the image sensor. Reducing noise is an important step in image processing to improve the overall quality of images. Pillow (PIL) provides several built-in filters and methods for reducing noise in images. Some common techniques and filters for noise reduction in Pillow include − Gaussian Blur: Applying a Gaussian blur filter to the image can help smooth out reduce noise by averaging the pixel values in the vicinity of each pixel. This creates a smoother appearance and can reduce the impact of noise. The degree of blurring can be adjusted to control the level of noise reduction. Median Filter: Median filtering replaces each pixel”s value with the median value of the neighboring pixels. The median filter is effective for removing salt-and-pepper noise where isolated pixels have extreme values. It replaces each pixel”s value with the median value of neighboring pixels. Bilateral Filter: The bilateral filter smooths the image while preserving edges. It can be effective at reducing noise while maintaining image details. Denoising Algorithms: Pillow supports various denoising algorithms such as the bilateral filter, Total Variation (TV) denoising algorithm or the Non-Local Means (NLMeans) filter which can be used to reduce noise while preserving image details. Thresholding: We can apply a threshold to an image to remove noise by converting pixel values below a certain threshold to black and values above the threshold to white effectively binarizing the image. Python Pillow – Image.filter() Method Image.filter() is a method in the Python Imaging Library (PIL) or its fork. Pillow used to apply various image filters and enhancements to an image. Filters are image processing operations that can be used to modify an image in different ways such as blurring, sharpening or enhancing certain features. This method allows us to apply various predefined filters to an image. Pillow provides a variety of predefined filters that we can use with Image.filter(), including − ImageFilter.BLUR − Applies a simple blur to the image. ImageFilter.CONTOUR − Enhances the contours of objects in the image. ImageFilter.DETAIL − Enhances the image”s details. ImageFilter.EDGE_ENHANCE − Emphasizes the edges in the image. ImageFilter.EMBOSS − Adds a 3D embossing effect to the image. ImageFilter.SHARPEN − Sharpens the image. Syntax The syntax and parameters for using Image.filter() is as follows − output_image = input_image.filter(filter_name, filter_parameters) Where, input_image − This is the source image to which we want to apply the filter. filter_name − This is a string specifying the name of the filter we want to apply. Pillow provides a variety of built-in filters and we can use one of these filter names as a string. For example “GaussianBlur,” “MedianFilter,” “Sharpen”, etc. We can also define our custom filters by providing a kernel (a list of values) as a filter. filter_parameters (optional) − Some filters may accept additional parameters that control the behavior of the filter. These parameters are specific to the particular filter being used. If the filter we are applying requires parameters we would pass them as arguments in the filter_parameters part. Example In this example we are trying to blur the image by passing the ImageFilter.BLUR as the input parameter to the Image.filter() method. from PIL import Image, ImageFilter #Open an image input_image = Image.open(“Images/flowers.jpg”) #Apply Gaussian blur to the image output_image = input_image.filter(ImageFilter.BLUR()) #Save the resulting image output_image.save(“output Image/blur.jpg”) output_image.show() Image to be used Output Example Here in this example we are blurring a specified part of the image by using the ImageFilter.BoxBlur() method. from PIL import Image, ImageFilter #Open an image input_image = Image.open(“Images/rose.jpg”) #Apply Gaussian blur to the image output_image = input_image.filter(ImageFilter.BoxBlur(20)) #Save the resulting image output_image.save(“output Image/blur.jpg”) output_image.show() Image to be used Output Print Page Previous Next Advertisements ”;
Python Pillow – Enhancing Contrast ”; Previous Next Enhancing contrast refers to the process of improving the visibility and quality of an image. It is an image processing technique that involves increasing the difference between the various elements within an image, such as objects, shapes, edges, and textures, by adjusting the distribution of intensity values or colors. This technique is widely used in fields such as medical imaging, computer vision, remote sensing, and photography to improve image quality and obtain more detailed visual information. The Python Pillow (PIL) library offers the Contrast() class within its ImageEnhance module, for the application of contrast enhancement to images. Enhancing Contrast of an Image To adjust the contrast of an image, you can apply ImageEnhance.Contrast() class to an image object with the enhancment factor. It controls the contrast of an image, much like adjusting the contrast on a television set. Below is the syntax of the ImageEnhance.Contrast() class − class PIL.ImageEnhance.Contrast(image) Following are the steps to achieve contrast enhancement of an image − Create a contrast object using the ImageEnhance.Contrast() class. Then apply the enhancement factor with the help of contrast_object.enhance() method. An enhancement factor is a floating-point value passed to the common single interface method, enhance(factor), which plays an important role in adjusting image contrast. When a factor of 0.0 is used, it will produce a solid grey image. A factor of 1.0 will give the original image, and when greater values are used, the contrast of the image is increased, making it visually more distinct. Example The following example demonstrates how to achieve a highly contrasted image using the PIL.ImageEnhance module. from PIL import Image, ImageEnhance # Open the input image image = Image.open(”Images/flowers.jpg”) # Create an ImageEnhance object for adjusting contrast enhancer = ImageEnhance.Contrast(image) # Display the original image image.show() # Enhance the contrast by a factor of 2 and display the result enhancer.enhance(2).show() Input Image Output Image Output a highly contrasted version of the input image − Example To reduce the contrast of an image, you can use a contrast enhancement factor less than 1. Here”s an example illustrating the creation of a low-contrast version of the input image using the PIL.ImageEnhance.Contrast class. from PIL import Image, ImageEnhance # Open the input image image = Image.open(”Images/flowers.jpg”) # Create an ImageEnhance object for adjusting contrast enhancer = ImageEnhance.Contrast(image) # Display the original image image.show() # Reduce the contrast by a factor of 0.5 and display the result enhancer.enhance(0.5).show() Input Image Output Image Output a low contrasted version of the input image − Print Page Previous Next Advertisements ”;
Python Pillow – Applying Perspective Transforms ”; Previous Next In Pillow applying perspective transforms involves altering the perspective or viewpoint of an image. This transformation modifies the position of the image”s points in a way that simulates a change in perspective such as rotating, skewing or distorting the image. Perspective Transformation in Pillow The Pillow”s transform() method allows you to apply differenyt types of transformations to an image. For perspective transforms a 3×3 transformation matrix is used to define the transformation. This matrix can represent operations like rotations, translations, scaling and shearing. For perspective transformation the matrix elements control how each pixel”s coordinates change. Matrix Elements for Perspective Transform The matrix elements (a, b, c, d, e, f, g, h) define the transformation − a and d represent scaling in the x and y directions. b and c represent shearing or skewing. e and f are translations along the x and y axes. g and h are perspective coefficients. Applying Perspective Transforms We can use transform() directly with Image.PERSPECTIVE and pass four source points and four destination points to specify the transformation. Perspective transformations can distort images significantly. So carefully choose the transformation matrix or points to achieve the desired effect without excessive distortion. Applying perspective transforms in Pillow involves using transformation matrices or defining source and destination points to alter the image”s perspective, simulating changes in angles, orientations or viewpoints. Understanding transformation matrices and point mappings is crucial for achieving the desired visual effects while avoiding excessive distortion or unwanted transformations in the image. The following are the syntax and parameters of the transform() method. transformed_image = image.transform(size, method, data, resample=0, fill=0) Where, image − The Pillow Image object we want to transform. size − A tuple representing the output size (width, height) of the transformed image. method − Defines the type of transformation to be applied Image.AFFINE, Image.PERSPECTIVE or Image.QUAD, etc. data − Transformation of data required based on the method used. resample (optional) − The resampling method to use such as Image.BILINEAR, Image.NEAREST and Image.BICUBIC. Default value is 0 i.e. nearest neighbor. fill (optional) − Fill color for areas outside the transformed image boundaries. Default is 0 i.e. black. Prepare data based on the Transformation method, for the Image.AFFINE transformation it requires a 6-element tuple that represents the affine transformation matrix. For perspective transformations, Image.PERSPECTIVE is used, which requires an 8-element tuple to represent the perspective transformation matrix. Additionally, Image.QUAD involves providing source and destination quadrilateral points for accurate perspective mapping. Example In this example we are performing the perspective transformation on the given input image by using the transform() method. from PIL import Image import numpy def find_data(source, target): matrix = [] for s, t in zip(source, target): matrix.append([t[0], t[1], 1, 0, 0, 0, -s[0]*t[0], -s[0]*t[1]]) matrix.append([0, 0, 0, t[0], t[1], 1, -s[1]*t[0], -s[1]*t[1]]) A = numpy.matrix(matrix, dtype=float) B = numpy.array(source).reshape(8) res = numpy.dot(numpy.linalg.inv(A.T * A) * A.T, B) return numpy.array(res).reshape(8) #Open an image image = Image.open(“Images/logo_w.png”) # image.show() #Define the transformation matrix for perspective transform coeffs = find_data( [(0, 0), (225, 0), (225, 225), (0, 225)], [(15, 115), (140, 20), (140, 340), (15, 250)]) #Applying the perspective transformation transformed_image = image.transform((300, 400), Image.PERSPECTIVE, coeffs, Image.BICUBIC) #Save or display the transformed image transformed_image.save(“output Image/transform.png”) transformed_image.show() Output Following is the input image − On executing the above code, the following transformed image is displayed − Example Here this is another example of performing the perspective transformation to the another image with the matrix elements (a, b, c, d, e, f, g, h). from PIL import Image #Open an image image = Image.open(“Images/flowers.jpg”) image.show() #Define the transformation matrix for perspective transform matrix = (10, 4, 11, -1, 5, 2, 1, -1) #Apply the perspective transformation transformed_image = image.transform(image.size, Image.PERSPECTIVE, matrix) #Save or display the transformed image transformed_image.save(“output Image/transform_image.jpg”) transformed_image.show() Output On executing the above code you will get the following output − Input image: Output perspective transformed image: Note The transform() method supports various transformation types and the transformation data required varies based on the chosen method. It”s crucial to provide the correct transformation data i.e. matrix or points based on the chosen transformation method to achieve the desired effect. The transform() method in Pillow is versatile and allowing us to perform different types of geometric transformations on images offering flexibility in image manipulation and perspective alterations. Print Page Previous Next Advertisements ”;
Python Pillow – Creating Images with Colors ”; Previous Next What is creating Images with colors? Creating images with color in Pillow (Python Imaging Library, now known as Pillow) involves creating new images filled with specific colors. Creating images with color in Pillow involves generating an image of a specific size and filling it with a desired color. This process allows us to generate solid-colored images which can be useful for various purposes such as creating backgrounds, placeholders or simple graphics. In pillow we have the method namely new() which is used to create the images with colors. At the beginning we have seen the syntax and parameters of the new() method available in the Image module. There are few steps to be followed to create the image with the defined color. Let”s see them one by one. Import the necessary modules To use Pillow we need to import the required modules typically Image and ImageDraw. The Image module provides functions for creating and manipulating images and ImageDraw is useful for drawing shapes and text on the images. Define the image size and color Determine the dimensions i.e. width and height of the image we want to create and specify the color we want to use. Colors can be defined in various ways such as RGB tuples or color names. Create a new image with the specified size and color Use the Image.new() method to create a new image. We can specify the image mode which can be “RGB,” “RGBA,” “L” (grayscale) and others depending on our needs. We can also provide the size and color for the image. Optionally draw on the image If we want to add shapes, text or other elements to the image then we can use the ImageDraw module. This allows us to draw on the image using various methods like draw.text(), draw.rectangle() and so on. Save or display the image We can save the created image to a file in a specific format (e.g., PNG, JPEG) using the save() method. Alternatively we can display the image using the show() method which opens the image in the default image viewer. Example Here in this example we are creating the solid red color image by using the new() method of the Image module. from PIL import Image, ImageDraw #Define image size (width and height) width, height = 400, 300 #Define the color in RGB format (e.g., red) color = (255, 0, 0) #Red #Create a new image with the specified size and color image = Image.new(“RGB”, (width, height), color) #Save the image to a file image.save(“output Image/colored_image.png”) #Show the image (opens the default image viewer) image.show() Output Example In this example we are using the optional feature i.e adding the text by using the ImageDraw module Draw() method. from PIL import Image, ImageDraw #Define image size (width and height) width, height = 400, 300 #Define the color in RGB format (e.g., red) color = (255, 0, 0) #Red #Create a new image with the specified size and color image = Image.new(“RGB”, (width, height), color) #Optional: If you want to draw on the image, use ImageDraw draw = ImageDraw.Draw(image) draw.text((10, 10), “Hello, Welcome to Tutorialspoint”, fill=(255, 255, 255)) #Draw white text at position (10, 10) #Save the image to a file image.save(“output Image/colored_image.png”) #Show the image (opens the default image viewer) image.show() Output Print Page Previous Next Advertisements ”;
Python Pillow – Colors on an Image ”; Previous Next In Pillow (Python Imaging Library) colors on an image are defined as a combination of red (R), green (G) and blue (B) components which are commonly known as the RGB color model. This model represents colors as a mixture of these three primary colors with each component ranging from 0, i.e. minimum intensity to 255, i.e. maximum intensity. A fourth component, alpha (A) is often included for transparency with 0 representing full transparency and 255 representing full opacity. Defining colors accurately is crucial when working with images as it determines the appearance and composition of the image. Pillow provides various ways to represent and define colors making it flexible for various image processing and manipulation tasks. Here is a detailed explanation of these color components − Red (R) The red component represents the amount of red in a color. When R is 0 which represents there is no red and resulting in a shade of cyan or green. When R is 255 which specifies there is maximum red intensity and produces a pure red color. Intermediate values produce varying shades of red from pink to orange. Green (G) The green component represents the amount of green in a color. When G is 0 which represents there is no green and results in shades of magenta or blue. When G is 255 which represents there is maximum green intensity and results in a pure green color. Intermediate values produce different shades of green from lime to teal. Blue (B) The blue component represents the amount of blue in a color. When B is 0 which represents there is no blue and results in shades of yellow or red. When B is 255 which represents there is maximum blue intensity by producing a pure blue color. Intermediate values create various shades of blue from navy to sky blue. Alpha (A) The alpha component is optional but essential for controlling transparency. When A is 0 which represents the pixel is fully transparent allowing what”s behind it to show through. When A is 255 which represents the pixel is fully opaque and it completely covers what”s underneath. Intermediate alpha values create varying levels of transparency allowing a pixel to be partially see-through. To represent a color in Pillow we typically use a tuple or list with four values in the order (R, G, B, A) to specify the color of a pixel. For example (255, 0, 0, 255) represents a fully opaque red pixel while (0, 255, 0, 128) represents a semi-transparent green pixel. Example Let”s see an example of creating an image using the Python Pillow with RGBA color representation. from PIL import Image # Create an RGBA image with Semi-transparent green image = Image.new(”RGBA”, (700, 300), (0, 255, 0, 128)) # Display the resultant Semi-transparent green image image.show() On executing the above program you will get output RGBA like below − Understanding the RGB color model and the alpha component is fundamental when working with image processing and manipulation in Pillow as it allows us to create, modify and combine colors and images in various ways. Hexadecimal Color Representation Hexadecimal color codes are widely used on the web and in graphics design. In Pillow we can define a color using a hexadecimal string which represents the RGB values. The format is #RRGGBB where RR, GG and BB are two-digit hexadecimal values for red, green and blue respectively. Example Here is an example of creating an image using the Python Pillow Hexadecimal color representation. In this example we are creating red colored image with 80% opacity. from PIL import Image # Create a red colored image with 80% opacity image = Image.new(”RGBA”, (700, 300), “#ff0000cc”) # Display the resultant image image.show() when you run the above program you will get following output − Named Colors Pillow ImageColor module provides a set of named colors (commonly used HTML color names), allowing us to use these color names instead of numerical values. For example, the name red indicates pure red color, and it is important to note that color names are case insensitive, meaning “red” and “Red” are treated the same. Example The following example demonstrates how to access and print the named colors available in Pillow”s ImageColor module. from PIL import ImageColor # Access all the named colors color_map = ImageColor.colormap # Count the number of named colors num_colors = len(color_map) # Print the available named colors and count print(color_map) print(f”Total number of named colors: {num_colors}”) when you run the above program you will get similar output like below − {”aliceblue”: ”#f0f8ff”, ”antiquewhite”: ”#faebd7”, ”aqua”: ”#00ffff”, ”aquamarine”: ”#7fffd4”, ”azure”: ”#f0ffff”, ”beige”: ”#f5f5dc”, ”bisque”: ”#ffe4c4”, ”black”: ”#000000”, ”blanchedalmond”: ”#ffebcd”, ”blue”: ”#0000ff”, ”blueviolet”: ”#8a2be2”, ”brown”: ”#a52a2a”, ”burlywood”: ”#deb887”, ”cadetblue”: ”#5f9ea0”, ”chartreuse”: ”#7fff00”, ”chocolate”: ”#d2691e”, ”coral”: ”#ff7f50”, ”cornflowerblue”: ”#6495ed”, ”cornsilk”: ”#fff8dc”, ”crimson”: ”#dc143c”, ”cyan”: ”#00ffff”, ”darkblue”: ”#00008b”, ”darkcyan”: ”#008b8b”, ”darkgoldenrod”: ”#b8860b”, ”darkgray”: ”#a9a9a9”, ”darkgrey”: ”#a9a9a9”, ”darkgreen”: ”#006400”, ”darkkhaki”: ”#bdb76b”, ”darkmagenta”: ”#8b008b”, ”darkolivegreen”: ”#556b2f”, ”darkorange”: ”#ff8c00”, ”darkorchid”: ”#9932cc”, ”darkred”: ”#8b0000”, ”darksalmon”: ”#e9967a”, ”darkseagreen”: ”#8fbc8f”, ”darkslateblue”: ”#483d8b”, ”darkslategray”: ”#2f4f4f”, ”darkslategrey”: ”#2f4f4f”, ”darkturquoise”: ”#00ced1”, ”darkviolet”: ”#9400d3”, ”deeppink”: ”#ff1493”, ”deepskyblue”: ”#00bfff”, ”dimgray”: ”#696969”, ”dimgrey”: ”#696969”, ”dodgerblue”: ”#1e90ff”, ”firebrick”: ”#b22222”, ”floralwhite”: ”#fffaf0”, ”forestgreen”: ”#228b22”, ”fuchsia”: ”#ff00ff”, ”gainsboro”: ”#dcdcdc”, ”ghostwhite”: ”#f8f8ff”, ”gold”: ”#ffd700”, ”goldenrod”: ”#daa520”, ”gray”: ”#808080”, ”grey”: ”#808080”, ”green”: ”#008000”, ”greenyellow”: ”#adff2f”, ”honeydew”: ”#f0fff0”, ”hotpink”: ”#ff69b4”, ”indianred”: ”#cd5c5c”, ”indigo”: ”#4b0082”, ”ivory”: ”#fffff0”, ”khaki”: ”#f0e68c”, ”lavender”: ”#e6e6fa”, ”lavenderblush”: ”#fff0f5”, ”lawngreen”: ”#7cfc00”, ”lemonchiffon”: ”#fffacd”, ”lightblue”: ”#add8e6”, ”lightcoral”: ”#f08080”, ”lightcyan”: ”#e0ffff”, ”lightgoldenrodyellow”: ”#fafad2”, ”lightgreen”: ”#90ee90”, ”lightgray”: ”#d3d3d3”, ”lightgrey”: ”#d3d3d3”, ”lightpink”: ”#ffb6c1”, ”lightsalmon”: ”#ffa07a”, ”lightseagreen”: ”#20b2aa”, ”lightskyblue”: ”#87cefa”, ”lightslategray”: ”#778899”, ”lightslategrey”: ”#778899”, ”lightsteelblue”: ”#b0c4de”, ”lightyellow”:
Python Pillow – Converting color string to RGB Color values ”; Previous Next Converting a color string to RGB color values is the process of taking a textual representation of a color and converting it into the numerical values that represent the color in the Red, Green and Blue (RGB) color model. In the RGB color model colors are specified by three numbers each ranging from 0 to 255 in which, The first number represents the amount of red in the color. The second number represents the amount of green in the color. The third number represents the amount of blue in the color. For example, the color red is typically represented as (255, 0, 0) in RGB values which means it has maximum red (255) and no green (0) or no blue (0). Converting color string to RGB Color values To perform the conversion of color string into RGB values we can use the getrgb() function in the ImageColor module of the Python Pillow library. Syntax The below is the syntax and parameters of the ImageColor.getrgb() method − ImageColor.getrgb(color) Where, color − This is a string representing the color we want to convert to RGB values. 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. Example In this example the ImageColor.getrgb() function takes a color string blue as an argument and returns a tuple of RGB values. from PIL import ImageColor #Define a color string color_string = “blue” #Convert the color string to RGB values rgb_color = ImageColor.getrgb(color_string) #Print the RGB values print(“The conversion of the color string”,color_string,”:”,rgb_color) Output The conversion of the color string blue: (0, 0, 255) Example Here, in this example we are converting the yellow color string into the RGB values. We are passing the color string argument as a hexadecimal value to the ImageColor.getrgb() method. from PIL import ImageColor #Define a color string color_string = “#FFFF00″ #Convert the color string to RGB values rgb_color = ImageColor.getrgb(color_string) #Print the RGB values print(“The conversion of the color string”,color_string,”:”,rgb_color) Output The conversion of the color string “#FFFF00″: (255, 255, 0) Print Page Previous Next Advertisements ”;
Python Pillow – Change the Color by Changing the Pixel Values ”; Previous Next Changing the color of an image by changing the pixel values in Pillow (PIL) involves manipulating the individual pixel values of an image to achieve the desired color transformation. We can perform various color operations by altering the RGB values of each pixel. Modifying Pixel Values using the getdata() Method We have the method namely, getdata() in pillow. It can used to retrieve the pixel data of an image. It returns a sequence of pixel values typically as a one-dimensional list or iterable where each pixel value represents the color of a pixel in the image. By using the getdata() method, you can access and modify the pixel values of an image. The below is the syntax and parameters of the Image.getdata() method − Image.getdata(band=None) Where, band − This specifies that what the band has to return. The default value is to return all bands. For returning a single band pass in the index value. For example 0 to get the Rband from an RGBimage. The below are the steps to be followed for changing the color pixels of an image. Open the image that we want to modify using Pillow”s Image.open() method. Access the image data as a pixel-by-pixel list using image.getdata(). Create a new list of pixel values by changing the color as we desire. Create a new image with the modified pixel values using Image.new(). Save or display the modified image using save(). Example In this example we are getting the list of pixel data of the given input image by using the Image.getdata() method. from PIL import Image #Open the image you want to modify image = Image.open(“Images/python logo.png”) #Access the pixel data of the image pixels = list(image.getdata()) print(pixels) Input Image Output [(255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255),………………………………………………………………………………………………………………………………………………………………………….. (255, 255, 255, 255), (255, 255, 255, 255)] Example Here in this example we are modifying the pixel of the given input image into red by using the Image.getdata() method. from PIL import Image #Open the image you want to modify image = Image.open(“Images/three.jpg”) #Access the pixel data of the image pixels = list(image.getdata()) #Define the new color you want (e.g., red) new_color = (255, 0, 0) #Red #Create a new list of pixel values with the new color modified_pixels = [new_color if pixel != (255, 255, 255) else pixel for pixel in pixels] #Create a new image with the modified pixel values modified_image = Image.new(“RGB”, image.size) modified_image.putdata(modified_pixels) #Save the modified image to a file modified_image.save(“output Image/modified_image.jpg”) #Display the modified image modified_image.show() Input Image Output Print Page Previous Next Advertisements ”;