Tuesday, July 12, 2022

Unsharp Filter OpenCV C++

 
Unsharp Filter OpenCV C++

Unsharp masking is an image sharpening technique, first implemented in darkroom photography, but now commonly used in digital image processing software. Its name derives from the fact that the technique uses a blurred, or "unsharp", negative image to create a mask of the original image. Wikipedia

Requirement

Implement C++ code to apply  unsharp filter for input image. 

Approach 

  • Blur the original Image
  • Subtract the blurred image from original image (Call this as mask)
  • Add the mask to the original

Source Code

/*
 * UnsharpFilter.cpp
 *
 *  Created on: Jul 12, 2022
 *      Author: viduranga
 */

#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>

using std::cin;
using std::cout;
using std::endl;

using namespace cv;

int kernel[5][5] = {1,4,7,4,1,
4,16,26,16,4,
7,26,41,26,7,
4,16,26,16,4,
1,4,7,4,1};

int accessPixel(unsigned char * arr, int col, int row, int k, int width, int height)
{
    int sum = 0;
    int sumKernel = 0;

    for (int j = -1; j <= 1; j++)
    {
        for (int i = -1; i <= 1; i++)
        {
            if ((row + j) >= 0 && (row + j) < height && (col + i) >= 0 && (col + i) < width)
            {
                int color = arr[(row + j) * 3 * width + (col + i) * 3 + k];
                sum += color * kernel[i + 1][j + 1];
                sumKernel += kernel[i + 1][j + 1];
            }
        }
    }

    return sum / sumKernel;
}

void guassian_blur2D(unsigned char * arr, unsigned char * result, int width, int height)
{
    for (int row = 0; row < height; row++)
    {
        for (int col = 0; col < width; col++)
        {
            for (int k = 0; k < 5; k++)
            {
                result[3 * row * width + 3 * col + k] = accessPixel(arr, col, row, k, width, height);
            }
        }
    }
}

int main(int argc, char** argv)
{
char* ImageFile = argv[1];
double threshold = 10, amount = 5;

Mat input_imge = imread(ImageFile);

if( argc != 2 || !input_imge.data )
{
   cout <<" No image data" <<endl;
   return -1;
}

Mat blurred_image = input_imge.clone();
guassian_blur2D(input_imge.data, blurred_image.data, input_imge.cols, input_imge.rows);
Mat lowConstrastMask = abs(input_imge - blurred_image) < threshold;
Mat sharpened = input_imge*(1+amount) + blurred_image*(-amount);
sharpened.copyTo(input_imge, lowConstrastMask);

imshow("Original Image", input_imge);
imshow("Mask Image",lowConstrastMask);
imshow("Blurred Image",blurred_image);
imshow("Unsharp Filter", sharpened);

waitKey(0);
return 0;
}

Output

Input Image
























Blurred Image
























Mask Image
























Unsharp Image



No comments:

Post a Comment