OpenCV锐化算法实现

Mat sharpen(const Mat &img, Mat &result)//锐化算子
{
    //Method 1  直接操作像素点
    result.create(img.rows, img.cols, img.type());
    int nl = img.rows;
    int nc = img.cols * img.channels();
    for (int j = 1; j < nl - 1; j++)
    {
        const uchar* previous = img.ptr<const uchar>(j - 1);//上一行
        const uchar* current = img.ptr<const uchar>(j);//当前行
        const uchar* next = img.ptr<const uchar>(j + 1);//下一行
        uchar* output = result.ptr<uchar>(j);//输出行
        for (int i = 1; i < nc - 1; i++)
        {
             output[i]= saturate_cast<uchar>(5 * current[i] - current[i-1]
                - current[i- 1] - previous[i] - next[i]);
        }
    }
    //将未处理的像素设置为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));
    return result;

    //Method 2  cv::filter2D
    //构造滤波核
    //
    //    0  -1  0
    //    -1  5  -1 
    //     0  -1  0
    //
    Mat kernel(3, 3, CV_32F, Scalar(0));
    kernel.at<float>(1, 1) = 5.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;

    cout << kernel << endl;
    filter2D(img, result, -1, kernel);
}

遍历图像各像素点:

void colorReduce(Mat &img, int div)
{
    //获取图像的行数、列数、通道数
    //int nl = img.rows;//行数
    //int nc = img.cols * img.channels();
    遍历像素
    //for (int j = 0; j < nl; j++)
    //{
    //  //得到第j行的首地址
    //  uchar* data = img.ptr(j);
    //  for (int i = 0; i < nc; i++)
    //  {
    //      data[i] = data[i] / div *div + div / 26;
    //      //像素处理完成
    //  }//行处理完成
    //}


    double duration = static_cast<double>(getTickCount());
    //使用迭代器
    Mat_::iterator it = img.begin();//得到初始位置的迭代器

    Mat_::iterator itend = img.end();//得到终止位置的迭代器

    //遍历所有像素
    for (; it != itend; it+=2)
    {
        //处理每个像素
        (*it)[0] = (*it)[0] / div *div + div / 2;
        (*it)[1] = (*it)[1] / div *div + div / 2;
        (*it)[2] = (*it)[2] / div *div + div / 2;
    }
    duration = static_cast<double>(getTickCount()) - duration;
    duration = duration / getTickFrequency();//运行时间 ms
    cout << duration << endl;
}

你可能感兴趣的:(OpenCV)