opencv学习笔记(05)——操作相邻区域

下面的例子以灰度图像为例:

#include <opencv2\highgui\highgui.hpp>

#include <opencv2\imgproc\imgproc.hpp>

#include <opencv2\core\core.hpp>





using namespace cv;



void sharpen(const cv::Mat& img_original, cv::Mat& img_altered);    



void sharpen2D(const cv::Mat& img_original, cv::Mat& img_altered);    



int main()

{



    cv::Mat img_original = cv::imread("F:\\images\\boldt.jpg", cv::IMREAD_GRAYSCALE );     

    cv::Mat img_altered = img_original.clone();



    // 锐化

    sharpen2D(img_original, img_altered);        



    cv::namedWindow("orignal");

    cv::imshow("orignal", img_original);

    cv::namedWindow("altered");

    cv::imshow("altered", img_altered);



    cv::waitKey();



    return 0;

}



void sharpen(const cv::Mat& img_original, cv::Mat& img_altered)    

{



    int nc = img_original.cols;

    int nl = img_original.rows;

    

    for(int j=1; j<nl-1; j++)

    {

        const uchar* previous = img_original.ptr<const uchar>(j-1); 

        const uchar* current = img_original.ptr<const uchar>(j); 

        const uchar* next = img_original.ptr<const uchar>(j+1); 



        uchar*     output = img_altered.ptr<uchar>(j);    



        for(int i=1; i<nc-1; i++)

        {

            *output++ = saturate_cast<uchar>( 5 * current[i] - previous[i] - next[i] - current[i-1] - current[i+1] );    

        }

    }



    img_altered.row(0).setTo(cv::Scalar(0));

    img_altered.row(nl-1).setTo(cv::Scalar(0));

    img_altered.col(0).setTo(cv::Scalar(0));

    img_altered.col(nc-1).setTo(cv::Scalar(0));



}





void sharpen2D(const cv::Mat& img_original, cv::Mat& img_altered)

{

    Mat kernel(3, 3, CV_32F, cv::Scalar(0));

    kernel.at<float>(0,1) = - 1.0;

    kernel.at<float>(1,0) = - 1.0;

    kernel.at<float>(1,2) = - 1.0;

    kernel.at<float>(2,1) = - 1.0;

    kernel.at<float>(1,1) = 5.0;



    //Mat_<cv::Scalar> kernel2 = kernel;

    //kernel2(0,1) = -1.0;

    //kernel2(1,0) = -1.0;

    //kernel2(1,2) = -1.0;

    //kernel2(2,1) = -1.0;

    //kernel2(1,1) = 5.0;



    cv::filter2D(img_original, img_altered, img_original.depth(), kernel);    



}

 

下面是彩色图像的例子:

你可能感兴趣的:(opencv)