OpenCV  4.2.0
Open Source Computer Vision
samples/cpp/warpPerspective_demo.cpp

An example program shows using cv::findHomography and cv::warpPerspective for image warping

#include <iostream>
using namespace std;
using namespace cv;
static void help(char** argv)
{
// print a welcome message, and the OpenCV version
cout << "\nThis is a demo program shows how perspective transformation applied on an image, \n"
"Using OpenCV version " << CV_VERSION << endl;
cout << "\nUsage:\n" << argv[0] << " [image_name -- Default right.jpg]\n" << endl;
cout << "\nHot keys: \n"
"\tESC, q - quit the program\n"
"\tr - change order of points to rotate transformation\n"
"\tc - delete selected points\n"
"\ti - change order of points to inverse transformation \n"
"\nUse your mouse to select a point and move it to see transformation changes" << endl;
}
static void onMouse(int event, int x, int y, int, void*);
Mat warping(Mat image, Size warped_image_size, vector< Point2f> srcPoints, vector< Point2f> dstPoints);
String windowTitle = "Perspective Transformation Demo";
String labels[4] = { "TL","TR","BR","BL" };
vector< Point2f> roi_corners;
vector< Point2f> dst_corners(4);
int roiIndex = 0;
bool dragging;
int selected_corner_index = 0;
bool validation_needed = true;
int main(int argc, char** argv)
{
help(argv);
CommandLineParser parser(argc, argv, "{@input| right.jpg |}");
string filename = samples::findFile(parser.get<string>("@input"));
Mat original_image = imread( filename );
Mat image;
float original_image_cols = (float)original_image.cols;
float original_image_rows = (float)original_image.rows;
roi_corners.push_back(Point2f( (float)(original_image_cols / 1.70), (float)(original_image_rows / 4.20) ));
roi_corners.push_back(Point2f( (float)(original_image.cols / 1.15), (float)(original_image.rows / 3.32) ));
roi_corners.push_back(Point2f( (float)(original_image.cols / 1.33), (float)(original_image.rows / 1.10) ));
roi_corners.push_back(Point2f( (float)(original_image.cols / 1.93), (float)(original_image.rows / 1.36) ));
namedWindow(windowTitle, WINDOW_NORMAL);
namedWindow("Warped Image", WINDOW_AUTOSIZE);
moveWindow("Warped Image", 20, 20);
moveWindow(windowTitle, 330, 20);
setMouseCallback(windowTitle, onMouse, 0);
bool endProgram = false;
while (!endProgram)
{
if ( validation_needed & (roi_corners.size() < 4) )
{
validation_needed = false;
image = original_image.clone();
for (size_t i = 0; i < roi_corners.size(); ++i)
{
circle( image, roi_corners[i], 5, Scalar(0, 255, 0), 3 );
if( i > 0 )
{
line(image, roi_corners[i-1], roi_corners[(i)], Scalar(0, 0, 255), 2);
circle(image, roi_corners[i], 5, Scalar(0, 255, 0), 3);
putText(image, labels[i].c_str(), roi_corners[i], FONT_HERSHEY_SIMPLEX, 0.8, Scalar(255, 0, 0), 2);
}
}
imshow( windowTitle, image );
}
if ( validation_needed & ( roi_corners.size() == 4 ))
{
image = original_image.clone();
for ( int i = 0; i < 4; ++i )
{
line(image, roi_corners[i], roi_corners[(i + 1) % 4], Scalar(0, 0, 255), 2);
circle(image, roi_corners[i], 5, Scalar(0, 255, 0), 3);
putText(image, labels[i].c_str(), roi_corners[i], FONT_HERSHEY_SIMPLEX, 0.8, Scalar(255, 0, 0), 2);
}
imshow( windowTitle, image );
dst_corners[0].x = 0;
dst_corners[0].y = 0;
dst_corners[1].x = (float)std::max(norm(roi_corners[0] - roi_corners[1]), norm(roi_corners[2] - roi_corners[3]));
dst_corners[1].y = 0;
dst_corners[2].x = (float)std::max(norm(roi_corners[0] - roi_corners[1]), norm(roi_corners[2] - roi_corners[3]));
dst_corners[2].y = (float)std::max(norm(roi_corners[1] - roi_corners[2]), norm(roi_corners[3] - roi_corners[0]));
dst_corners[3].x = 0;
dst_corners[3].y = (float)std::max(norm(roi_corners[1] - roi_corners[2]), norm(roi_corners[3] - roi_corners[0]));
Size warped_image_size = Size(cvRound(dst_corners[2].x), cvRound(dst_corners[2].y));
Mat H = findHomography(roi_corners, dst_corners); //get homography
Mat warped_image;
warpPerspective(original_image, warped_image, H, warped_image_size); // do perspective transformation
imshow("Warped Image", warped_image);
}
char c = (char)waitKey( 10 );
if ((c == 'q') | (c == 'Q') | (c == 27))
{
endProgram = true;
}
if ((c == 'c') | (c == 'C'))
{
roi_corners.clear();
}
if ((c == 'r') | (c == 'R'))
{
roi_corners.push_back(roi_corners[0]);
roi_corners.erase(roi_corners.begin());
}
if ((c == 'i') | (c == 'I'))
{
swap(roi_corners[0], roi_corners[1]);
swap(roi_corners[2], roi_corners[3]);
}
}
return 0;
}
static void onMouse(int event, int x, int y, int, void*)
{
// Action when left button is pressed
if (roi_corners.size() == 4)
{
for (int i = 0; i < 4; ++i)
{
if ((event == EVENT_LBUTTONDOWN) & ((abs(roi_corners[i].x - x) < 10)) & (abs(roi_corners[i].y - y) < 10))
{
selected_corner_index = i;
dragging = true;
}
}
}
else if ( event == EVENT_LBUTTONDOWN )
{
roi_corners.push_back( Point2f( (float) x, (float) y ) );
validation_needed = true;
}
// Action when left button is released
if (event == EVENT_LBUTTONUP)
{
dragging = false;
}
// Action when left button is pressed and mouse has moved over the window
if ((event == EVENT_MOUSEMOVE) && dragging)
{
roi_corners[selected_corner_index].x = (float) x;
roi_corners[selected_corner_index].y = (float) y;
validation_needed = true;
}
}
cv::Mat::rows
int rows
the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
Definition: mat.hpp:2086
cv::FONT_HERSHEY_SIMPLEX
normal size sans-serif font
Definition: imgproc.hpp:814
cv::String
std::string String
Definition: cvstd.hpp:150
calib3d.hpp
cv::Mat::clone
Mat clone() const CV_NODISCARD
Creates a full copy of the array and the underlying data.
cv::moveWindow
void moveWindow(const String &winname, int x, int y)
Moves window to the specified position.
cv::samples::findFile
cv::String findFile(const cv::String &relative_path, bool required=true, bool silentMode=false)
Try to find requested data file.
cv::Point2f
Point_< float > Point2f
Definition: types.hpp:192
cv::WINDOW_NORMAL
the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal s...
Definition: highgui.hpp:183
cv::waitKey
int waitKey(int delay=0)
Waits for a pressed key.
CV_VERSION
#define CV_VERSION
Definition: version.hpp:19
cv::Size_
Template class for specifying the size of an image or rectangle.
Definition: types.hpp:315
highgui.hpp
cv::max
softfloat max(const softfloat &a, const softfloat &b)
Definition: softfloat.hpp:440
cv::namedWindow
void namedWindow(const String &winname, int flags=WINDOW_AUTOSIZE)
Creates a window.
cv::norm
static double norm(const Matx< _Tp, m, n > &M)
cv::EVENT_LBUTTONDOWN
indicates that the left mouse button is pressed.
Definition: highgui.hpp:207
cv::Size
Size2i Size
Definition: types.hpp:347
cv::findHomography
Mat findHomography(InputArray srcPoints, InputArray dstPoints, int method=0, double ransacReprojThreshold=3, OutputArray mask=noArray(), const int maxIters=2000, const double confidence=0.995)
Finds a perspective transformation between two planes.
cv::line
void line(InputOutputArray img, Point pt1, Point pt2, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)
Draws a line segment connecting two points.
cv::imread
Mat imread(const String &filename, int flags=IMREAD_COLOR)
Loads an image from a file.
cv::Mat::cols
int cols
Definition: mat.hpp:2086
imgcodecs.hpp
cv::swap
void swap(Mat &a, Mat &b)
Swaps two matrices.
cv::abs
static uchar abs(uchar a)
Definition: cvstd.hpp:66
cvRound
int cvRound(double value)
Rounds floating-point number to the nearest integer.
Definition: fast_math.hpp:197
cv::imshow
void imshow(const String &winname, InputArray mat)
Displays an image in the specified window.
cv::Scalar
Scalar_< double > Scalar
Definition: types.hpp:669
cv::setMouseCallback
void setMouseCallback(const String &winname, MouseCallback onMouse, void *userdata=0)
Sets mouse handler for the specified window.
cv::putText
void putText(InputOutputArray img, const String &text, Point org, int fontFace, double fontScale, Scalar color, int thickness=1, int lineType=LINE_8, bool bottomLeftOrigin=false)
Draws a text string.
cv::EVENT_MOUSEMOVE
indicates that the mouse pointer has moved over the window.
Definition: highgui.hpp:206
cv::Mat
n-dimensional dense array class
Definition: mat.hpp:791
cv::CommandLineParser
Designed for command line parsing.
Definition: utility.hpp:796
cv
"black box" representation of the file storage associated with a file on disk.
Definition: affine.hpp:51
imgproc.hpp
cv::WINDOW_AUTOSIZE
the user cannot resize the window, the size is constrainted by the image displayed.
Definition: highgui.hpp:184
cv::EVENT_LBUTTONUP
indicates that left mouse button is released.
Definition: highgui.hpp:210
cv::hal::warpPerspective
void warpPerspective(int src_type, const uchar *src_data, size_t src_step, int src_width, int src_height, uchar *dst_data, size_t dst_step, int dst_width, int dst_height, const double M[9], int interpolation, int borderType, const double borderValue[4])
cv::datasets::circle
Definition: gr_skig.hpp:62