Apply Top Hat Operation to an Image using OpenCV

Apply Top Hat Operation to an Image using OpenCV

Top hat (also known as white hat) is a morphological image processing operation. It is the difference between input image and image on which applied opening operation. Top hat operation is commonly used for grayscale images, but it can be used for binary images as well. This operation is useful to increase contrast in a grayscale image.

The morphologyEx function with MORPH_TOPHAT parameter can be used to apply the top hat operation to an image.

import cv2
import numpy as np

inputImg = cv2.imread('test.jpg')
inputImg = cv2.cvtColor(inputImg, cv2.COLOR_BGR2GRAY)

kernel = np.ones((4, 4))
outputImg = cv2.morphologyEx(inputImg, cv2.MORPH_TOPHAT, kernel)

cv2.imshow('Input image', inputImg)
cv2.imshow('Output image', outputImg)
cv2.waitKey(0)
cv2.destroyAllWindows()
#include <opencv2/opencv.hpp>

using namespace cv;

int main()
{
    Mat inputImg = imread("test.jpg");
    cvtColor(inputImg, inputImg, COLOR_BGR2GRAY);

    Mat kernel = getStructuringElement(MORPH_RECT, Size(4, 4));
    Mat outputImg;
    morphologyEx(inputImg, outputImg, MORPH_TOPHAT, kernel);

    imshow("Input image", inputImg);
    imshow("Output image", outputImg);
    waitKey(0);
    destroyAllWindows();

    return 0;
}
#include <opencv2/opencv.hpp>
#include <opencv2/cudaimgproc.hpp>
#include <opencv2/cudafilters.hpp>

using namespace cv;

int main()
{
    Mat img = imread("test.jpg");
    cuda::GpuMat gpuInputImg(img), gpuOutpuImg;
    cuda::cvtColor(gpuInputImg, gpuInputImg, COLOR_RGB2GRAY);
    Mat inputImg(gpuInputImg);

    Mat kernel = getStructuringElement(MORPH_RECT, Size(4, 4));
    Ptr<cuda::Filter> filter = cuda::createMorphologyFilter(MORPH_TOPHAT, gpuInputImg.type(), kernel);
    filter->apply(gpuInputImg, gpuOutpuImg);
    Mat outputImg(gpuOutpuImg);

    imshow("Input image", inputImg);
    imshow("Output image", outputImg);
    waitKey(0);
    destroyAllWindows();

    return 0;
}
package app;

import org.opencv.core.*;
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 inputImg = Imgcodecs.imread("test.jpg");
        Imgproc.cvtColor(inputImg, inputImg, Imgproc.COLOR_BGR2GRAY);

        Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(4, 4));
        Mat outputImg = new Mat();
        Imgproc.morphologyEx(inputImg, outputImg, Imgproc.MORPH_TOPHAT, kernel);

        HighGui.imshow("Input image", inputImg);
        HighGui.imshow("Output image", outputImg);
        HighGui.waitKey(0);
        HighGui.destroyAllWindows();

        System.exit(0);
    }
}
Top hat operation applied to an image using OpenCV

Leave a Comment

Cancel reply

Your email address will not be published.