Python Pillow – Compositing Images ”; Previous Next What is compositing Image? Compositing images in Pillow involve combining two or more images to create a new image. This process often includes blending the pixel values of one image with another based on certain criteria such as transparency or specific blending modes. Pillow provides the Image.alpha_composite() method for compositing images especially when dealing with alpha (transparency) channels. It is commonly used for overlaying one image onto another adding watermarks or creating special effects. Here are the key concepts related to compositing images in Pillow − Image Composition Combining images to create a new image by overlaying one image onto another. The image composting is commonly used for adding watermarks or creating special effects. Alpha Channel The alpha channel represents the transparency of each pixel in an image. Images with an alpha channel can be composited more seamlessly allowing for smooth blending. The Image.alpha_composite() Method The Image.alpha_composite() method in Pillow is used for compositing two images using their alpha channels. It takes two Image objects as input and returns a new Image with the composited result. Here is the syntax and parameters of the Image.alpha_composite() method − PIL.Image.alpha_composite(image1, image2) Where, image1 − The background image onto which the second image will be composited. image2 − The foreground image that will be composited onto the background. Example This example shows how to composite two images using Image.alpha_composite() method. from PIL import Image #Open or create the background image background = Image.open(“Images/decore.png”) #Open or create the foreground image with transparency foreground = Image.open(“Images/library_banner.png”) #Ensure that both images have the same size if background.size != foreground.size: foreground = foreground.resize(background.size) #Perform alpha compositing result = Image.alpha_composite(background, foreground) # Display the resulting image result.show() Image to be used Output Adding Watermarks Using Compositing Images Adding a watermark to an image is one of the applications in image compositing tasks. You can overlay a watermark onto an image at a specific position and transparency. This is achieved by creating a new layer for the watermark and blending it with the base image using the Image.alpha_composite() method. Example This example demonstrates how to to add a watermark onto an image using the Image.alpha_composite() method. The watermark image is placed on top of the base image with adjustable transparency. from PIL import Image # Load the images and convert them to RGBA image = Image.open(”Images/yellow_car.jpg”).convert(”RGBA”) watermark = Image.open(”Images/reading_img2.png”).convert(”RGBA”) # Create an empty RGBA layer with the same size as the image layer = Image.new(”RGBA”, image.size, (0, 0, 0, 0)) layer.paste(watermark, (20, 20)) # Create a copy of the layer and adjust the alpha transparency layer2 = layer.copy() layer2.putalpha(128) # Merge the layer with its transparent copy using the alpha mask layer.paste(layer2, (0, 0), layer2) # Composite the original image with the watermark layer result = Image.alpha_composite(image, layer) # Display the resulting image result.show() Image to be used Watermark Image Output Print Page Previous Next Advertisements ”;
Category: python Pillow
Python Pillow – Converting Image File Formats ”; Previous Next Converting image file formats with Python Pillow is a straightforward process. You can open an image in one format and save it in another, specifying the desired output format. This process typically involves the following steps − Open the Source Image: Use the Image.open() function to open the source image. Save the Image: Use the save() method to save the image in the desired format, specifying the new file format and destination. Pillow can recognize and read over 30 different formats. When using the open() function, Pillow determines the format based on the image content, not just the file name. However, when saving images with the save() method, it usually looks at the file name to decide the format unless you specifically tell which format to use. Pillow Supported File Formats Pillow supports various image formats for both reading and writing. Some formats are fully supported, meaning you can both read from and write to images in those formats. These include popular formats like JPEG, PNG, BMP, BLP, DDS, EPS, GIF, ICNS, ICO, MSP, PCX, PNG, PPM, SGI, TGA, TIFF, WebP, and XBM. Additionally, it provides read-only and write-only support for a range of other formats. Read-Only Formats: CUR, DCX, FITS, FLI, FLC, FPX, GBR, GD, IMT, IPTC/NAA, MCIDAS, MIC, MPO, PCD, PIXAR, PSD, QOI, SUN, WAL, and WMF/EMF. Write-Only Formats: PALM, PDF, and XV Thumbnails. The library can also identify the format of images in formats such as BUFR, GRIB, HDF5, and MPEG. Let”s see the exmaples of converting image file formats with Python Pillow. Example This example converts the image from JPEG to PNG format. from PIL import Image # Open the source image in JPEG format image = Image.open(“Images/logo.jpg”) # Convert and save the image in PNG format image.save(“output_image_PNG_format.png”) print(“Image saved successfully in PNG format…”) Output Image saved successfully in PNG format… Example This example converts the image from BMP to GIF format. from PIL import Image # Open the source image in BMP format image = Image.open(“Images/lena.bmp”) # Convert and save the image in GIF format image.save(“output_image.gif”) print(“Image saved successfully in GIF format…”) Output Image saved successfully in GIF format… Example This example converts the image from GIF to TIFF format. from PIL import Image # Open the source image in GIF format image = Image.open(“Images/Book_Animation.gif”) # Convert and save the image in TIFF format image.save(“output_image.tiff”) print(“Image saved successfully in TIFF format…”) Output Image saved successfully in TIFF format… Example This example converts the image from .bpm file format to .jpg format. from PIL import Image # Open the source image in BMP format image = Image.open(“Images/lena.bmp”) # Convert and save the image in JPEG format image.save(”lena_new.jpg”) print(“Image saved successfully in JPEG format…”) Output Image saved successfully in JPEG format… If you visit the folder where the output images are saved you can observe resultant images. Print Page Previous Next Advertisements ”;
Python Pillow with Tkinter BitmapImage and PhotoImage objects ”; Previous Next The ImageTk module in the python pillow library provides functionality to create and manipulate Tkinter BitmapImage and PhotoImage objects from PIL images. This tutorial discusses the descriptions of the key classes and methods within the ImageTk module. These classes and methods provide convenient ways to work with Tkinter images using PIL in Python, allowing for integration of images into graphical user interfaces. Tkinter BitmapImage class in Python Pillow The ImageTk.BitmapImage class represents a Tkinter-compatible bitmap image that can be utilized wherever Tkinter expects an image object. Here are the key details about the class − The provided image must have a mode of “1”. Pixels with a value of 0 are considered transparent. Additional options, if provided, are forwarded to Tkinter. A commonly used option is foreground, allowing specification of the color for non-transparent parts. Following is the syntax of the ImageTk.BitmapImage() class − class PIL.ImageTk.BitmapImage(image=None, **kw) Where, image − A PIL image with mode “1”. Pixels with value 0 are treated as transparent. **kw − Additional options passed on to Tkinter. The most commonly used option is foreground, which specifies the color for the non-transparent parts. Following are the list of methods provided by the BitmapImage class − height() − Returns the height of the image in pixels. width() − Returns the width of the image in pixels. Example Here is an example demonstrating creating Tkinter windows, loading images with PIL, and then using ImageTk.BitmapImage to create Tkinter-compatible image objects for display in a Tkinter Label. from tkinter import * from PIL import ImageTk, Image # Create a Tkinter window root = Tk() # Create a sample image 1-bit mode image (black and white) pil_image = Image.new(“1″, (700, 300), color=1) # Create a BitmapImage from the PIL image bitmap_image = ImageTk.BitmapImage(pil_image, background=””, foreground=”gray”) # Display the BitmapImage in a Tkinter Label label = Label(root, image=bitmap_image) label.pack() # Run the Tkinter event loop root.mainloop() Output The PhotoImage class in Python Pillow The ImageTk.PhotoImage() class represents a Tkinter-compatible photo image in Pillow, it suitable for use wherever Tkinter expects an image object. Here are the key details about the class − If the image is in RGBA format, pixels with an alpha value of 0 are treated as transparent. The constructor can be initialized with either a PIL image, or a mode and size. Alternatively, you have the option to use the file or data parameters to initialize the photo image object. Here is the syntax of the ImageTk.PhotoImage() class − class PIL.ImageTk.PhotoImage(image=None, size=None, **kw) Where, image − Represents either a PIL image or a mode string. If a mode string is used, a size must also be given. size − If the first argument is a mode string, this defines the size of the image. file − A filename to load the image from using Image.open(file). data − An 8-bit string containing image data, as loaded from an image file. Following are the list of methods provided by the PhotoImage() class − height() − Get the height of the image in pixels. width() − Get the width of the image in pixels. paste(im) − Paste a PIL image into the photo image. Note that this can be slow if the photo image is displayed. Parameters − im – A PIL image. The size must match the target region. If the mode does not match, the image is converted to the mode of the bitmap image. Example Here is an example demonstrating creating Tkinter windows, loading images with PIL, and then using ImageTk.PhotoImage to create Tkinter-compatible image objects for display in a Tkinter Label. from tkinter import * from PIL import ImageTk, Image # Create a Tkinter window root = Tk() # Create a canvas widget canvas = Canvas(root, width=700, height=400, bg=”white”) canvas.grid(row=2, column=3) # Load an image using PIL and create a PhotoImage pil_image = Image.open(“Images/pillow-logo-w.jpg”) tk_image = ImageTk.PhotoImage(pil_image) # Draw the image on the canvas canvas.create_image(20, 20, anchor=NW, image=tk_image) # Start the Tkinter event loop mainloop() Output Print Page Previous Next Advertisements ”;
Python Pillow – ML with Numpy ”; Previous Next Image manipulation with NumPy is a common practice in image processing tasks. NumPy provides a powerful array manipulation library that complements Pillow”s image processing capabilities. This tutorial demonstrates how to use Pillow with NumPy for efficient image processing. Installation Before proceeding, ensure we have NumPy installed. Open the command prompt in administrator mode and execute the following command − pip install numpy Note − This command works only if you have PIP installed and updated. Creating image from Numpy Array When working with NumPy arrays as images, we can use the Image.fromarray() function to create an image memory from an object that exports the array interface, typically using the buffer protocol. If the input array (obj) is contiguous in memory, Pillow can use the array interface directly. If the array is not contiguous, Pillow will use the tobytes method, and frombuffer() will be used to create the image. Here”s the syntax of the fromarray() function − PIL.Image.fromarray(obj, mode=None) Where, obj − The object exporting the array interface. This is usually a NumPy array, but it can be any object that exposes the required interface. mode (optional) − The mode parameter specifies the color mode or pixel format of the resulting image. If not provided, the mode is inferred from the type of the input array. It”s important to note that Pillow modes (color modes) do not always correspond directly to NumPy data types (dtypes). Pillow modes include options for 1-bit pixels, 8-bit pixels, 32-bit signed integer pixels, and 32-bit floating-point pixels. The mode is either explicitly specified or inferred from the dtype of the input array. Example In this example, a NumPy array is created, and then Image.fromarray() is used to create a Pillow Image from the NumPy array. The resulting image is a Pillow Image object that can be further processed or saved. from PIL import Image import numpy as np # Create a NumPy array arr = np.zeros([150, 250, 3], dtype=np.uint8) arr[:,:100] = [255, 128, 0] arr[:,100:] = [0, 0, 255] # Create a Pillow Image from the NumPy array image = Image.fromarray(arr) # Display the created image image.show() Output Example Here is another example that create a Pillow Image from the NumPy array by explicitly specifying the mode. from PIL import Image import numpy as np # Create a NumPy array arr = np.zeros([250, 350, 3], dtype=np.uint8) arr[:100, :200] = 250 # Create a Pillow Image from the NumPy array by explicitly specifying the mode image = Image.fromarray(arr, mode=”RGB”) # Display the created image image.show() Output Example This example creates a grayscale image from a numpy 2-dimensional array by explicitly specifying the mode equal to “L”. from PIL import Image import numpy as np # Create a NumPy array arr = np.zeros([300, 700], dtype=np.uint8) arr[100:200, 100:600] = 250 # Create a Pillow grayscale Image from the NumPy array # by explicitly specifying the mode image = Image.fromarray(arr, mode=”L”) print(“Pixel values of image at (150, 150) of the grayscale image is:”, image.getpixel((150, 150))) # Display the created image image.show() Output Pixel values of image at (150, 150) of the grayscale image is: 250 Creating numpy array from a Pillow Image The numpy.asarray() function can be used to convert a Pillow image to a NumPy array. However, it”s important to note that when converting Pillow images to arrays, only the pixel values are transferred. This means that certain image modes, like P and PA, will lose their palette information during the conversion. Example The following example demonstrates how to convert a Pillow image to a NumPy array. from PIL import Image import numpy as np # Open an image as a pillow image object image = Image.open(“Images/TP logo.jpg”) # Convert the Pillow image to a NumPy array result = np.asarray(image) # Display the type, shape and dtype of the NumPy array print(“Type:”, type(result)) print(“Shape:”, result.shape) print(“Dtype:”, result.dtype) Output Type: <class ”numpy.ndarray”> Shape: (225, 225, 3) Dtype: uint8 Print Page Previous Next Advertisements ”;
Python Pillow – Useful Resources ”; Previous Next The following resources contain additional information on Python Pillow. Please use them to get more in-depth knowledge on this. Useful Video Courses Python Flask and SQLAlchemy ORM 22 Lectures 1.5 hours Jack Chan More Detail Python and Elixir Programming Bundle Course 81 Lectures 9.5 hours Pranjal Srivastava More Detail TKinter Course – Build Python GUI Apps 49 Lectures 4 hours John Elder More Detail A Beginner”s Guide to Python and Data Science 81 Lectures 8.5 hours Datai Team Academy More Detail Deploy Face Recognition Project With Python, Django, And Machine Learning Best Seller 93 Lectures 6.5 hours Srikanth Guskra More Detail Professional Python Web Development with Flask 80 Lectures 12 hours Stone River ELearning More Detail Print Page Previous Next Advertisements ”;
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 ”;
Python Pillow – Merging Images ”; Previous Next Pillow (PIL) library is used for merging or combining individual bands of an image to create a new multiband image. It”s particularly useful when working with multispectral or multichannel images such as RGB or CMYK images and we want to create a new image by merging specific bands. In pillow we have the merge() method which belongs to the Image module which is used to merge the given input images. This method is useful for tasks like combining multiple channels of satellite or medical images, creating custom color images or working with images that have separate channels that need to be combined into a single image. Here”s the syntax and usage of the Image.merge() method − Image.merge(mode, bands) Where, mode − This parameter specifies the mode of the new multiband image. It should match the mode of the individual bands we want to merge. Common modes include “RGB” for color images, “RGBA” for images with an alpha channel, and “CMYK” for cyan, magenta, yellow and black color spaces. bands − This parameter is a tuple of individual image bands that we want to merge. Each band should be a single-channel image or a grayscale image. Example Here is an example of how to use the Image.merge() method to merge the red, green and blue bands of an image to create a new RGB image. from PIL import Image image = Image.open(“Images/butterfly.jpg”) r, g, b = image.split() image = Image.merge(“RGB”, (b, g, r)) image.show() Image to be used Output Example Here, in this example we are merging two input images by using the merge() method of the Image module of pillow library. from PIL import Image image1 = Image.open(“Images/butterfly.jpg”) image2 = Image.open(“Images/hand writing.jpg”) #resize, first image image1 = image1.resize((426, 240)) image1_size = image1.size image2_size = image2.size new_image = Image.new(“RGB”,(2*image1_size[0], image1_size[1]), (250,250,250)) new_image.paste(image1,(0,0)) new_image.paste(image2,(image1_size[0],1)) new_image.save(“output Image/merged.jpg”) new_image.show() The two images to be merged Output Print Page Previous Next Advertisements ”;
Pillow – Resizing an Image ”; Previous Next Resizing an image in Pillow Library involves changing the dimensions i.e. width and height of the image. This operation can be used to make an image larger or smaller and it can serve various purposes such as preparing images for display on a website, reducing file size or generating thumbnails. Resizing an Image using the resize() method In Pillow the resize() method is used to change the dimensions of an image. This function allows us to resize an image in the following ways. Absolute Dimensions − We can specify the new width and height in pixels to which the image should be resized. Maintaining Aspect Ratio − If We only specify one dimension either width or height then Pillow can automatically calculate the other dimension to maintain the image”s aspect ratio. Scaling − We can resize the image by a scale factor which uniformly resizes both width and height while preserving the aspect ratio. Here”s the basic syntax for the resize() method − PIL.Image.resize(size, resample=3) Where, size − This can be either a tuple specifying the new width and height in pixels i.e. a single integer specifying the new size (width or height) or a float specifying a scaling factor. resample(optional) − The default value is 3 which corresponds to the anti-aliased high-quality filter. We can choose from various resampling filters such as Image.NEAREST, Image.BOX, Image.BILINEAR, Image.HAMMING, Image.BICUBIC, Image.LANCZOS, etc. Following is the input image used in all the examples of this chapter. Example In this example we are using the resize() function for adjusting the width and height of the image by passing a tuple as input parameter. from PIL import Image #Open an image image = Image.open(“Images/rose.jpg”) #Resize to specific dimensions (e.g., 300×200 pixels) new_size = (300, 200) resized_image = image.resize(new_size) #Display resized image resized_image.show() Output Example Here in this example we are resizing the image by maintaining the same aspect ratio of the original input image. from PIL import Image #Open an image image = Image.open(“Images/rose.jpg”) #Resize by maintaining aspect ratio (e.g., specify the width) new_width = 200 aspect_ratio_preserved = image.resize((new_width, int(image.height * (new_width / image.width)))) aspect_ratio_preserved.show() Output Example In this example we are resizing the image with the scale by factor. from PIL import Image #Open an image image = Image.open(“Images/rose.jpg”) #Scale the image by a factor (e.g., 10% of the original size) scaling_factor = 0.1 scaled_image = image.resize((int(image.width * scaling_factor), int(image.height * scaling_factor))) scaled_image.show() Output Print Page Previous Next Advertisements ”;
Python Pillow – Home
Python Pillow Tutorial Table of content Python Pillow Tutorial Why to Learn Python Pillow? Features of Python Pillow Applications of Python Pillow Installing Python Pillow Who Should Learn Python Pillow Python Pillow Jobs and Opportunities Prerequisites to Learn Python Pillow Frequently Asked Questions about Python Pillow PDF Version Quick Guide Resources Job Search Discussion Python Pillow Tutorial Pillow or the Python Imaging Library (PIL) fork by Jeffrey A.Clark and contributors, is an open-source library that makes it easy to work with images in Python. It is one of the important libraries of python for image processing. It provides a comprehensive suite of tools and functions for image processing tasks, from basic operations to advanced image manipulation. In this tutorial, you will see the hands-on approach to learn different functionalities of pillow, From loading and saving images to performing image enhancements, transformations, and more. Why to Learn Python Pillow? Learning Pillow is essential for anyone interested in image processing using Python. Its ease of use and integration with other Python libraries make it a valuable tool for a variety of applications, from basic image manipulations to advanced computer vision projects. Pillow supports a wide range of image file formats, including JPEG, PNG, GIF, TIFF, and many others. This flexibility allows you to read images from various sources and save your processed images in the desired format. Whether you are working on simple image resizing or complex image transformations, Pillow has the capabilities you need. By mastering Pillow, you”ll be able to handle images effortlessly, extract useful information, and apply meaningful transformations to visual data. Features of Python Pillow Following are the main features of Python Pillow − Pillow is an open-source library, freely available for use and contribution. Easy to read and write images of various formats. The library support for various image formats including JPEG, PNG, GIF, TIFF, BMP, and more. This flexibility allows you to handle images from different sources. It offers a wide range of image processing tools, making it easy to manipulate and transform images to meet specific needs. The library includes various predefined image enhancement filters, such as brightness, sharpness, and color adjustments. Additionally, it supports different image filters for effects like blurring, contouring, and edge detection. With Pillow, you can perform complex image transformations such as affine, perspective, and projective transformations, allowing for advanced image manipulation tasks. And it offers a user-friendly API that simplifies the process of performing image processing tasks. Applications of Python Pillow Pillow is a powerful tool widely used in various applications involving image processing and computer vision. Whether you are developing web applications that require image uploads, creating image processing scripts, or analyzing images, Pillow provides a rich set of tools to achieve your goals. And this Library is best suited for image archival and batch processing applications. Installing Python Pillow To install Pillow you can simply use pip (the default package manager for Python), just run the below command in your command prompt − pip install pillow For detailed installation instructions, visit the Environment Setup chapter. Who Should Learn Python Pillow? This tutorial is basically designed to work as a guide for individuals who wants to learn python capabilities, automate image editing. It is also for the beginners who wish to know the image processing capabilities of python using pillow package and for the web developers who wants to update and use images with logos & watermark on their websites. Python Pillow Jobs and Opportunities Proficiency in Pillow opens up a range of career opportunities in industries such as − Web Development Data Science Machine Learning Computer Vision Job roles like Image Processing Engineer, Computer Vision Developer, Data Scientist specializing in image analysis, Machine Learning Engineer, and Data Analyst often require knowledge of Pillow. Prerequisites to Learn Python Pillow To get started with Pillow, familiarity with Python programming is essential. Knowledge of basic concepts such as python data types, functions, and libraries will help you understand Pillow”s functionality more effectively. Additionally, being comfortable with installing Python packages using pip (e.g., “pip install pillow”) will be helpful. Frequently Asked Questions about Python Pillow There are some very Frequently Asked Questions(FAQ) about Python Pillow, this section tries to answer them briefly. What is Pillow in Python used for? Pillow is a powerful library used for image processing in Python. What are the capabilities of Pillow in Python? Pillow allows users to perform various image processing tasks such as opening and loading images, resizing, cropping, rotation, color adjustment, filtering, text and drawing, color mode conversion, histogram equalization, metadata handling, and more. How to resize image in python pillow? To resize an image in Python using Pillow, you can use the resize() function from the pillow’s Image module. How to install pillow in Python? Installing Pillow in Python can be done by using pip or conda installers, which depends on your preference. You can install Pillow in Python using pip. Simply run pip install Pillow in your command prompt or terminal. What color format is Python pillow? Python Pillow supports various color formats, including RGB, RGBA, CMYK, and grayscale. Is Pillow a standard Python library? No, Pillow is not a standard Python library it is not integrated in the standard library and does not come with distributions of Python. You need to install it separately using pip. What formats can pillow Python save? Pillow in Python can save images in various formats, including JPEG, PNG, BMP, GIF, TIFF, BPL, and many more. Which Python version supports Pillow? The current Pillow versions 10.1 supports the following Python versions − Python 3.12 Python 3.11 Python 3.10 Python 3.9 Python 3.8 Which is the best place to learn Python Pillow? You can use our simple and the best Python Pillow tutorial to learn Python Pillow. Our tutorial offers an excellent starting point for learning Image processing with Python Pillow. You can explore our simple and effective learning materials at your own pace. Also, you can find resources to learn Python Pillow on
Python Pillow – Flip and Rotate Images ”; Previous Next Flipping and rotating images are basic image processing tasks often used to enhance visibility, correct orientation, or achieve specific effects. The Python Pillow library provides simple methods to perform these operations on images. Flipping images Flipping an image is an image processing operation that involves reversing the orientation of the image along a specified axis. This operation can be performed either horizontally i.e. left to right or vertically i.e. top to bottom. In digital image processing flipping is often used for various purposes such as mirroring, correcting for camera orientation or achieving artistic effects. In the context of image flipping there are two primary types, one is horizontal flip and other is vertical flip. Horizontal Flip (Left to Right) − In a horizontal flip each row of pixels is reversed effectively mirroring the image from left to right. Vertical Flip (Top to Bottom) − In a vertical flip each column of pixels is reversed effectively mirroring the image from top to bottom. These can be achieved by using the transpose() method of the Image module of the pillow library. Flipping images using the transpose() method The transpose() method in Pillow is used to manipulate the orientation of an image. It allows us to perform various transformations on the image such as rotating and mirroring by specifying the type of transpose operation we want to apply. The following is the syntax and parameters of the transpose() method. PIL.Image.transpose(method) Where, method − The transpose method to be applied. It can take one of the following values − Image.Transpose.ROTATE_90 − Rotate the image 90 degrees counterclockwise. Image.Transpose.ROTATE_180 − Rotate the image 180 degrees. Image.Transpose.ROTATE_270 − Rotate the image 90 degrees clockwise. Image.Transpose.FLIP_LEFT_RIGHT − Flip the image horizontally i.e. left to right. Image.Transpose.FLIP_TOP_BOTTOM − Flip the image vertically i.e. top to bottom. Following is the input image used in all the examples of this chapter. Example In this example we are using the transpose() method to flip the input image by 90 degrees counterclockwise. from PIL import Image #Open an image image = Image.open(“Images/image_.jpg”) #Rotate the image 90 degrees counterclockwise rotated_image = image.transpose(Image.Transpose.ROTATE_90) #Save or display the rotated image rotated_image.save(“output Image/rotated_image.jpg”) open_rotated_image = Image.open(“output Image/rotated_image.jpg”) open_rotated_image.show() Output Example In this example we are using the transpose() method to flip the input image by horizontally. from PIL import Image #Open an image image = Image.open(“Images/image_.jpg”) #Flip the image horizontally (left to right) flipped_image = image.transpose(Image.Transpose.FLIP_LEFT_RIGHT) #Save or display the rotated image flipped_image.save(“output Image/flipped_image.jpg”) open_flipped_image = Image.open(“output Image/flipped_image.jpg”) open_flipped_image.show() Output Example In this example we are using the transpose() method by using FLIP_TOP_BOTTOM parameter to flip the input image by vertically. from PIL import Image #Open an image image = Image.open(“Images/image_.jpg”) #Flip the image horizontally (left to right) vflipped_image = image.transpose(Image.Transpose.FLIP_TOP_BOTTOM) #Save or display the rotated image vflipped_image.save(“output Image/vflipped_image.jpg”) open_flipped_image = Image.open(“output Image/vflipped_image.jpg”) open_flipped_image.show() Output Rotating Images Rotating an image in Pillow (Python Imaging Library) refers to the process of changing the orientation of an image by a specific angle. This can be useful for various purposes such as correcting the orientation of photos, creating special effects or aligning images. Pillow provides the rotate() method to perform this operation. The below are the points we need to know about rotating images in Pillow. Rotate by Angle − The rotate() method allows us to specify the angle in degrees by which we want to rotate the image. A positive angle rotates the image counterclockwise and a negative angle rotates it clockwise. Canvas Expansion − By default when we rotate an image it may not fit entirely within the original image canvas and which can lead to cropping. Then we can use the expand parameter to ensure that the rotated image fits within the canvas without being cropped. Rotating images using the rotate() method The rotate() method in Image module is used to perform rotation of the given input image. Here the following is the basic syntax of the rotate() method. PIL.Image.rotate(angle, expand=False, resample=3) Where, angle − This parameter specifies the angle of rotation in degrees. Positive values rotate the image counterclockwise while negative values rotate it clockwise. expand (optional) − If it is set to True it allows the image canvas to be expanded to ensure that the entire rotated image fits within it. If it is set to ”False” (the default) the image is cropped to fit within the original canvas. resample (optional) − An optional resampling filter. The default value is ”3” which corresponds to the anti-aliased high-quality filter. We can choose from various resampling filters such as ”Image.NEAREST”, ”Image.BOX”, ”Image.BILINEAR”, ”Image.HAMMING”, ”Image.BICUBIC”, ”Image.LANCZOS”, etc. Following is the input image used in all the examples of this chapter. Example In this example we are using the rotate() method for rotating the given input image by 45 degrees. from PIL import Image #Open an image image = Image.open(“Images/flowers.jpg”) #Rotate the image by 45 degrees counterclockwise rotated_image = image.rotate(45) #Save the rotated image rotated_image.save(“output.jpg”) rotated_image.show() Output Example Here in this example we are rotating the input image by ensuring the rotated image fits within the canvas without cropping. This can be achieved by setting the expand parameter to True. from PIL import Image #Open an image image = Image.open(“Images/flowers.jpg”) #Rotate the image by 45 degrees and expand the canvas to fit the entire rotated image rotated_image = image.rotate(45, expand=True) rotated_image.show() Output Example In this example we