# Reading a colored image as grey scale using Java OpenCV library.

JavaObject Oriented ProgrammingProgramming

The imread() method of the Imgcodecs class accepts a string value representing a file name as a parameter. This method reads the contents of the specified file into a matrix object and returns it. Using this method you can read the contents of an image.

In addition to this, the Imgcodecs class also provides another variant of this method which accepts an integer value representing a flag specifying the required reading mode.

The following are the various fields of the Imgcodecs class that can be used as flag values.

• IMREAD_COLOR − If the flag is set to this value, the loaded image will be converted to a 3-channel BGR (Blue Green Red) color image.

• IMREAD_GRAYSCALE − If the flag is set to this value, the loaded image will be converted to a single-channel grayscale image.

• IMREAD_LOAD_GDAL − If the flag is set to this value, you can load the image using the GDAL driver.

• IMREAD_ANYCOLOR − If the flag is set to this value, the image is read in any possible color format.

− If the flag is set to this value, the image is read as three-channel BGR, and the size of the image is reduced to ½, ¼th or ⅛th of the original size of the image with respect to the field used.

− If the flag is set to this value, the image is read as a single-channel grayscale image, and the size of the image is reduced to ½, ¼th or ⅛th of the original size of the image with respect to the field used.

• IMREAD_UNCHANGED − If the flag is set to this value, the loaded image is returned as it is.

Therefore, if you need to read a colored image as a greyscale image you should pass IMREAD_GRAYSCALE or, IMREAD_REDUCED_GRAYSCALE_X as parameters.

## Example 1

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
public static void main(String args[]) {
//Reading the Image from the file
//Writing the image
Imgcodecs.imwrite("D://images//sunset_greyscale.jpg", matrix);
System.out.println("Image re-Saved");
}
}

## Example 2

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
public static void main(String args[]) {
}