Python Pillow – Function Reference ”; Previous Next Python Pillow, a powerful image processing library, offers a wide range of modules and functionalities to perform various image-related tasks. From basic operations like channel manipulations to advanced features such as generating graphics and evaluating mathematical expressions on images. Below, you”ll find an overview of the modules offered by Pillow along with details about their methods. ImageChops (“Channel Operations”) Module The ImageChops module, referred to as “channel operations” or “chops” provides a range of operations that can be performed on images, primarily to perform mathematical image operations such as enhancing special effects, creating composite images, algorithmic painting, and more. These operations are useful for image enhancement, blending, and creating effects. It”s important to note that, currently, most channel operations are only available for 8-bit images, such as “L” and “RGB.” Functions Channel operations typically accept one or two image inputs and produce a new image as output. Unless specified otherwise, the result of a channel operation is always clipped within the 0 to MAX range. For the supported modes in this module, MAX is set to 255. The following are the methods available in this Module − Sr.No. Methods with Description 1 ImageChops.add() Adds two images, and divides the result by a specified scale, and then adds an offset. 2 ImageChops.subtract() Subtracts one image from another, and divides the result by a specified scale, and then adds an offset. 3 ImageChops.add_modulo() Add two images without clipping the result. 4 ImageChops.subtract_modulo() Subtract two images without clipping the result. 5 ImageChops.composite() Composites two images by blending two images using a mask. 6 ImageChops.duplicate() Returns a copy of the image. 7 ImageChops.darker() Compares two images and returns the darker pixel value for each pixel. 8 ImageChops.constant() Creates a new image by filling the channel of an image with a given grey level. 9 ImageChops.difference() Computes the absolute difference between two images. 10 ImageChops.invert() Inverts the pixel values of an image. 11 ImageChops.lighter() Compares two images and returns the lighter pixel value for each pixel. 12 ImageChops.logical_and() It performs the logical AND between two images. 13 ImageChops.logical_or() It performs the logical OR between two images. 14 ImageChops.logical_xor() It performs the logical XOR between two images. 15 ImageChops.multiply() Multiplies two images together. 16 ImageChops.soft_light() Superimposes two images on top of each other using the Soft Light algorithm. 17 ImageChops.hard_light() Superimpose two images on top of each other using the Hard Light algorithm. 18 ImageChops.overlay() Applies an overlay blending mode between two images. 19 ImageChops.offset() Shifts the image by a given offset. 20 ImageChops.screen() Superimposes two inverted images on top of each other using the screen blending mode. ImageOps Module The ImageOps module provides a set of ready-made operations for image processing. The following are the list of methods available in this Module. Let”s explore and understand the basic fuctionality of each method. Sr.No. Methods with Description 1 ImageOps.autocontrast() Enhances the contrast of an image automatically. 2 ImageOps.colorize() Colorizes a grayscale image. 3 ImageOps.scale() Scales the image by a given factor. 4 ImageOps.equalize() Equalizes the histogram of an image. 5 ImageOps.grayscale() Converts an image to grayscale. 6 ImageOps.posterize() Reduces the number of bits for each color channel. 7 ImageOps.solarize() Inverts all pixel values above a threshold. ImageDraw Module The ImageDraw module provides simple 2D graphics support for creating new images, adding shapes, and drawing text. It is commonly used for generating graphics on the fly and for annotating images. The following are the list of methods available in this Module. Let”s explore and understand the basic fuctionality of each method − Sr.No. Methods with Description 1 ImageDraw.arc() Draws an arc inside a specified bounding box. 2 ImageDraw.chord() Draws a chord (a segment of a circle) inside a bounding box. 3 ImageDraw.pieslice() Draws a filled pie slice inside a bounding box. 4 ImageDraw.point() Draws points (single pixels) at specified coordinates on an image. 5 ImageDraw.regular_polygon() Draws a regular polygon with a given bounding circle. 6 ImageDraw.rounded_rectangle() Draws a rounded rectangle. 7 ImageDraw.multiline_text() Draws multiline text at a specified position on an image. ImageGrab Module The ImageGrab module provides functions for capturing the contents of the screen or part of the screen to the PIL Image memory. It can be used to take screenshots or to capture images from the clipboard. Let”s explore and understand the basic fuctionality of each functions available in this module − Sr.No. Methods with Description 1 ImageGrab.grab() Captures the snapshot of the screen. 2 ImageGrab.grabclipboard() Captures a snapshot of the clipboard image. ImageMath Module The ImageMath module allows you to evaluate image expressions. And you can perform operations, such as arithmetic, bitwise, and logical operations, on images. Let”s
Category: python Pillow
Python Pillow – Image Blending ”; Previous Next Image blending is a process of combining or mixing two images to create a new image. One common method for image blending is to use alpha blending. In alpha blending, each pixel in the result is computed based on a weighted sum of the corresponding pixels in the input images. The alpha channel, representing transparency, is used as the weight factor. This technique is commonly used in graphics, image processing, and computer vision to achieve various visual effects. The Python Pillow library provides the blend() function within its Image module to perform the blending operation on images. The Image.blend() function This function provides a convenient way to create a smooth transition between two images by specifying a blending factor (alpha). The function creates a new image by interpolating between two input images using a constant alpha value. The interpolation is performed according to the formula − out=image1×(1.0−alpha)+image2×alpha Following is the syntax of the function − PIL.Image.blend(im1, im2, alpha) Where − im1 − The first image. im2 − The second image. It must have the same mode and size as the first image. alpha − The interpolation alpha factor. If alpha is 0.0, a copy of the first image is returned. If alpha is 1.0, a copy of the second image is returned. There are no restrictions on the alpha value. If necessary, the result is clipped to fit into the allowed output range. Example Let”s see a basic example of blending two images using the Image.blend() method. from PIL import Image # Load two images image1 = Image.open(“Images/ColorDots.png”) image2 = Image.open(“Images/pillow-logo-w.png”) # Blend the images with alpha = 0.5 result = Image.blend(image1, image2, alpha=0.5) # Display the input and resultant iamges image1.show() image2.show() result.show() Input Images Output Example Here is an example that demonstrates the use of PIL.Image.blend() with alpha values 2. from PIL import Image # Load two images image1 = Image.open(“Images/ColorDots.png”) image2 = Image.open(“Images/pillow-logo-w.png”) # Blend the images with alpha = 2 result = Image.blend(image1, image2, alpha=2) # Display the input and resultant iamges image1.show() image2.show() result.show() Input Images Output Example Here is an example that demonstrates the use of PIL.Image.blend() with alpha value 1.0. It will return a copy of the second image. from PIL import Image # Load two images image1 = Image.open(“Images/ColorDots.png”) image2 = Image.open(“Images/pillow-logo-w.png”) # Blend the images with alpha = 2 result = Image.blend(image1, image2, alpha=1.0) # Display the input and resultant iamges image1.show() image2.show() result.show() Input Images Output Print Page Previous Next Advertisements ”;
Python Pillow – Batch Processing Images ”; Previous Next Batch processing images in Python Pillow allows you to efficiently apply the same edits or operations to multiple images simultaneously. This approach is valuable for tasks like resizing, cropping, renaming, watermarking, or formatting images, as it enhances workflow efficiency and optimizes output. This is particularly useful when working with a large number of images, as it can significantly impact the speed and efficiency of your computer. It allows you to apply the same operation to each image, saving time and effort. Steps for Batch Processing Images The steps involved in batch processing images with Python Pillow are as follows − Create a List of Image Files: Generate a list of file paths to the images you want to process. Iterate Through the List of Images: Use loops to traverse the list of image files. You can use ”for” or ”while” loops to handle each image one at a time. Perform Image Processing Operations: Within the loop, apply the desired image processing operations to each image. This may include resizing, cropping, applying filters, adding text or watermarks, or any other operation necessary. Save Processed Images: After performing the processing operations on each image, save the processed image to the desired location. Resizing Images using Batch Processing Resizing images using Python Pillow batch processing is one of the common tasks in image processing. It involves adjusting the dimensions of multiple images to a specific size or aspect ratio. Example Here is an example that demonstrates the resizing multiple images at once using the Python Pillow batch processing. In this example, a collection of JPG images in a specified folder is resized to a specific size (e.g., 700×400). from PIL import Image import glob import os # Get a list of image files in the ”Images for Batch Operation” directory input_directory = “Images for Batch Operation” output_directory = “Output directory for Batch Operation” image_files = [f for f in glob.glob(os.path.join(input_directory, “*.jpg”))] for file in image_files: image = Image.open(file) # Resize the image to a specific size (e.g., 700×400) image = image.resize((700, 400)) # Save the resized image to the ”Output directory for Batch Operation” directory output_path = os.path.join(output_directory, os.path.basename(file)) image.save(output_path) Output Following image represents the list of image files available in the input directory − If we navigate to the directory where the output image was saved (i.e, “Output directory for Batch Operation”), we will be able to observe resized images as shown below − Renaming Images using the Batch Processing Renaming images is another frequently performed task in batch processing. It involves changing the filenames of multiple images according to a specified pattern. Example The following example adds the prefix “New_” to the names of a batch of PNG images located in the specified input_directory. It renames these images and saves them in the output_directory with the new names. from PIL import Image import glob import os # Get a list of image files in the ”Images for Batch Operation” directory input_directory = “Images for Batch Operation” output_directory = “Output directory for Batch Operation” image_files = [f for f in glob.glob(os.path.join(input_directory, “*.png”))] for file in image_files: image = Image.open(file) # Save the image with the new name to the ”Output directory for Batch Operation” directory output_path = os.path.join(output_directory, ”New_”+os.path.basename(file)) image.save(output_path) Output Following image represents the list of image files available in the input directory − If we navigate to the directory where the output image was saved (i.e, “Output directory for Batch Operation”), we will be able to observe renamed images as shown below − Print Page Previous Next Advertisements ”;
Python Pillow – Adding Padding to an Image ”; Previous Next Adding padding to an image involves adding a border around it. This is a useful technique while adjusting the image”s size without changing its aspect ratio or trimming it. Padding can be added to the top, bottom, left, and right sides of the image. This is particularly important when working with images that have important information at the edges, which you want to retain for tasks like segmentation. The Pillow (PIL) library provides two functions, pad() and expand(), within its ImageOps module for adding padding to images. Padding Images with ImageOps.pad() function The pad() function is used to resize and pad an image to a specified size and aspect ratio. It allows you to specify the output size, resampling method, background color, and positioning of the original image within the padded area. Syntax of this function as follows − PIL.ImageOps.pad(image, size, method=Resampling.BICUBIC, color=None, centering=(0.5, 0.5)) Where, image − The image to resize and pad. size − A tuple specifying the requested output size in pixels, in the format (width, height). The function will resize the image to this size while maintaining the aspect ratio. method − This parameter determines the resampling method used during resizing. The default method is BICUBIC, which is a type of interpolation. You can specify other resampling methods supported by PIL. Common options include NEAREST, BILINEAR, and LANCZOS. color − This parameter specifies the background color of the padded area. It supports the RGBA tuple also, like (R, G, B, A). If not specified, the default background color is black. centering − This parameter controls the position of the original image within the padded version. It”s specified as a tuple with two values between 0 and 1. Example Here is an example that adds padding to an image using the ImageOps.pad() function. from PIL import Image from PIL import ImageOps # Open the input image input_image = Image.open(”Images/elephant.jpg”) # Add padding to the image image_with_padding = ImageOps.pad(input_image, (700, 300), color=(130, 200, 230)) # Display the input image input_image.show() # Display the image with the padding image_with_padding.show() Input Output Output image After resizing with padding − Adding Borders with the ImageOps.expand() function The expand() function adds a border of a specified width and color around the image. It is useful for creating a decorative frame or emphasizing the content of the image. Its syntax is as follows − PIL.ImageOps.expand(image, border=0, fill=0) image − The image to expand the border. border − The width of the border to add, specified in pixels. It determines how wide the border will be around the image. The default value is (0). fill − The pixel fill value, which represents the color of the border. The default value is 0, which corresponds to black. You can specify the fill color using an appropriate color value. Example Here is an example that adds padding to an image using the ImageOps.expand() function. from PIL import Image, ImageOps # Open the input image input_image = Image.open(”Images/Car_2.jpg”) # Add padding of 15-pixel border image_with_padding = ImageOps.expand(input_image, border=(15, 15, 15, 15), fill=(255, 180, 0)) # Display the input image input_image.show() # Display the output image with padding image_with_padding.show() Input Output Output image with padding − Print Page Previous Next Advertisements ”;
Python Pillow – Creating Animated GIFs ”; Previous Next The GIF (Graphics Interchange Format), is a bitmap image format developed by a team at CompuServe, an online services provider, under the leadership of American computer scientist Steve Wilhite. GIF ware not designed as an animation medium. However, its ability to store multiple images within a single file made it a logical choice for representing the frames of an animation sequence. To support the presentation of animations, the GIF89a specification introduced the Graphic Control Extension (GCE). This extension enables the specification of time delays for each frame, effectively allowing the creation of a video clip from a series of images. In an animated GIF, each frame is introduced by its own GCE, specifying the time delay that should occur after the frame is drawn. Additionally, global information defined at the beginning of the file applies as the default setting for all frames, simplifying the management of animation settings and behaviors. Python”s Pillow library can read GIF files in both GIF87a and GIF89a formats. By default, it writes GIF files in GIF87a format unless GIF89a features are used or the input file is already in GIF89a format. The saved files use LZW encoding. Creating Animated GIFs with Python Pillow It is possible to create animated GIFs using Pillow”s Image.save() function. Below are the syntax and the available options when calling save() function to save a GIF file − Syntax: Image.save(out, save_all=True, append_images=[im1, im2, …]) Options: save_all − If set to true, it saves all frames of the image. Otherwise, it saves only the first frame of a multi-frame image. append_images − This option allows appending a list of images as additional frames. The images in the list can be single or multi-frame images. This feature is supported for GIF, PDF, PNG, TIFF, and WebP formats, as well as for ICO and ICNS formats. When images of relevant sizes are provided, they will be used instead of scaling down the main image. include_color_table − Determines whether or not to include a local color table. interlace − Specifies whether the image is interlaced. By default, interlacing is enabled, unless the image”s width or height is less than 16 pixels. disposal − Indicates how the graphic should be treated after being displayed. It can be set to values like 0 (no disposal specified), 1 (do not dispose), 2 (restore to the background color), or 3 (restore to previous content). You can pass a single integer for a constant disposal or a list/tuple to set disposal for each frame separately. palette − This option allows you to use a specified palette for the saved image. The palette should be provided as a bytes or bytearray object containing the palette entries in RGBRGB… form. It should be no more than 768 bytes. Alternatively, you can pass the palette as a PIL.ImagePalette.ImagePalette object. optimize − If set to true, it attempts to compress the palette by eliminating unused colors. This optimization is useful when the palette can be compressed to the next smaller power of 2 elements. Additional options like transparency, duration, loop, and comment can be provided to control specific aspects of the animated GIF. Example Here is an example that demonstrates how to create a GIF animation by generating individual frames with different colors and saving them. import numpy as np from PIL import Image # Function to create a new image with a specified width, height, and color def create_image(width, height, color): return Image.new(“RGBA”, (width, height), color) # Set the width and height of the images width, height = 300, 300 # Define the colors for the images colors = [(64, 64, 3), (255, 0, 0), (255, 255, 0), (255, 255, 255), (164, 0, 3)] # Create a list of images using a list comprehension images = [create_image(width, height, color) for color in colors] # Save the images as a GIF with specified parameters images[0].save(“Output.gif”, save_all=True, append_images=images[1:], duration=1000/2, loop=0) Output The animated GIFs file is saved successfully… Below you can see the saved animated GIFs in your working directory − Example The following example takes a list of existing image files to create an animated GIF by saving these images in sequence. from PIL import Image # List of file paths for existing images image_paths = [”Images/book_1.jpg”, ”Images/book_2.jpg”, ”Images/book_3.jpg”, ”Images/book_4.jpg”] # Create a list of image objects from the provided file paths image_list = [Image.open(path) for path in image_paths] # Save the first image as an animated GIF output_path = Book_Animation.gif” image_list[0].save( output_path, save_all=True, append_images=image_list[1:], # Append the remaining images duration=1000, # Frame duration in milliseconds loop=0 ) print(”The animated GIF file has been created and saved successfully…”) Output The animated GIF file has been created and saved successfully… The following image represents the saved animated GIFs in your working directory − Example This example modifies an existing GIF file by duplicating its last frame a few times and then saves it as a new GIF file. In this example we will use the ImageSequence module to iterate each frames from the input GIF file. from PIL import Image, ImageSequence # Open the existing GIF file input_image = Image.open(“Book_Animation.gif”) # Create an empty list to store the frames of the GIF frames = [] # Iterate over the frames of the GIF and append them to the frames list for frame in ImageSequence.Iterator(input_image): frames.append(frame) # Duplicate the last frame three times to extend the animation for i in range(3): frames.append(frames[-1]) # Save the frames as a new GIF file (“newGif.gif”): output_path = “newGif.gif” frames[0].save( output_path, save_all=True, append_images=frames[1:], optimize=False, duration=40, # Set the frame duration to 40 milliseconds loop=0 ) Output
Python Pillow – Correcting Color Balance ”; Previous Next Correcting color balance, in the context of image processing, refers to the adjustment of the intensities of different colors within an image to achieve a desired visual outcome. This adjustment typically involves the primary colors of red, green, and blue and is aimed at rendering specific colors, especially neutral colors like white or gray, correctly. Correct color balance ensures that the colors in an image appear as they would in the real world, making it look more naturalistic and pleasing to the human eye. The Python pillow library provides several options to correct the color balance of an image. Let”s explore them below. Correcting Color Balance of an Image Correcting or adjusting an image”s color balance can simply be done by using the PIL.ImageEnhance.Color() class. This class provides the ability to fine-tune the color balance of an image by changing the enhancement factor. Below is the syntax of the ImageEnhance.Color() class − class PIL.ImageEnhance.Color(image) 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 color balance. 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. Following are the steps to adjust the color balance of an image − Create a color enhancer object using the ImageEnhance.Color() class. Then apply the enhancement factor using the enhancer_object.enhance() method. Example Here is an example that uses the PIL.ImageEnhance.Color class to adjust the color balance of an image. from PIL import Image, ImageEnhance # Open the image input_image = Image.open(“Images/Tajmahal_2.jpg”) # Create a ColorEnhance object color_enhancer = ImageEnhance.Color(input_image) # Adjust the color balance by setting the enhancement factor enhancement_factor = 1.5 color_balanced_image = color_enhancer.enhance(enhancement_factor) # Display the original and color balanced images input_image.show() color_balanced_image.show() Input Image Output Color Balanced Image − Correcting Color Balance using the Point Transforms Here is another approach of applying point transforms to color channels of an image for adjusting the color balance of an image. Point transforms can generally be used to adjust various aspects of an image, including color balance, brightness, and contrast. This can be done by using the point() method, it helps to Process the individual bands/ channels of an image. Example Here is an example that demonstrates the application of point transforms to correct the color balance of an image. from PIL import Image # Open the image input_image = Image.open(“Images/tree.jpg”) # Extract the red (R), green (G), and blue (B) channels red_channel, green_channel, blue_channel = input_image.split() # Adjust the color balance by scaling the intensity of each channel # Increase green intensity green_channel = green_channel.point(lambda i: i * 1.2) # Decrease blue intensity blue_channel = blue_channel.point(lambda i: i * 0.8) # Merge the channels back into an RGB image corrected_image = Image.merge(“RGB”, (red_channel, green_channel, blue_channel)) # Display the input and corrected images input_image.show() corrected_image.show() Input Image Output Image Output Color Balanced Image − Example The following example adjusts the color balance of an image by applying a transformation matrix to its color channels. from PIL import Image # Open the input image input_image = Image.open(“Images/Tajmahal_2.jpg”) # Define a transformation matrix to adjust color channels # Multiply R (red) by 1.2, leaving G (green) and B (blue) unchanged transformation_matrix = (1.5, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0) # Apply the color channel transformation and create the corrected image corrected_image = input_image.convert(“RGB”, transformation_matrix) # Show the original and corrected images input_image.show() corrected_image.show() Input Image Output Image Output Color Balanced Image − Print Page Previous Next Advertisements ”;
Python Pillow – Quick Guide
Python Pillow – Quick Guide ”; Previous Next Python Pillow – Overview In today’s digital world, we come across lots of digital images. In case, we are working with Python programming language, it provides lot of image processing libraries to add image processing capabilities to digital images. Some of the most common image processing libraries are: OpenCV, Python Imaging Library (PIL), Scikit-image, Pillow. However, in this tutorial, we are only focusing on Pillow module and will try to explore various capabilities of this module. Pillow is built on top of PIL (Python Image Library). PIL is one of the important modules for image processing in Python. However, the PIL module is not supported since 2011 and doesn’t support python 3. Pillow module gives more functionalities, runs on all major operating system and support for python 3. It supports wide variety of images such as “jpeg”, “png”, “bmp”, “gif”, “ppm”, “tiff”. You can do almost anything on digital images using pillow module. Apart from basic image processing functionality, including point operations, filtering images using built-in convolution kernels, and color space conversions. Image Archives The Python Imaging Library is best suited for image archival and batch processing applications. Python pillow package can be used for creating thumbnails, converting from one format to another and print images, etc. Image Display You can display images using Tk PhotoImage, BitmapImage and Windows DIB interface, which can be used with PythonWin and other Windows-based toolkits and many other Graphical User Interface (GUI) toolkits. For debugging purposes, there is a show () method to save the image to disk which calls the external display utility. Image Processing The Pillow library contains all the basic image processing functionality. You can do image resizing, rotation and transformation. Pillow module allows you to pull some statistics data out of image using histogram method, which later can be used for statistical analysis and automatic contrast enhancement. Python Pillow – Environment Setup This chapter discusses how to install pillow package in your computer. Installing pillow package is very easy, especially if you’re installing it using pip. Installing Pillow using pip To install pillow using pip, just run the below command in your command prompt − python -m pip install pip python -m pip install pillow In case, if pip and pillow are already installed in your computer, above commands will simply mention the ‘requirement already satisfied’as shown below − Python Pillow – Using Image Module To display the image, pillow library is using an image class within it. The image module inside pillow package contains some important inbuilt functions like, load images or create new images, etc. Opening, rotating and displaying an image To load the image, we simply import the image module from the pillow and call the Image.open(), passing the image filename. Instead of calling the Pillow module, we will call the PIL module as to make it backward compatible with an older module called Python Imaging Library (PIL). That’s why our code starts with “from PIL import Image” instead of “from Pillow import Image”. Next, we’re going to load the image by calling the Image.open() function, which returns a value of the Image object data type. Any modification we make to the image object can be saved to an image file with the save() method. The image object we received using Image.open(), later can be used to resize, crop, draw or other image manipulation method calls on this Image object. Example Following example demonstrates the rotation of an image using python pillow − from PIL import Image #Open image using Image module im = Image.open(“images/cuba.jpg”) #Show actual Image im.show() #Show rotated Image im = im.rotate(45) im.show() Output If you save the above program as Example.py and execute, it displays the original and rotated images using standard PNG display utility, as follows − Actual image Rotated image (45 degrees) Attributes of Image Module The instance of the Image class has some attributes. Let’s try to understand few of them by example − Image.filename This function is used to get the file name or the path of the image. >>>image = Image.open(”beach1.jpg”) >>> image.filename ”beach1.jpg” Image.format This function returns file format of the image file like ‘JPEG’, ‘BMP’, ‘PNG’, etc. >>> image = Image.open(”beach1.jpg”) >>> >>> image.format ”JPEG” Image.mode It is used to get the pixel format used by the image. Typical values are “1”, “L”, “RGB” or “CMYK”. >>> image.mode ”RGB” Image.size It returns the tuple consist of height & weight of the image. >>> image.size (1280, 721) Image.width It returns only the width of the image. >>> image.width 1280 Image.height It returns only the height of the image. >>> image.height 721 Image.info It returns a dictionary holding data associated with the image. >>> image.info {”jfif”: 257, ”jfif_version”: (1, 1), ”dpi”: (300, 300), ”jfif_unit”: 1, ”jfif_density”: (300, 300), ”exif”: b”Exifx00x00MMx00*x00x00x00 …. …. xebx00x00”x10x00x00xd7xb3x00x00x03xe8″} Image.palette It returns the colour palette table, if any. >>> image.palette Output above − None Python Pillow – Working with Images This chapter elaborates on topics including how to read and save an image in Pillow. Reading an Image Reading and writing images using pillow library is very simple, with the help of PIL.Image module function. Syntax Image.open(fp, mode=’r’) Where fp − A filename (string), pathlib.Path object or a file object. The file object must implement read(), seek() and tell() methods and be opened in binary mode. mode − It’s an optional argument, if given, must be ‘r’. Return value − An Image object. Error − If the file cannot be found, or the image cannot be opened and identified. Example Following is a very simple example, where we are going to open an image of any format (We are using .jpg), display it in a window and then save it (default location) with another file format (.png). from PIL import Image image = Image.open(”beach1.jpg”) image.show() image.save(”beach1.bmp”) image1 = Image.open(”beach1.bmp”) image1.show() In the above example, we import the Image module from PIL library and then, call the Image.open() function to read an image
Python Pillow – Discussion
Discuss Python Pillow ”; Previous Next This tutorial is about “Pillow” package, one of the important libraries of python for image manipulation. Pillow is a free and open source library for the Python programming language that allows you to easily create & manipulate digital images. In this tutorial, you will see the hands-on approach to learn different functionalities of pillow, much more than, read & save an image, creating thumbnail & merge to images, blur, crop, flip & rotate images, resizing & adding watermark, adding filters & working with colors to an image and use of pillow & numpy in machine learning. Print Page Previous Next Advertisements ”;
Python Pillow – Extracting Image Metadata ”; Previous Next Image metadata refers to information associated with a digital image. This metadata can include various details, such as camera model, date and time of capture, location information (GPS coordinates), and keywords. In this context, extracting image metadata retrieves this underlying information from an image. One widely used type of image metadata is EXIF data, short for “Exchangeable Image File Format.” This standardized format, established by organizations like Canon, Minolta/Sony, and Nikon, encapsulates a comprehensive set of specifics related to the image, including camera settings, exposure parameters, and more. It”s important to note that all EXIF data is metadata, but not all metadata is EXIF data. EXIF is a specific type of metadata, and the data you”re seeking might also fall under other metadata types, such as IPTC or XMP data. Extracting Basic Image Metadata The Python Pillow Image object offers a straightforward way of accessing the basic image metadata, including the filename, dimensions, format, mode, and more. Example The example demonstrates how to extract various basic metadata from an image using attributes of the Pillow Image object. from PIL import Image # Path to the image image_path = “Images/dance-cartoon.gif” # Read the image data using Pillow image = Image.open(image_path) # Access and print basic image metadata print(“Filename:”, image.filename) print(“Image Size:”, image.size) print(“Image Height:”, image.height) print(“Image Width:”, image.width) print(“Image Format:”, image.format) print(“Image Mode:”, image.mode) # Check if the image is animated (for GIF images) if hasattr(image, “is_animated”): print(“Image is Animated:”, image.is_animated) print(“Frames in Image:”, image.n_frames) Output Filename: Images/dance-cartoon.gif Image Size: (370, 300) Image Height: 300 Image Width: 370 Image Format: GIF Image Mode: P Image is Animated: True Frames in Image: 12 Extracting Advanced Image Metadata The Python Pillow library offers tools to access and manage image metadata, specifically through the Image.getexif() function and the ExifTags module. The Image.getexif() function retrieves EXIF data from an image, which includes a wealth of valuable information about the image. The syntax for using this function is − Image.getexif() The function returns an Exif object, This object provides read and write access to EXIF image data. The PIL.ExifTags.TAGS dictionary is used to interpret EXIF data. This dictionary maps 16-bit integer EXIF tag enumerations to human-readable descriptive string names, making the metadata easier to understand. The syntax for this dictionary is − PIL.ExifTags.TAGS: dict Example The following example demonstrates how to access and print EXIF metadata from an image file using Pillow”s getexif() method. It also shows how to use the TAGS dictionary to map tag IDs to human-readable tag names. from PIL import Image from PIL.ExifTags import TAGS # The path to the image image_path = “Images/flowers_canon.JPG” # Open the image using the PIL library image = Image.open(image_path) # Extract EXIF data exif_data = image.getexif() # Iterate over all EXIF data fields for tag_id, data in exif_data.items(): # Get the tag name, instead of the tag ID tag_name = TAGS.get(tag_id, tag_id) print(f”{tag_name:25}: {data}”) Output GPSInfo : 10628 ResolutionUnit : 2 ExifOffset : 360 Make : Canon Model : Canon EOS 80D YResolution : 72.0 Orientation : 8 DateTime : 2020:10:25 15:39:08 YCbCrPositioning : 2 Copyright : CAMERAMAN_SAI XResolution : 72.0 Artist : CAMERAMAN_SAI Print Page Previous Next Advertisements ”;
Python Pillow – Color Inversion ”; Previous Next Color inversion in Python Pillow is a popular photo effect, that transforms an image by reversing the colors to their complementary hues on the color wheel. It results in changes such as black becoming white, white becoming black, and other color shifts. This technique, also referred to as image inversion or color negation, is a method in image processing that systematically alters the colors within an image. In a color-inverted image, the colors are transformed in such a way that light areas become dark, dark areas become light, and colors are inverted across the color spectrum. Applying the Color Inversion to an Image In Python Pillow, color inversion is achieved through the inversion of colors across the image spectrum. The library offers the invert() function within its ImageOps module, allowing you to apply color inversion to the images. This function is designed to negate the colors of a given image, effectively applying the color inversion effect. The syntax of the method is as follows − PIL.ImageOps.invert(image) Where, image − This is the input image to invert. Example The following example creates an inverted version of an input image using the PIL.ImageOps.invert() function. from PIL import Image import PIL.ImageOps # Open an image input_image = Image.open(”Images/butterfly.jpg”) # Create an inverted version of the image inverted_image = PIL.ImageOps.invert(input_image) # Display the input image input_image.show() # Display the inverted image inverted_image.show() Input Image Output inverted image Applying the Color Inversion to RGBA Images While most functions in the ImageOps module are designed to work with L (grayscale) and RGB images. When you attempt to apply this invert function to an image with RGBA mode (which includes an alpha channel for transparency), it will indeed raise an OSError stating that it is not supported for that image mode. Example Here is an example that demonstrates how to work with RGBA images while handling transparency. from PIL import Image import PIL.ImageOps # Open an image input_image = Image.open(”Images/python logo.png”) # Display the input image input_image.show() # Check if the image has an RGBA mode if input_image.mode == ”RGBA”: # Split the RGBA image into its components r, g, b, a = input_image.split() # Create an RGB image by merging the red, green, and blue components rgb_image = Image.merge(”RGB”, (r, g, b)) # Invert the RGB image inverted_image = PIL.ImageOps.invert(rgb_image) # Split the inverted image into its components r2, g2, b2 = inverted_image.split() # Merge the inverted RGB image with the original alpha channel to maintain transparency final_transparent_image = Image.merge(”RGBA”, (r2, g2, b2, a)) # Show the final transparent image final_transparent_image.show() else: # Invert the image for non-RGBA images inverted_image = PIL.ImageOps.invert(input_image) inverted_image.show() Input Image Output inverted image Print Page Previous Next Advertisements ”;