Python is now one of the most widely used programming languages in the world. It can be used to perform various functions and tasks using a simple syntax. Show
One important function Python can perform is automatic processing of digital images, which can be done using Pillow. In this tutorial, we’ll show you how to process images using the Pillow module. Then, we’ll take it a step further and demonstrate how to implement some basic image operations. To follow along with this tutorial, you should have basic knowledge of Python and the Python 3 interpreter installed on your local machine. What is Pillow?Pillow is a fork of the Python Imaging Library (PIL). It is a free and open-source library for manipulating and processing images. PIL is a powerful library in its own right, but it hasn’t been updated since 2009 and doesn’t support Python 3. Pillow provides more features and support for Python 3. Pillow supports a range of image file formats, such as .PNG, .JPEG, .PPM, .GIF, .TIFF, and .BMP. You can perform various operations on images such as cropping, resizing, adding text, rotating, grayscaling, and so much more using this library. Installation and project setupYou can install Pillow using pip, a package manager for Python packages: python3 -m pip install --upgrade pip python3 -m pip install --upgrade Pillow Pillow offers the To get started, first import the from PIL import Image Next, load the image by calling the image = Image.open('sample.jpg') For our examples, we’ll use a sample image from Unsplash. Also worth noting, the images are in the same directory as the Python script file being run. Properties of the Image objectThere are several properties of the image we can access to get more data from the image:
Basic image operationsWe are also able to process and manipulate our images using various operations. Any changes made to the Let’s zoom in and explore some of these operations in more detail. Changing image formatsPillow supports a wide variety of images formats. An image can be converted from one format to another as follows: image = Image.open('sample.jpg') image.save('sample_formatted.png') First, the image is loaded. Then, Pillow sees the file extension specified as
Creating thumbnailsYou can resize images by creating a thumbnail of the image using Pillow. Using the image = Image.open('sample.jpg') image.thumbnail((200, 200)) image.save('sample_thumbnail.jpg') The image is then resized within the maximum limit so as not to be overstretched or blurred. More great articles from LogRocket:
Flipping and rotating imagesIf you need the image to face a different direction, Pillow enables you to flip it. This is done using the
image = Image.open('sample.jpg') image.transpose(Image.FLIP_TOP_BOTTOM) image.save('sample_flip.jpg') The resulting image is flipped vertically. Alternatively, you can rotate images using the image = Image.open('sample.jpg') image.rotate(90) image.save('image_rotate90.jpg') The image is rotated by an angle of 90 degrees. Cropping imagesTo crop an image is to cut out only a specific portion. Cropping often comes into play when editing images for web applications. The image = Image.open('sample.jpg') image.crop(200, 50, 450, 300) image.save('sample_cropped.jpg') In the example above, the first two values represent the starting position from the upper-left; the third and fourth values represent the distance in pixels from the starting position toward the right and bottom direction. The full size of the cropped image can be calculated as 250×250 pixels. Color transformationThere are various forms of pixel representations, including L (luminance), RGB, and CMYK. Pillow allows you to convert images between different pixel representations using the image = Image.open('sample.jpg') grayscale_image = image.convert('L') grayscale_image.save('sample_grayscale.jpg') Using the convert function, the sample image is converted from RGB to L (luminance) mode, which will result in a grayscale image. Image filteringThe act of modifying and enhancing images to improve the appearance can be known as filtering. Using the
For example, let’s take a look at the from PIL import Image, ImageFilter image = Image.open('sample.jpg') edges_image = image.filter(ImageFilter.FIND_EDGES) edges_image.save('sample_edges.jpg') The filter processes the image to display the edges of the image. Any image can be processed using any of the filters available to produce the desired output. Processing images with Pillow: A practical exampleNow that we have a basic understanding of the library, let’s create a simple python script to automate the processing of various types of images. Let’s say you’re given a group of images and asked to add a watermark to each image. To solve the problem, you can create a Python file called First, import all necessary modules: import os from PIL import Image The OS module in Python provides functions for creating and removing a directory and changing and identifying the current directory. Create a directory for the processed image: os.makedirs('watermarked_images') Store the width and height of the logo image: logo_image = Image.open('watermark_logo.png') logo_image = logo_image.resize((50, 50)) logo_width, logo_height = logo_image.size Use the for image in os.listdir('./images'): try: # Separting the filepath from the image's name path, filename = os.path.split(image) filename = os.path.splitext(filename)[0] Open the image: image = Image.open('./images/'+image) #Resizing the image to a set size. edited_image = image.resize((300, 300)) #Setting the position for the placement width = edited_image.width height = edited_image.height Use the paste function to position the logo on the image: edited_image.paste(logo_image, (width - logo_width, height - logo_height), logo_image) Save the images in the new directory: edited_image.save('./watermarked_Images/' + filename + ".jpg") Each image in the directory has been processed and the watermark added. This script enabled us to efficiently perform the task in less time. You can also check out the GitHub repository for the full code and resources associated with this tutorial. ConclusionPillow is a powerful library for processing images in Python. In this tutorial, we established a foundational understanding of how to perform basic operations on images in Python using Pillow. If you want to learn more, check out the official Pillow documentation. LogRocket: Full visibility into your web and mobile appsLogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store. In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page and mobile apps. Try it for free. How do you make a python pillow image?Create Feature Image With Python (Pillow). Install the Pillow Library. To do this Python image programming tutorial, we will use Pillow. ... . Add the Features of Your Image. ... . Find Your Background Image. ... . Create The Color Templates. ... . Define The Functions. ... . Run the Function.. How do you save an image in Python?The PIL module is used for storing, processing, and displaying images in Python. To save images, we can use the PIL. save() function. This function is used to export an image to an external file.
How do I open an image in a Pillow Python?To read an image with Python Pillow library, follow these steps.. Import Image from PIL library.. Use Image. open() method and pass the path to image file as argument. Image. open() returns an Image object. You can store this image object and apply image operations on it.. How do I save a PNG in Python?Use PIL.. original = PIL. Image. open("original.jpg"). file_type = original. format.. print(file_type). original. save("converted.png", format="png"). converted = PIL. Image. open("converted.png"). file_type = converted. format.. print(file_type). |