Java|使用 cvtColor() 将图像转换为灰度
为了使用 OpenCV 将彩色图像转换为灰度图像,我们将图像读入 BufferedImage 并将其转换为 Mat Object。
Syntax:
File input = new File("digital_image_processing.jpg");
BufferedImage image = ImageIO.read(input);
使用 Imgproc 类中的方法 cvtColor() 将图像从 RGB 转换为灰度格式。
Syntax:
Imgproc.cvtColor(source mat, destination mat1, Imgproc.COLOR_RGB2GRAY);
Parameters: The method cvtColor() takes three parameters which are the source image matrix, the destination image matrix, and the color conversion type.
// Java program to convert a color image to gray scale
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class GeeksforGeeks {
public static void main(String args[]) throws Exception
{
// To load OpenCV core library
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
String input = "C:/opencv/GeeksforGeeks.jpg";
// To Read the image
Mat source = Imgcodecs.imread(input);
// Creating the empty destination matrix
Mat destination = new Mat();
// Converting the image to gray scale and
// saving it in the dst matrix
Imgproc.cvtColor(source, destination, Imgproc.COLOR_RGB2GRAY);
// Writing the image
Imgcodecs.imwrite("C:/opencv/GeeksforGeeks.jpg", destination);
System.out.println("The image is successfully to Grayscale");
}
}
输入 :输出 :