RGB image to grayscale java

In various cases, you may need to convert the RGB images to grayscale or black and white, for example, in image processing, etc. Accordingly, in this article, you will learn how to convert an RGB image to grayscale using Java. Moreover, the article will cover grayscaling and binarization of the images explicitly.

Convert Color Image to Grayscale in Java - API Installation

To convert RGB images to grayscale, we’ll use Aspose.Imaging for Java. It is a Java image processing API that allows you to manipulate popular image formats seamlessly. You can either download the API or install it using the following Maven configurations.

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java API</name>
    <url>http://repository.aspose.com/repo/</url>
</repository>
<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-imaging-java</artifactId>
    <version>21.7</version>
    <classifier>jdk16</classifier>
</dependency>

Convert an RGB Image to Grayscale in Java

The following are the steps to convert an RGB image to grayscale in Java.

The following code sample shows how to convert an image to grayscale in Java.

Input Image

The following is a sample image used in this article.

image to grayscale Java

Converted to Grayscale

The following is the image after conversion to grayscale.

grayscale image

Java Image to Grayscale - Binarization

In binarization, each pixel in an image can have only two possible values; 0 or 1. Here, 0 denotes the absence and 1 denotes the presence of the color. Aspose.Imaging supports two binarization methods i.e. binarization with fixed and binarization with Otsu threshold.

Binarization with Fixed Threshold

The following are the steps to perform binarization on an image using fixed threshold.

The following Java code applies binarization to an image and converts it to black and white.

Binarization with Otsu Threshold

The following are the step to convert an image to black and white with Otsu threshold.

The following code sample shows how to convert an image to black and white with Otsu threshold using Java.

Convert Image to Grayscale with a Free License

You can get a free temporary license and convert images to grayscale without evaluation limitations.

Conclusion

In this article, you have learned how to convert a color image to grayscale and black and white using Java. Moreover, you have seen how to apply binarization to the images with fixed or Otsu thresholds. In addition, you can explore more about the Java image processing API using documentation. Also, you can share your queries with us via our forum.

See Also