Python Pillow – Adding Borders to Images

Python Pillow – Adding Borders to Images ”; Previous Next Adding borders to images is one of the common task in image processing. Borders can help to frame the content, draw attention to specific areas, or add a decorative element. In Pillow (PIL) the expand() method of the ImageOps module is used to increase the dimensions of an image by adding a border or padding around it. This can be helpful for various purposes such as adding a border, creating a canvas of a specific size or resizing the image to fit a particular aspect ratio. The expand() method The expand() method is useful for adding borders to images and adjusting their dimensions while maintaining the aspect ratio. We can customize the size and border color to suit our specific requirements. Here”s the basic syntax for the expand() method − PIL.Image.expand(size, fill=None) Where, size − A tuple specifying the new dimensions i.e. width and height for the expanded image. fill (optional) − An optional color value to fill the border area. It should be specified as a color tuple (R, G, B) or an integer value representing the color. Following is the input image used in all the examples of this chapter. Example In this example we are using the expand() method to create the expanded image with the border. from PIL import Image, ImageOps #Open an image image = Image.open(“Images/hand writing.jpg”) #Define the new dimensions for the expanded image new_width = image.width + 40 #Add 40 pixels to the width new_height = image.height + 40 #Add 40 pixels to the height #Expand the image with a white border expanded_image = ImageOps.expand(image, border=20, fill=”red”) #Save or display the expanded image expanded_image.save(“output Image/expanded_output.jpg”) open_expand = Image.open(“output Image/expanded_output.jpg”) open_expand.show() Output Example Here this is another example we are expanding the image border with blue color by using the expand() method of the Image module. from PIL import Image, ImageOps #Open an image image = Image.open(“Images/hand writing.jpg”) #Define the new dimensions for the expanded image new_width = image.width + 40 #Add 40 pixels to the width new_height = image.height + 40 #Add 40 pixels to the height #Expand the image with a white border expanded_image = ImageOps.expand(image, border=100, fill=”blue”) #Save or display the expanded image expanded_image.save(“output Image/expanded_output.jpg”) open_expand = Image.open(“output Image/expanded_output.jpg”) open_expand.show() Output Print Page Previous Next Advertisements ”;

Python Pillow – Cropping an Image

Pillow – Cropping an Image ”; Previous Next Cropping an image in Pillow (Python Imaging Library) involves selecting a specific region or subarea of an image and creating a new image from that region. This operation is useful for removing unwanted parts of an image and focusing on a particular subject or resizing an image to specific dimensions. The Image module of the pillow library provides the crop() method to perform the crop operation on the images. Cropping an Image using the crop() method Cropping an image can be done by using the crop() method, which allows us to define a box specifying the coordinates of the left, upper, right and lower corners of the region that we want to retain and then it creates a new image with only that portion of the original image. Here is the basic syntax for the crop() method in Pillow library − PIL.Image.crop(box) Where, box − A tuple specifying the coordinates of the cropping box in the format (left, upper, right, lower). These coordinates represent the left, upper, right and lower edges of the rectangular region we want to retain. Example In this example we are cropping the image by using the crop() method by passing the left, upper, right and lower corners of the image region that we want. from PIL import Image #Open an image image = Image.open(“Images/saved_image.jpg”) # Display the inaput image image.show() #Define the coordinates for the region to be cropped (left, upper, right, lower) left = 100 upper = 50 right = 300 lower = 250 #Crop the image using the coordinates cropped_image = image.crop((left, upper, right, lower)) #Display the cropped image as a new file cropped_image.show() Output The above code will generate the following output − Input image: Output image cropped image: Example Here this is another example of performing the crop operation of the specified portion of the input image using the crop() method. from PIL import Image #Open an image image = Image.open(“Images/yellow_car.jpg”) # Display the inaput image image.show() #Define the coordinates for the region to be cropped (left, upper, right, lower) left = 100 upper = 100 right = 300 lower = 300 #Crop the image using the coordinates cropped_image = image.crop((left, upper, right, lower)) #Display the cropped image cropped_image.show() Output On executing the above code you will get the following output − Input image: Output cropped image: Print Page Previous Next Advertisements ”;

