内核及其自定义进行邻域操作:
代码如下:
// b2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <OpenCV245.h>
using namespace std;
using namespace cv;
void addValue(Mat &image, int &value)
{
/*int nl = image.rows;
int nc = image.cols * image.channels();
if (image.isContinuous())
{
nc *= nl;
nl = 1;
}
for (int j = 0; j < nl; j++)
{
uchar* data = image.ptr<uchar>(j);
for (int i = 0; i < nc; i++)
{
if (data[i] > 133 )
{
data[i] = 255;
}
}
}
*/
Mat_<Vec3b>::iterator it = image.begin<Vec3b>();
Mat_<Vec3b>::iterator itend = image.end<Vec3b>();
for (; it != itend ; ++it)
{
(*it)[0] =(*it)[0] + value;
}
}
void sharpen(const Mat &image, Mat &result)
{
result.create(image.size(), image.type());
for (int j = 1; j < image.rows - 1; j++)
{
const uchar* previous = image.ptr<const uchar>(j - 1);
const uchar* current = image.ptr<const uchar>(j);
const uchar* next = image.ptr<const uchar>(j + 1);
uchar* output = result.ptr<uchar>(j);
for (int i = 1; i < image.cols - 1; i++)
{
*output++ = saturate_cast<uchar>(5*current[i] - current[i - 1] - current[i+1] - previous[i] - next[i]);
//saturate_cast是保证将算后的值在灰度的范围内。uchar为8位,则使其范围在0到255之间
}
}
//set the unprocess 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));
}
void sharpen2D(const Mat &image, Mat &result)
{
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>(2, 1) = -1.0;
kernel.at<float>(1, 0) = -1.0;
kernel.at<float>(1, 2) = -1.0;
filter2D(image, result, image.depth(), kernel);
}
int _tmain(int argc, _TCHAR* argv[])
{
char src_window[] = "src";
char dst_window[] = "dst";
Mat src = imread("C:\\Users\\sony\\Desktop\\pic\\Lena.jpg", 0);
Mat dst;
int value = 50;
double t;
t = static_cast<double>(getTickCount());
/*addValue(src, value);*/
/*sharpen(src, dst);*/
sharpen2D(src, dst);
t = static_cast<double>(getTickCount()) - t;
cout<<"time : "<< t*0.45<<endl;
resize(dst,dst,Size(600, 600));
resize(src,src,Size(600,600));
imshow("src",src);
imshow("dst",dst);
waitKey(0);
return 0;
}