To convert a color image to Grayscale image using OpenCV, we read the image into BufferedImage and convert it into Mat Object.
Syntax:
File input = new File("digital_image_processing.jpg");
BufferedImage image = ImageIO.read(input);
To transform the image from RGB to Grayscale format by using method cvtColor() in the Imgproc class.
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.
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
{
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
String input = "C:/opencv/GeeksforGeeks.jpg" ;
Mat source = Imgcodecs.imread(input);
Mat destination = new Mat();
Imgproc.cvtColor(source, destination, Imgproc.COLOR_RGB2GRAY);
Imgcodecs.imwrite( "C:/opencv/GeeksforGeeks.jpg" , destination);
System.out.println( "The image is successfully to Grayscale" );
}
}
|
Input :
Output :