Apply Histogram Equalization to an Image using OpenCV

Histogram equalization is a method in image processing that allows to adjust the contrast of an image using histogram. Histogram equalization transforms pixel intensity values so that the histogram of the output image is more distributed through the entire range of values.

OpenCV provides equalizeHist function that allows to apply histogram equalization to a grayscale image.

import cv2

img = cv2.imread('test.jpg')
grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
equImg = cv2.equalizeHist(grayImg)

cv2.imshow('Original image', grayImg)
cv2.imshow('Equalized image', equImg)
cv2.waitKey(0)
cv2.destroyAllWindows()
#include <opencv2/opencv.hpp>

using namespace cv;

int main()
{
    Mat img = imread("test.jpg");
    Mat grayImg;
    cvtColor(img, grayImg, COLOR_BGR2GRAY);
    Mat equImg;
    equalizeHist(grayImg, equImg);

    imshow("Original image", grayImg);
    imshow("Equalized image", equImg);
    waitKey(0);
    destroyAllWindows();

    return 0;
}
package app;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class Main
{
    static { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); }

    public static void main(String[] args)
    {
        Mat img = Imgcodecs.imread("test.jpg");
        Mat grayImg = new Mat();
        Imgproc.cvtColor(img, grayImg, Imgproc.COLOR_BGR2GRAY);
        Mat equImg = new Mat();
        Imgproc.equalizeHist(grayImg, equImg);

        HighGui.imshow("Original image", grayImg);
        HighGui.imshow("Equalized image", equImg);
        HighGui.waitKey(0);
        HighGui.destroyAllWindows();

        System.exit(0);
    }
}

Result:

Applying histogram equalization using OpenCV

Leave a Comment

Your email address will not be published. Required fields are marked *