Python Pillow – Working with Images

Python Pillow – Working with Images ”; Previous Next Opening, writing, displaying and saving images are the fundamental operations while working with images using python pillow library. The Python Pillow library provides a wide range of tools for image processing tasks, providing straightforward methods and customizable options for these basic operations. In this tutorial, you will lean essential aspects of working with images using the Pillow library including reading, displaying,writting, and saving images. Reading Images Reading images, refers to the process of opening and reading image files and making them accessible for manipulation and processing within a Python program. In Pillow the Image module provides the function open() to perform loading of the given input image. When we call Image.open() it reads the specified image file, decodes the image and creates a Pillow Image object representing the image. This object can then be used for various image processing tasks. Reading images using open() function The Image.open() function is capable of loading different image formats such as JPEG, PNG, GIF, BMP, TIFF, ICO and so on. The below is the syntax and parameters of this function. PIL.Image.open(fp, mode=”r”, formats = None) Where, fp − A filename or path or URL of an image within the string format. mode (optional) − The mode parameter is used to set the image into open mode and it should be assigned as r. formats (optional) − A list or tuple of formats which to be loaded. This can be used as the restriction of the file formats to be loaded. This function returns the image as the output. Here for displaying the image we have to use the show() function of the Image module. Example In this example we are loading an image by specifying the path of the image in the string format and defining the mode as r. from PIL import Image #Load an image loaded_image = Image.open(“Images/butterfly.jpg”, mode = ”r”) loaded_image.show() #Saving the image img.save(“Output_Images/reading.png”) Image to be used Output Example In this example we are loading the image from the image url. So to perform that we have to use urllib.request() module for reading the image url. We use the urlretrieve() function of the urllib.request module to download the image from the URL and save it to the local filesystem with the specified filename. import urllib.request from PIL import Image url = “https://www.tutorialspoint.com/images/logo.png” #Download the image using urllib urllib.request.urlretrieve(url, “image.png”) #Open the downloaded image in PIL loading_image = Image.open(“image.png”, mode = ”r”) #Show the image loading_image.show() Output Example In this example we are passing the image name and the formats = None as the input parameters. from PIL import Image #load the image loading_image = Image.open(“pillow.jpg”, formats = None) #Show the image loading_image.show() Output Writing Images Writing images are nothing but creating new image files from scratch or modifying existing ones such as drawing, pixel manipulation and compositing. The resulting image can then be further processed or saved to disk using other Pillow functions and methods. Writing images using new() method You can use the new() method from the Image module to create a blank image with a specified mode and size. It”s a way to generate a blank or uninitialized image with the desired characteristics. The following is the syntax for Image.new() − PIL.Image.new(mode, size, color) Where, mode − This parameter specifies the color mode for the image such as “RGB” for full-color images or “L” for grayscale. The available modes depend on the version of Pillow and the capabilities of the underlying image libraries (e.g., “RGB,” “RGBA,” “L,” “CMYK,” etc.). size − This parameter is a tuple specifying the width and height of the image in pixels. For example to create a 300×200-pixel image we can use ”(300, 200)”. color” (optional) − This parameter specifies the initial color of the image. It”s an optional parameter and can be a single color value or a tuple for multi-channel images. The default color is black for most modes. Example In this example we are creating a new image with black using the new() method in Image module in pillow library. from PIL import Image #Create a new 300×200 pixel RGB image filled with white img = Image.new(”RGB”, (300, 200), color=”black”) img.show() Output Example Here, in this example we are creating a new image with blue color of width 600 and height 600 using the new() method in Image module of the pillow. from PIL import Image #Create a new 300×200 pixel RGB image filled with white img = Image.new(”RGB”, (500, 200), color=”blue”) img.show() Output Displaying Image Displaying images is about rendering the image on the screen so you can view it. Pillow provides the show() method to display an image using the default image viewer of the system. Displaying images using the show() method The show() method in Image module does not require any parameters or arguments. This is a straightforward. Syntax The below is the syntax of show() function − PIL.Image.show() Example In this example we are displaying the output of the open() function using the show() function of Image module. from PIL import Image #Open an image image = Image.open(“Images/hand writing.jpg”) #Display the image using the default image viewer image.show() Output Displaying Images in the Jupyter Notebook Environment If we are working in a Jupyter Notebook environment then we can display images directly in the notebook using the IPython display() function. The following is the syntax and parameters of the display() function

