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