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 ”;
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
Python Pillow – Environment Setup ”; Previous Next To set up the environment for Pillow, it is recommended to use the pip package manager, as it simplifies downloading and installing Python packages. In this chapter, we will cover how to install the Pillow package on your computer. 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 − How to Install Pillow on MacOS? Installing Pillow in a Python environment on macOS is straightforward and can be done using package management tools like pip or conda. Follow the below steps to set up Pillow on macOS − Open Terminal: We can access the Terminal application on macOS from the Applications folder under Utilities. Check Python Version: It”s a good practice to ensure we have Python installed. To check our Python version to run the following command − python –version Install ”pip” (if not already installed): Most recent versions of Python come with pip pre-installed. To check if pip is installed we can run − pip –version If it”s not installed, we can install it by downloading the get-pip.py script and running it with Python. Download the script using curl − curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py Then run the following script. python get-pip.py Install Pillow: And finally install Pillow using pip by simply run the following command. pip install Pillow This command will download and install Pillow and its dependencies. Now we have successfully set up the Pillow library in our macOS Python environment. We can now start using Pillow for image processing and manipulation tasks. How to Install Pillow on Windows? To install the Python Imaging Library (PIL) or its more up-to-date fork on Windows we can follow these steps − Install Python: If we haven”t already installed Python on our Windows system we can do so by following these steps − Download the latest Python installer for Windows from the official Python website (https://www.python.org/downloads/windows/). Run the installer and during installation and make sure to check the option Add Python X.Y to PATH (replace X.Y with the Python version we are installing). Verify Python Installation: Open a command prompt and check that Python has been installed successfully by running the below code − python –version Install Pillow (Recommended): Pillow is the modern fork of PIL and is more actively maintained. To install Pillow open a command prompt and run the following command − pip install Pillow This command will download and install Pillow and its dependencies on our Windows system. How to Install Pillow on Linux? Setting up the Pillow library in a Python environment on a Linux-based operating system is similar to the process on macOS. Here are the steps for setting up the environment for Pillow on Linux. Check Python Installation: Most Linux distributions come with Python pre-installed. To check if Python is installed first open the terminal and run the following code. python –version Make sure we have Python 3.x installed as Python 2 is no longer supported. Install ”pip” (if not already installed): Most recent versions of Python come with pip pre-installed. To check if pip is installed, run the following code. pip –version If it”s not installed we can install it using the package manager specific to our Linux distribution. For example on Debian/Ubuntu-based systems run the following commands based on the OS. sudo apt-get install python3-pip On Red Hat/CentOS-based systems sudo yum install python3-pip Install Pillow: To install Pillow using pip and run the below command − pip install Pillow This command will download and install Pillow and its dependencies. Verifying Installation To verify that Pillow has been successfully installed in our system, we can create a Python script and import the library − Example from PIL import Image #Create an Image object img = Image.new(”RGB”, (100, 100), color=”blue”) #Display the image img.show() Output Save the script with a .py extension and execute it using Python. If Pillow is installed correctly an image window displaying a red square should appear. Virtual Environment (Optional but Recommended) It”s a good practice to create a virtual environment for our Python projects to keep dependencies isolated. We can create a virtual environment using the following command − python -m venv myenv Replace myenv with the name we want for our virtual environment. To activate the virtual environment run the below code − source myenv/bin/activate Now we can use our virtual environment to work on Python projects that require Pillow. Print Page Previous Next Advertisements ”;
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 ”;