Two methods of image sharpening

Keywords: OpenCV

Reprint:
https://blog.csdn.net/qq_18649781/article/details/86484827

Introduction:

There is a well-known conclusion in the field of image processing: if the Laplacian part is subtracted from the image, the edge of the image will be enlarged, so the image will become sharper. Based on the Laplace operator, the image is sharpened by visiting the adjacent pixels in the image

1. Sharpening principle formula

5*current[i] - current[i-nchannels] - current[i+nchannels]-previous[i]-next[i]);

2. The first way: sharpen the image by visiting adjacent pixels

void sharpen(const Mat &image,Mat result)
{
    ///Determine whether image data needs to be allocated. Assign if necessary
    result.create(image.size(),image.type());
    int nchannels = image.channels(); ///Get the number of channels
    ////The next program is to process all the lines
    for (int j = 1 ; j < image.rows-1; j++) {
        const uchar* previous = image.ptr<const uchar>(j-1);   /// last line
        const uchar* current = image.ptr<const uchar>(j);      //Current line
        const uchar* next = image.ptr<const uchar>(j+1);   //Next line
        uchar* output = result.ptr<uchar>(j);  //Output line
      /**** Operation part of sharpening operator****/
        ////Here, three channels of each pixel are combined into a matrix, so there is (image.cols-1)*nchannels operation.
        ///It should be noted that for color pictures, when there are three channels, BGR must operate on color pixels, so here are current[i-nchannels] and current[i+nchannels]
        for (int i = nchannels; i < (image.cols-1)*nchannels; i++) {    ///Cycle three channels for corresponding processing
        *output++ = saturate_cast<uchar>(
                5*current[i] - current[i-nchannels] - current[i+nchannels]-previous[i]-next[i]);       ///Five times the value minus four numbers
        }
    }
    ///Next, set the unprocessed pixels to 0.
    result.row(0).setTo(Scalar(0));
    result.row(result.rows -1).setTo(Scalar(0));
    result.col(0).setTo(Scalar(0));
    result.col(result.cols-1).setTo(Scalar(0));
    imshow("HAHAH1",result);
}

3. The second way: Based on the special filter2D() function of OpenCV

void sharpen2D(const Mat &image,Mat &result)
{
    // First, build a kernel
    Mat kernel(3,3,CV_32F,Scalar(0));
    
    ///Assign a value to the corresponding kernel
    kernel.at<float>(1,1) = 5.0;
    kernel.at<float>(0,1) = -1.0;
    kernel.at<float>(2,1) = -1.0;
    kernel.at<float>(1,0) = -1.0;
    kernel.at<float>(1,2) = -1.0;

    // The kernel can also be constructed directly
    // lap_5 = np.array([[0,-1,0],[-1,5,-1],[0,-1,0]])
    // lap_9 = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]])

    ///Filter the image
    filter2D(image,result,image.depth(),kernel);
    imshow("HAHAH2",result);
}

Posted by mol on Thu, 31 Oct 2019 10:36:21 -0700