1 #include <opencv2/core.hpp> 2 #include <opencv2/core/utility.hpp> 3 #include <opencv2/imgcodecs.hpp> 4 #include <opencv2/highgui.hpp> 5 #include <opencv2/imgproc.hpp> 6 #include <iostream> 7 8 using namespace std; 9 using namespace cv; 10 11 static void help(char* progName) 12 { 13 cout << endl 14 << "This program shows how to filter images with mask: the write it yourself and the" 15 << "filter2d way. " << endl 16 << "Usage:" << endl 17 << progName << " [image_name -- default ../data/lena.jpg] [G -- grayscale] " << endl << endl; 18 } 19 20 21 void Sharpen(const Mat& myImage,Mat& Result); 22 23 int main( int argc, char* argv[]) 24 { 25 help(argv[0]); 26 const char* filename = argc >=2 ? argv[1] : "../data/lena.jpg"; 27 28 Mat I, J, K; 29 30 if (argc >= 3 && !strcmp("G", argv[2])) 31 I = imread( filename, IMREAD_GRAYSCALE); 32 else 33 I = imread( filename, IMREAD_COLOR); 34 35 namedWindow("Input", WINDOW_AUTOSIZE); 36 namedWindow("Output", WINDOW_AUTOSIZE); 37 38 imshow("Input", I); 39 double t = (double)getTickCount(); 40 41 Sharpen(I, J); 42 43 t = ((double)getTickCount() - t)/getTickFrequency(); 44 cout << "Hand written function times passed in seconds: " << t << endl; 45 46 imshow("Output", J); 47 waitKey(0); 48 49 Mat kern = (Mat_<char>(3,3) << 0, -1, 0, 50 -1, 5, -1, 51 0, -1, 0); 52 t = (double)getTickCount(); 53 filter2D(I, K, I.depth(), kern ); 54 t = ((double)getTickCount() - t)/getTickFrequency(); 55 cout << "Built-in filter2D time passed in seconds: " << t << endl; 56 57 imshow("Output", K); 58 59 waitKey(0); 60 return 0; 61 } 62 void Sharpen(const Mat& myImage,Mat& Result) 63 { 64 CV_Assert(myImage.depth() == CV_8U); // accept only uchar images 65 66 const int nChannels = myImage.channels(); 67 Result.create(myImage.size(),myImage.type()); 68 69 for(int j = 1 ; j < myImage.rows-1; ++j) 70 { 71 const uchar* previous = myImage.ptr<uchar>(j - 1); 72 const uchar* current = myImage.ptr<uchar>(j ); 73 const uchar* next = myImage.ptr<uchar>(j + 1); 74 75 uchar* output = Result.ptr<uchar>(j); 76 77 for(int i= nChannels;i < nChannels*(myImage.cols-1); ++i) 78 { 79 *output++ = saturate_cast<uchar>(5*current[i] 80 -current[i-nChannels] - current[i+nChannels] - previous[i] - next[i]); 81 } 82 } 83 84 Result.row(0).setTo(Scalar(0)); 85 Result.row(Result.rows-1).setTo(Scalar(0)); 86 Result.col(0).setTo(Scalar(0)); 87 Result.col(Result.cols-1).setTo(Scalar(0)); 88 } 89