Scaling Images using OpenCV in Java
Scaling of Image refers to the resizing of images. It is useful in image processing and manipulation in machine learning applications as it can reduce the time of training as less number of pixels, less is the complexity of the model. Imgproc module of OpenCV library provides an adequate interpolation method for resizing an image.
Imgproc.resize Method of Imgproc module of OpenCV can be used to resize the image. This function resizes the image src down to or up to the specified size. It provides all the features to resize the image i.e. either shrink it or zoom it to meet the size requirements.
Syntax:
resize(
src: &Mat,
dst: &mut Mat,
dsize: Size,
fx: f64,
fy: f64,
interpolation: i32
)
Parameters:
Name |
Definition |
src |
It is the input image of the MAT type. |
dst |
It is the output image of MAT type |
dsize |
It is the size of the output image of Size type |
fx |
Scale factor along X-axis of double type |
fy |
Scale factor along Y-axis of double type |
interpolation |
It is the method for image decimation. Default interpolation is INTER_LINEAR interpolation
|
Algorithm:
- Load OpenCV modules.
- Read the image(2D matrix) from the directory.
- Store image/2D matrix as a Mat object.
- Create an image/2D matrix using the object.
- Scale and write using the above object created.
Samples:
Suppose the user wants to resize src so that it fits the pre-created destination file, then the syntax for calling the function is as follows
resize(src, dst, dst.size(), 0, 0, interpolation);
Suppose the user wants to reduce the image by a factor of 2 in each direction, then the syntax for calling the function is as follows
resize(src, dst, Size(), 0.5, 0.5, interpolation);
Implementation: Considering the below image as an input image that is supposed to be scaled producing a new output image. Here the input image is supposed to be scaled down which is illustrated with help of an example.
Input Image
Java
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class GFG {
public static void main(String args[])
{
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
String image_location
= "C:\\Users\\user\\Downloads\\InputImage.jpg" ;
Mat src = Imgcodecs.imread(image_location);
Mat dst = new Mat();
Imgproc.resize(src, dst, new Size( 0 , 0 ), 0.1 , 0.1 ,
Imgproc.INTER_AREA);
Imgcodecs.imwrite( "D:/resized_image.jpg" , dst);
System.out.println( "Image Processed" );
}
}
|
Output:
Final Image
Last Updated :
08 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...