Reading Multiple Images and Do Resizing in Python Opencv
Come up, let'due south acquire about image resizing with OpenCV . To resize an image, calibration it along each axis (top and width), considering the specified calibration factors or just set the desired top and width.
When resizing an image:
- It is important to proceed in mind the original aspect ratio of the prototype (i.east. width by superlative), if you want to maintain the same in the resized paradigm likewise.
- Reducing the size of an epitome will require resampling of the pixels.
- Increasing the size of an paradigm requires reconstruction of the prototype. This means you demand to interpolate new pixels.
Various interpolation techniques come into play to attain these operations. Several methods are bachelor in OpenCV, the choice typically depends on the particular application.
- Reading an Prototype using OpenCV imread() role
- Image resizing with a custom Width and Height
- Resizing an image with a Scaling cistron
- Image resizing with unlike Interpolation methods
- Summary
Let's go through the code example for making an image larger and smaller by resizing with custom height and width. As you keep further, we will hash out resizing with different scale factors and interpolation methods as well.
Python
# permit'southward showtime with the Imports import cv2 import numpy as np # Read the prototype using imread role epitome = cv2.imread('epitome.jpg') cv2.imshow('Original Image', image) # allow's downscale the image using new width and acme down_width = 300 down_height = 200 down_points = (down_width, down_height) resized_down = cv2.resize(prototype, down_points, interpolation= cv2.INTER_LINEAR) # let's upscale the image using new width and summit up_width = 600 up_height = 400 up_points = (up_width, up_height) resized_up = cv2.resize(prototype, up_points, interpolation= cv2.INTER_LINEAR) # Display images cv2.imshow('Resized Down by defining height and width', resized_down) cv2.waitKey() cv2.imshow('Resized Up image by defining height and width', resized_up) cv2.waitKey() #press whatsoever key to shut the windows cv2.destroyAllWindows() C++
// allow'southward start with including libraries #include<opencv2/opencv.hpp> #include<iostream> // Namespace to nullify use of cv::office(); syntax using namespace std; using namespace cv; int main() { // Read the prototype using imread function Mat paradigm = imread("image.jpg"); imshow("Original Image", epitome); // let's downscale the epitome using new width and height int down_width = 300; int down_height = 200; Mat resized_down; //resize down resize(epitome, resized_down, Size(down_width, down_height), INTER_LINEAR); // let'south upscale the image using new width and elevation int up_width = 600; int up_height = 400; Mat resized_up; //resize upwardly resize(image, resized_up, Size(up_width, up_height), INTER_LINEAR); // Display Images and press whatsoever key to continue imshow("Resized Down by defining height and width", resized_down); waitKey(); imshow("Resized Up image past defining summit and width", resized_up); waitKey(); destroyAllWindows(); render 0; } NEW COURSE LIVE ON KICKSTARTER
Deep Learning With TensorFlow & Keras
Read The Image
Let's begin by importing the required modules as shown beneath.
Python
# Importing the libraries import cv2 import numpy as np Download Lawmaking To easily follow along this tutorial, please download lawmaking by clicking on the button below. It'south Free!
C++
#include<opencv2/opencv.hpp> #include<iostream> // Namespace to nullify use of cv::function(); syntax using namespace std; using namespace cv; Side by side, read in a test prototype, using the imread() function, as discussed in previous posts. The syntax is shown below.
Python
# Reading image epitome= cv2.imread('image.jpg') C++
// Reading image Mat prototype = imread("image.jpg"); Note that in the C++ snippet, you first created a matrix for the paradigm, then used the imread() function to read it.
Earlier you lot start resizing the paradigm, know its original size. To obtain the size of an image:
- utilize the shape method in Python
- rows and cols in C++
image.shape in Python returns 3 values: Acme, width and number of channels.
In C++:
-
image.rowsgives you the height -
prototype.columnsgives you the width of the image
The above results tin can also be obtained, using the size() function.
-
image.size().widthreturns the width -
image.size().meridianreturns the superlative
Python
# Go original height and width h,westward,c = prototype.shape print("Original Height and Width:", h,"x", w) C++
// Become height and width cout << "Original Acme and Width :" << prototype.rows << "x" << image.cols << endl; Ane important matter to note here is that OpenCV outputs the shape of an epitome in
format, whereas some other image-processing libraries give in the form of width, height. There's a logical take to this.
When images are read using OpenCV, they are represented as NumPy arrays. And in general, you ever refer to the shape of an array, in terms of
(rows representing its height and the columns its width). And so, fifty-fifty when reading images with OpenCV to get their shape, the same NumPy array rule comes into play. And you get the shape in the form of
.
Resize Function Syntax
Let'due south brainstorm by taking a look at the OpenCV resize() function syntax. Notice that only 2 input arguments are required:
- The source image.
- The desired size of the resized prototype,
dsize.
We will talk over the various input argument options in the sections below.
resize(src, dsize[, dst[, fx[, fy[, interpolation]]]])
-
src: It is the required input paradigm, it could be a string with the path of the input image (eg: 'test_image.png'). -
dsize: It is the desired size of the output image, it can be a new tiptop and width. -
fx: Scale cistron along the horizontal axis. -
fy: Scale factor along the vertical axis. -
interpolation: Information technology gives the states the option of different methods of resizing the image.
Resizing by Specifying Width and Height
In this first instance, let'south resize the image by specifying a new width and peak that will downscale the paradigm. In the code below:
- Nosotros gear up the desired width equally 300 and the desired height, 200.
- These 2 values are combined in a 2D vector, required by the
resize()function. - Nosotros also specify the interpolation method, which happens to exist the default value.
Python
# Set rows and columns # lets downsize the image using new width and peak down_width = 300 down_height = 200 down_points = (down_width, down_height) resize_down = cv2.resize(image, down_points, interpolation= cv2.INTER_LINEAR) C++
// Set rows and columns // lets downsize the image using new width and peak int down_width = 300; int down_height = 200; Mat resize_down; // resize down resize(image, resize_down, Size(down_width, down_height), INTER_LINEAR); Adjacent, we create another variable to increase the size of the image.
Python
# Set rows and columns up_width = 600 up_height = 400 up_points = (up_width, up_height) # resize the prototype resized_up = cv2.resize(paradigm, up_points, interpolation = cv2.INTER_LINEAR) C++
// Set rows and columns int up_width = 600; int up_height = 400; Mat resized_up; //resize up resize(image, resized_up, Size(up_width, up_height), INTER_LINEAR); In the in a higher place Python snippet, we are defining new width and top to upscale the image, using the resize() function. Process and steps are similar to the previous snippet.
In the C++ snippet:
- Nosotros define new integers for width and tiptop for upscaling.
- Give a matrix for the output image.
- So use the
resize()function, same every bit the previous snippet.
At present, permit us display all the images using the imshow() function from OpenCV.
Python
# Display images cv2.imshow('Resized Down by defining peak and width', resized_down) cv2.waitKey() cv2.imshow('Resized Up image past defining summit and width', resized_up) cv2.waitKey() cv2.destroyAllWindows() C++
// Display Images and press whatsoever key to continue imshow("Resized Downwardly by defining height and width", resized_down); waitKey(); imshow("Resized Up paradigm by defining peak and width", resized_up); waitKey(); destroyAllWindows();
Our resize operations worked as expected. The image either got bigger or smaller, co-ordinate to the new acme and width parameters we defined. Simply ane thing to note is that such resizing by defining an explicit value for width and summit is making the resulting image distorted. That is, the aspect ratio of the image does non stay intact.
So, how to correct this? Well, you'll accept to learn to employ a scaling factor when resizing.
Resizing With a Scaling Factor
Okay, so now we resize the image with a scaling factor. But before going further, you need to understand what exactly is a scaling factor.
Scaling Gene or Scale Cistron is ordinarily a number that scales or multiplies some quantity, in our case the width and height of the paradigm. It helps go along the attribute ratio intact and preserves the display quality. And then the image does non appear distorted, while you are upscaling or downscaling it.
Python
# Scaling Up the epitome i.2 times past specifying both scaling factors scale_up_x = 1.2 scale_up_y = ane.ii # Scaling Down the image 0.half dozen times specifying a single scale factor. scale_down = 0.6 scaled_f_down = cv2.resize(image, None, fx= scale_down, fy= scale_down, interpolation= cv2.INTER_LINEAR) scaled_f_up = cv2.resize(image, None, fx= scale_up_x, fy= scale_up_y, interpolation= cv2.INTER_LINEAR) C++
// Scaling Upwardly the image 1.2 times by specifying both scaling factors double scale_up_x = 1.2; double scale_up_y = 1.2; // Scaling Downwardly the image 0.6 times specifying a single scale factor. double scale_down = 0.6; Mat scaled_f_up, scaled_f_down; //resize resize(image,scaled_f_down, Size(), scale_down, scale_down, INTER_LINEAR); resize(image, scaled_f_up, Size(), scale_up_x, scale_up_y, INTER_LINEAR); In the above Python snippet:
- We define new scaling factors along the horizontal and vertical centrality.
- Defining the scaling factors removes the demand to have new points for width and summit. Hence, we keep
dsizeasNone.
In the in a higher place C++ snippet:
- We define the new scaling factors likewise every bit the matrices for the new images.
- As nosotros do not need new points for width and height, nosotros keep
Size()empty and apply theresize()function.
Now, let u.s.a. display the images for visualization and meliorate understanding.
Python
# Brandish images and printing any primal to check next image cv2.imshow('Resized Down by defining scaling cistron', scaled_f_down) cv2.waitKey() cv2.imshow('Resized Up prototype by defining scaling factor', scaled_f_up) cv2.waitKey() C++
// Brandish images and Press whatever key to continue bank check adjacent epitome imshow("Resized Downwards by defining scaling factor", scaled_f_down); waitKey(); imshow("Resized Upwardly by defining scaling factor", scaled_f_up); waitKey();
Resizing With Dissimilar Interpolation Methods
Different interpolation methods are used for different resizing purposes.
-
INTER_AREA:INTER_AREAuses pixel area relation for resampling. This is best suited for reducing the size of an prototype (shrinking). When used for zooming into the epitome, information technology uses theINTER_NEARESTmethod. -
INTER_CUBIC: This uses bicubic interpolation for resizing the paradigm. While resizing and interpolating new pixels, this method acts on the four×4 neighboring pixels of the epitome. Information technology and then takes the weights average of the 16 pixels to create the new interpolated pixel. -
INTER_LINEAR: This method is somewhat similar to theINTER_CUBICinterpolation. But unlikeINTER_CUBIC, this uses 2×2 neighboring pixels to go the weighted average for the interpolated pixel. -
INTER_NEAREST: TheINTER_NEARESTmethod uses the nearest neighbor concept for interpolation. This is one of the simplest methods, using just ane neighboring pixel from the image for interpolation.
Do not worry if y'all exercise non empathise the interpolation methods completely. We volition cover them in a split up post.
Python
# Scaling Down the image 0.half-dozen times using different Interpolation Method res_inter_nearest = cv2.resize(paradigm, None, fx= scale_down, fy= scale_down, interpolation= cv2.INTER_NEAREST) res_inter_linear = cv2.resize(image, None, fx= scale_down, fy= scale_down, interpolation= cv2.INTER_LINEAR) res_inter_area = cv2.resize(image, None, fx= scale_down, fy= scale_down, interpolation= cv2.INTER_AREA) C++
# Scaling Downward the image 0.6 using different Interpolation Method Mat res_inter_linear, res_inter_nearest, res_inter_area; resize(paradigm, res_inter_linear, Size(), scale_down, scale_down, INTER_LINEAR); resize(epitome, res_inter_nearest, Size(), scale_down, scale_down, INTER_NEAREST); resize(image, res_inter_area, Size(), scale_down, scale_down, INTER_AREA); In the to a higher place Python snippet, we are resizing the paradigm using different Interpolation methods. Similarly, in the C++ snippet, we are kickoff defining new matrices for output images, then resizing them with dissimilar Interpolation methods. Permit's brandish the images now.
Python
# Concatenate images in horizontal centrality for comparison vertical= np.concatenate((res_inter_nearest, res_inter_linear, res_inter_area), centrality = 0) # Display the image Press whatever fundamental to go on cv2.imshow('Inter Nearest :: Inter Linear :: Inter Area', vertical) C++
Mat a,b,c; vconcat(res_inter_linear, res_inter_nearest, a); vconcat(res_inter_area, res_inter_area, b); vconcat(a, b, c); // Brandish the image Press whatsoever central to continue imshow("Inter Linear :: Inter Nearest :: Inter Area :: Inter Expanse", c);
We promise by now y'all are familiar with the resize() role in OpenCV. We likewise saw how to resize an image in a couple of different ways.
The below GIF shows the process of executing the complete code for all the resizing operations that you lot learned, similar resizing past prototype width and pinnacle, scaling factor, and unlike interpolation methods.
Encounter the Resizing Feature in Activeness in a Spider web App
Now that you have a articulate idea about the resize part and its usability, why not try it in a spider web app. See the furnishings of resizing there also. We have created a small demo application for the resize() function using Streamlit. You tin can visit the application page hither. Play around with the prototype provided, or upload one of your choice.
Summary
You learned to resize an image, using custom height and width. Yous also saw how using the scaling factor kept the aspect ratio intact, ensuring the resized prototype did not look distorted. We as well discussed different types of interpolation methods.
Y'all tin find the Colab Notebook for this mail here.
Subscribe & Download Code
If you liked this commodity and would like to download code (C++ and Python) and case images used in this post, delight click here. Alternately, sign upwardly to receive a costless Computer Vision Resource Guide. In our newsletter, we share OpenCV tutorials and examples written in C++/Python, and Computer Vision and Machine Learning algorithms and news.
Do try out the app we have provided to see the resize role of an image in activeness. We recommend you download the code for study and practice. Feel free to reach out to usa in the annotate section for any doubts/feedback or suggestions.
shaveryourbithes1967.blogspot.com
Source: https://learnopencv.com/image-resizing-with-opencv/
0 Response to "Reading Multiple Images and Do Resizing in Python Opencv"
Postar um comentário