Resizing images is an integral part of the web, whether to display images on your website or app, store lower-resolution images, or generate a training set for neural networks. Show
Python offers a rich set of options to perform some of the routine image resizing tasks. This article will walk you through those options and look at ImageKit - a cloud-based, ready-to-use solution that offers real-time image manipulation. We will look at
Before we get startedMake sure you have a recent version of Python installed on your system, preferably Python 3.6+, then spin up a virtual environment.
When we get to ImageKit later in this article, you will need to sign up for a free account on ImageKit's website. The free plan has access to all the features we need for image resizing and other transformations. We will be using an image by Asad from Pexels for all examples in this article. This image is also hosted on ImageKit.
Resizing Images using Pillow (PIL)Pillow is one of the most popular options for performing basic image manipulation tasks such as cropping, resizing, or adding watermarks. Install the latest version of Pillow with 6.
Pillow provides the resize() method, which takes a (width, height) tuple as an argument.
We read our image using the 7 method from the Image module. Then we use 8 with a tuple, representing the width and height of the output image, respectively, as an argument containing the new size.Here is how our resized image looks like The output of the resized imageMaintain Aspect Ratio while ResizingThe 8 method is pretty handy and quick to work with, but it doesn't always give the best results. Images resized using this method may be stretched or forced to fit in a box and therefore skewed.ImageKit makes it ridiculously easy to resize images while maintaining the aspect ratio. See how ImageKit works for resizing.
0 method can address the problem of skewing, it creates a thumbnail version of the image whose size does not exceed the dimensions specified in the arguments.
The thumbnail method resizes the image in place without returning an image object. Therefore, make sure to save the file with a different name. Resized image to suit a thumbnailCropping an image with PillowThe 1 method used to crop an image accepts a 4-tuple of the x and y coordinates of the top-left and the bottom-right corner of the crop area.So, if we want to crop an image from the (300,300) point to (700,900) point, the code would be
There is an easier method of using 2. The 3 method accepts two arguments:
Here is our sample image cropped by 600px from all sides. Image cropped with PillowYou should check out the pillow handbook for more complex image operations. Bonus: Adding a watermark to an imageTo add watermarks, we need to use the ImageDraw and ImageFont methods. The ImageDraw module provides simple-to-use APIs for working with 2D graphics, from creating polygons to writing text. ImageFont sets the font of the watermark text.
Make sure to choose a font that is available on your system. You can set the position, fill, anchor, or language. You can also download a font of your choice and provide the path to it. Here is the sample output - Applying a simple watermark on the imageResizing images using OpenCV
First, let's install the latest opencv for Python using pip.
Note that we are using OpenCV 4.5 for this tutorial. 6 is the name of the Python wrapper.Resizing with OpenCVAlthough OpenCV is a viable choice for image resizing, it is best suited for heavy-duty tasks like object detection. Stick to Pillow for basic image manipulation or . Resizing images can be done by 7 method.
Cropping an image with OpenCVOpenCV uses a NumPy array under the hood for representing images. We can leverage array slicing to extract the part of the pixels we need, i.e., crop the image. Since this is a 2D array, we need to specify the start and end coordinates, just like we did while cropping images with Pillow. Though, the syntax here is slightly different. If we want to crop an image starting at (0,0) point to (2732, 3640) point, then we can do this with OpenCV as shown below 0You can read more about image processing tutorials from OpenCV. Using ImageKit to resize and crop imagesBoth Pillow and OpenCV are good options to resize and crop images. But these solutions require extensive setup and maintenance in line with the changing business needs. ImageKit.io is a real-time image and video optimization, manipulation, and storage product that can help you do basic resizing and cropping on your images and more. You have the flexibility to either upload your images to the integrated media library or attach your existing cloud storage or servers to ImageKit and start delivering optimized files. Several image and video optimizations are done automatically, considering multiple factors, whereas resizing, cropping, and other transformations can be done by simply modifying the URL in real-time. Setup with ImageKitIn our example, we have already uploaded the sample image to ImageKit.
You should sign up for a free account on ImageKit that comes with an ample amount of storage and delivery bandwidth. You can download the original image from Pexels from here and upload it to your media library. We will be using ImageKit's Python SDK to create the resized and cropped image URLs. You can install this SDK using the following command - 2Basic resizing by changing height and widthResizing images in ImageKit is simple. Just add the required dimension transformation to the URL, and you will get the resized image in real-time. For example, to get the sample image with a width of 200px, the URL will be - 3Image resized to width 200px using URL-based transformation parametersWhile this is a simple string append operation, the Python SDK makes the code simpler and readable. 4Example of generating a URL at width 200px with the Python SDKSimilarly, if we want to get a 400 x 300px resized image from ImageKit, the URL will contain height and width transformation parameters. 5The corresponding code with the Python SDK will be 6There are several other image transformation options with ImageKit. You can read about them from the product documentation or from the Python SDK documentation. Cropping images with a specific aspect ratioAnother transformation available in ImageKit is the aspect ratio transformation. You can use it with either the width or the height transformation to fix the output image's aspect ratio and transformations. For example, to get an image at 800px width with an aspect ratio 4:3, the URL will be 7Cropping options available with ImageKitIn the above examples, if the output aspect ratio doesn't match the input aspect ratio, the image gets cropped around the center of the original by default. However, ImageKit gives us multiple cropping options that can prevent cropping on the image and help us get the required output. Let's look at some of the standard cropping options below. 1. No cropping - Forcing Requested Dimensions You can do this by adding the 8 transformation parameter to the URL. This will force-fit the image to the size requested. Though, because this is a force fit, it may cause the image to get skewed. 8The image is force-fit to the 400x200px sizeIn the Python SDK, this can be specified using the 9 transformation 92. Fit inside a container The 0 crop strategy fits the image inside a container with a defined height and width while preserving the aspect ratio. Either the height or width of the image may differ from the requested dimensions, and the resulting image will always be smaller than the dimensions specified. 0The image fits inside the 400x200px box3. Fit outside a container Opposite to the 0 crop, the 2 crop results in an image that is at least the size that is specified using the height and width dimensions. Either the height or width of the image may differ from the requested dimensions, and the resulting image will always be larger than the dimensions specified. 1The resulting image is larger than the 400x200px dimension specified4. Pad an image If you still want the resulting image to match the output dimension requested but not get cropped, you can use the 3 crop mode. Note that this is different from the 9 transformations used above and is specified using the 5 transformation. You can also specify the padding color that is added around the image using the background transformation. 2The resulting URL is 3Image with padding using URL a parameterYou can see grey-colored padding around the image, which perfectly fits the 400 x 200px output dimensions without cropping the image. Bonus: Adding watermarks to an image using ImageKitImageKit offers more than 40+ different real-time transformation parameters for images. Let's look at an example to add text on the image in the top-left corner of our base image. Here we specify the text, its font size, and font color in the URL itself. 4The resulting image URL is 5Adding watermark to the image with a URL parameter
ConclusionHere's a quick summary of what we learned today. We looked at three different ways of resizing images in Python. Apa fungsi Reshape?Fungsi reshape digunakan untuk membuat atau merubah baris kolom. Format penulisannya yaitu reshape([row], [column]) dimana row dan column berisi jumlah baris dan kolom yang diinginkan.
Apa fungsi NumPy pada python?NumPy (Numerical Python) adalah library Python yang fokus pada scientific computing. Simpelnya: Numpy menyediakan fungsi yang siap pakai untuk memudahkan kita melakukan perhitungan saintifik seperti matriks, aljabar, statistik, dan sebagainya.
|