
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                                    %
%                                        C++                                         %
%                                                                                    %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\ifCpp
\section{Detection of planar objects}
The goal of this tutorial is to learn how to use features2d and calib3d modules for detecting known planar objects in scenes. 

\texttt{Test data}: use images in your data folder, for instance, box.png and box\_in\_scene.png. 

Create a new console project. Read two input images. Example:
\begin{lstlisting}
Mat img1 = imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE);
\end{lstlisting}

Detect keypoints in both images. Example:
\begin{lstlisting}
// detecting keypoints
FastFeatureDetector detector(15);
vector<KeyPoint> keypoints1;
detector.detect(img1, keypoints1);
\end{lstlisting}

Compute descriptors for each of the keypoints. Example:
\begin{lstlisting}
// computing descriptors
SurfDescriptorExtractor extractor;
Mat descriptors1;
extractor.compute(img1, keypoints1, descriptors1);
\end{lstlisting}

Now, find the closest matches between descriptors from the first image to the second:
\begin{lstlisting}
// matching descriptors
BruteForceMatcher<L2<float> > matcher;
vector<DMatch> matches;
matcher.match(descriptors1, descriptors2, matches);
\end{lstlisting}

Visualize the results:
\begin{lstlisting}
// drawing the results
namedWindow("matches", 1);
Mat img_matches;
drawMatches(img1, keypoints1, img2, keypoints2, matches, img_matches);
imshow("matches", img_matches);
waitKey(0);
\end{lstlisting}

Find the homography transformation between two sets of points:
\begin{lstlisting}
vector<Point2f> points1, points2;
// fill the arrays with the points
....
Mat H = findHomography(Mat(points1), Mat(points2), CV_RANSAC, ransacReprojThreshold);
\end{lstlisting}

Create a set of inlier matches and draw them. Use perspectiveTransform function to map points with homography:
\begin{lstlisting}
Mat points1Projected;
perspectiveTransform(Mat(points1), points1Projected, H);
\end{lstlisting}
Use drawMatches for drawing inliers. 
\fi