Mask operations on matrices

#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include
using namespace std;
using namespace cv;

void Sharpen(const Mat& myImage, Mat& Result); // &引用传递,可以改变传入实参的值

int main()
{
const char* filename = “/home/chang/projects/opencv_GPU_example/test.jpg”;
Mat src, dst0, dst1;

src = imread(samples::findFile(filename), IMREAD_COLOR);
if(src.empty())
{
	cerr << "Can't open image [" << filename << "]" << endl;
	return EXIT_FAILURE;
}

namedWindow("Input", WINDOW_AUTOSIZE);
namedWindow("Output", WINDOW_AUTOSIZE);

imshow("Input", src);
double t = (double)getTickCount();

Sharpen(src, dst0);

t = ((double)getTickCount() - t) / getTickFrequency();
cout << "Hand written function time passed in seconds: " << t*1000 << "ms" << endl;

imshow("Output", dst0);
waitKey();

Mat kernel = (Mat_<char>(3, 3) << 0, -1, 0,
								 -1, 5, -1,
								 0, -1, 0);
t = (double)getTickCount();

filter2D(src, dst1, src.depth(), kernel);
t = ((double)getTickCount() - t) / getTickFrequency();
cout << "Built-in filter2D time passed in seconds: " << t * 1000 << "ms" << endl;

imshow("Output", dst1);
waitKeyEx();

return 0;

}

void Sharpen(const Mat& myImage, Mat& Result)
{
CV_Assert(myImage.depth() == CV_8U); // accept only uchar images

const int nChannels = myImage.channels(); // nChannels=3
Result.create(myImage.size(), myImage.type()); // Mat::create()函数创建矩阵体

// cout << "row = " << Result.rows << "col = " << Result.cols << endl;
for(int j = 1; j < myImage.rows - 1; ++j)
{
const uchar* previous = myImage.ptr(j - 1); //ptr是智能指针,(j-1)是指向uchar对象的一个指针
const uchar* current = myImage.ptr(j );
const uchar* next = myImage.ptr(j + 1);

	uchar* output = Result.ptr<uchar>(j);
	for(int i = nChannels; i < nChannels*(myImage.cols-1); ++i)
	{
		*output++ = saturate_cast<uchar>(5*current[i] - current[i-nChannels] - current[i+nChannels] - previous[i] -next[i]);	
	}
}

Result.row(0).setTo(Scalar(0));             // 0行设置为0
Result.row(Result.rows-1).setTo(Scalar(0)); // 倒数第1行设置为0
Result.col(0).setTo(Scalar(0));             // 第一列设置为0
Result.col(Result.cols-1).setTo(Scalar(0)); // 倒数第一类列设置为0

}

发布了43 篇原创文章 · 获赞 0 · 访问量 406

猜你喜欢

转载自blog.csdn.net/weixin_42505877/article/details/103928259
今日推荐