load image
openCv has a simple function called imread for reading an image from a file
The imread function is in the same-named package of the Imgcodecs class.
load image code
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Core;
import org.opencv.imgcodecs.Imgcodecs;
import origami.Origami;
public class HelloCv {
public static void main(String[] args) throws Exception {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Mat mat = Imgcodecs.imread("./images/test.jpg");
System.out.println(mat.width()+"x"+mat.height()+","+mat.type());
}
}
If the loading is successful, the following message will be output
This function can also load grayscale images
Control via IMREAD_GRAYSCALE
Mat mat = Imgcodecs.imread("./images/test.jpg",Imgcodecs.IMREAD_GRAYSCALE);
IMREAD_GRAYSCALE coerces the image to a grayscale image and loads it into a Mat object
In addition to the IMREAD_GRAYSCALE parameter, you can also pass other parameters to get specific processing channels and image depths
save Picture
The imwrite function can be used to save pictures, and it is also in the Imgcodecs class
Our image is in color, changed to a grayscale image by IMREAD_GRAYSCALE, and output as output.jpg
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Core;
import org.opencv.imgcodecs.Imgcodecs;
import origami.Origami;
public class HelloCv {
public static void main(String[] args) throws Exception {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Mat mat = Imgcodecs.imread("./images/test.jpg",Imgcodecs.IMREAD_GRAYSCALE); //灰度加载
System.out.println(mat.width()+"x"+mat.height()+","+mat.type());
Imgcodecs.imwrite("./images/output.jpg",mat);
}
}
For JPEG, you can use the CV_IMWRITE_JPEG_QUALITY parameter, and the parameter value ranges from 0 to 100 (the larger the value, the higher the image quality). The default value is 95.
For PNG, you can use 0 to 9 as the parameter value of the compression degree. The larger the value, the smaller the image and the longer the compression time. The default value is 3.
Compressing the output file with compression parameters can be achieved by using another OpenCV object called MatOfInt, which is a matrix of integers, or in a simpler form, an array.
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Core;
import org.opencv.core.MatOfInt;
import org.opencv.imgcodecs.Imgcodecs;
import origami.Origami;
public class HelloCv {
public static void main(String[] args) throws Exception {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Mat mat = Imgcodecs.imread("./images/test.jpg",Imgcodecs.IMREAD_GRAYSCALE);
System.out.println(mat.width()+"x"+mat.height()+","+mat.type());
MatOfInt moi = new MatOfInt(Imgcodecs.IMWRITE_PNG_COMPRESSION,9);
Imgcodecs.imwrite("./images/output.png",mat,moi);
}
}
uncompressed size
Compressed size