生活随笔
收集整理的這篇文章主要介紹了
矩阵的掩模操作(锐化举例)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
矩陣的掩模操作(通常也叫做卷積操作)非常簡單。本文的中心思想是基于掩模矩陣(也稱為內核或者卷積核)重新計算圖像每個像素的值。此掩模矩陣(卷積核)的值定義了當前像素和相鄰像素對新像素值進行影響的值。From a mathematical point of view we make a weighted average, with our specified values.(從數學的角度來看,基于掩模矩陣指定的值進行mask操作后再進行加權平均)。具體(實現銳化效果的)描述如下:
第一個是公式的形式; 第二個是基于掩模矩陣的版本。兩個等價。
I ( i , j ) = 5 ? I ( i , j ) ? [ I ( i ? 1 , j ) + I ( i + 1 , j ) + I ( i , j ? 1 ) + I ( i , j + 1 ) ]
等價于
I ( i , j ) ? M , 其中 M= 0 ? 1 0 ? 1 5 ? 1 0 ? 1 0
實現銳化效果的例子代碼如下:
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>using namespace std;
using namespace cv;static void help(char* progName)
{cout << endl<< "This program shows how to filter images with mask: the write it yourself and the"<< "filter2d way. " << endl<< "Usage:" << endl<< progName << " [image_name -- default lena.jpg] [G -- grayscale] " << endl << endl;
}void Sharpen(const Mat& myImage,Mat& Result);int main( int argc, char* argv[])
{help(argv[0]);const char* filename = argc >=2 ? argv[1] : "lena.jpg";Mat src, dst0, dst1;if (argc >= 3 && !strcmp("G", argv[2]))src = imread( filename, IMREAD_GRAYSCALE);elsesrc = imread( filename, IMREAD_COLOR);if (src.empty()){cerr << "Can't open image [" << filename << "]" << endl;return -1;}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 times passed in seconds: " << t << endl;imshow( "Output", dst0 );waitKey();//掩模矩陣定義初始化,用于filter2D函數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 << endl;imshow( "Output", dst1 );waitKey();return 0;
}//基于公式計算的版本
void Sharpen(const Mat& myImage,Mat& Result)//公式計算方式
{CV_Assert(myImage.depth() == CV_8U); // accept only uchar imagesconst int nChannels = myImage.channels();Result.create(myImage.size(),myImage.type());for(int j = 1 ; j < myImage.rows-1; ++j){const uchar* previous = myImage.ptr<uchar>(j - 1);const uchar* current = myImage.ptr<uchar>(j );const uchar* next = myImage.ptr<uchar>(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));Result.row(Result.rows-1).setTo(Scalar(0));Result.col(0).setTo(Scalar(0));Result.col(Result.cols-1).setTo(Scalar(0));
}
總結
以上是生活随笔 為你收集整理的矩阵的掩模操作(锐化举例) 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。