How to alter the brightness of an image using Java OpenCV library?

JavaObject Oriented ProgrammingProgramming

The convertTo() method of the org.opencv.core.Mat class performs the required calculations on the given matrix to alter the contrast and brightness of an image. This method accepts 4 parameters −

• mat − Empty matrix to hold the result with the same size and type as the source matrix.

• rtype − integer value specifying the type of the output matrix. If this value is negative, the type will be the same as the source.

• alpha − Gain value, which must be greater than 0 (default value 1).

• beta − Bias value (default value 0).

Altering the brightness of an image using OpenCV Java library

As mentioned the beta value passed to this method alters the brightness of an image, if the chosen value for this parameter is a negative value (0 to -255) the brightness of the image is reduced. Similarly, if it is greater than 0 (0 to 255) the brightness of the image is increased.

To alter the contrast of an image invokes the convertTo() method by passing the empty matrix, -1 (to get the same type), 1 as alpha value and, beta value to increase or decrease the brightness.

Example

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
public class AlteringBrightness {
public static void main (String[] args) {
//Reading the Image from the file
String file ="D:\\Images\\tiger.jpg";
//Creating an empty matrix
Mat dest = new Mat(src.rows(), src.cols(), src.type());
//Increasing the brightness of an image
src.convertTo(dest, -1, 1, 100);
// Writing the image
Imgcodecs.imwrite("D:\\Images\\altering_brightness_100.jpg", dest);
}
}

Input image

Following are the various output images for different alpha values −

α-value: -100

α-value: -50

α-value: 50

α-value: 100

Published on 09-Apr-2020 07:52:15