Python Pillow – Overview

Python pillow – Overview ”; Previous Next 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, Scikit-image, Pillow, Mahotas and more. However, in this tutorial, we are only focusing on Pillow library and will try to explore various capabilities of this module. What is Pillow? Pillow or the Python Imaging Library (PIL) fork by Jeffrey A.Clark and contributors, is a powerful Python library for working with digital images and Image processing. It”s built on top of the Python Image Library (PIL) and offers a wide range of functionalities for working with images. It provides extensive functionality for opening, manipulating and saving images in various formats. Pillow is a widely used tool in applications involving image processing, computer vision, web development, graphic design and more. Pillow offers a wide range of tools and functions for image processing, allowing you to perform tasks such as − Opening and Loading Images − Pillow allows us to open and load images in various formats making them available for processing. Resizing and Scaling − We can resize images to specific dimensions, scale them up or down and generate thumbnails. Cropping − Image cropping involves removing unwanted portions of an image to focus on a specific region. Rotation and Flipping − Images can be rotated to correct orientation or for creative purposes. We can also flip images horizontally or vertically. Color Adjustment − Pillow provides functions to adjust image properties, including brightness, contrast and color balance. Filtering and Effects − Image filtering involves applying filters like blurring, sharpening, edge detection and various effects to enhance or modify the appearance of images. Text and Drawing − We can add text, shapes and drawings to images which is useful for annotation and labeling. Color Mode Conversion − Pillow supports converting images between different color modes such as RGB, grayscale and CMYK. Histogram Equalization − This is a technique for enhancing the contrast of an image by redistributing pixel values. Image Filtering − We can apply custom convolution filters to images allowing for advanced image processing operations. Geometric Transformations − Pillow supports geometric transformations like affine and perspective transformations which are used for tasks such as correcting image distortion. Merging and Compositing − We can merge multiple images or overlay images to create composite images or visual effects. Metadata Handling − Pillow allows us to access and modify image metadata such as EXIF and ICC profiles which can be useful for data extraction and management. Data Access and Analysis − We can access and manipulate pixel data at a low level enabling more advanced image processing and analysis tasks. Why Pillow? Pillow is a preferred choice for image processing in Python due to its − Image Processing Capabilities − Pillow provides a comprehensive set of tools for image manipulation such as opening, editing, enhancing and saving images. It supports various image formats for making it versatile for handling different types of image data. Ease of Use − Python as a high-level programming language is known for its readability and simplicity. Pillow inherits these characteristics and making it easy for developers to work with images even if they have minimal experience in image processing. Platform Independence − Python is platform-independent and so is Pillow. This means we can use Pillow to process images on different operating systems without worrying about compatibility issues. Abundance of Documentation − Python and Pillow have extensive documentation, tutorials and a supportive community which simplifies the learning curve for newcomers and provides a wealth of resources for experienced developers. Integration with Other Libraries − Python can seamlessly integrate Pillow with other popular libraries and frameworks such as NumPy and OpenCV for advanced image processing and computer vision tasks. Open Source − Both Python and Pillow are open-source which means they are free to use and continually improved by a large community of contributors. Basic Example Here is a basic example to get you started with Pillow. Opening and Displaying an Image This example demonstrates how to open and display an image in Python Pillow. from PIL import Image #Load an image loaded_image = Image.open(“Images/logo-w.png”) # Display the image loaded_image.show() Output The above code will load an image from the specified path and display it using the default image viewer on your system. Print Page Previous Next Advertisements ”;