perspective-correction.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include <opencv2/opencv.hpp>
  2. using namespace cv;
  3. using namespace std;
  4. struct userdata{
  5. Mat im;
  6. vector<Point2f> points;
  7. };
  8. void mouseHandler(int event, int x, int y, int flags, void* data_ptr)
  9. {
  10. if ( event == EVENT_LBUTTONDOWN )
  11. {
  12. userdata *data = ((userdata *) data_ptr);
  13. circle(data->im, Point(x,y),3,Scalar(0,0,255), 5, cv::LINE_AA);
  14. imshow("Image", data->im);
  15. if (data->points.size() < 4)
  16. {
  17. data->points.push_back(Point2f(x,y));
  18. }
  19. }
  20. }
  21. int main( int argc, char** argv)
  22. {
  23. // Read source image.
  24. Mat im_src = imread("book1.jpg");
  25. // Destination image. The aspect ratio of the book is 3/4
  26. Size size(300,400);
  27. Mat im_dst = Mat::zeros(size,CV_8UC3);
  28. // Create a vector of destination points.
  29. vector<Point2f> pts_dst;
  30. pts_dst.push_back(Point2f(0,0));
  31. pts_dst.push_back(Point2f(size.width - 1, 0));
  32. pts_dst.push_back(Point2f(size.width - 1, size.height -1));
  33. pts_dst.push_back(Point2f(0, size.height - 1 ));
  34. // Set data for mouse event
  35. Mat im_temp = im_src.clone();
  36. userdata data;
  37. data.im = im_temp;
  38. cout << "Click on the four corners of the book -- top left first and" << endl
  39. << "bottom left last -- and then hit ENTER" << endl;
  40. // Show image and wait for 4 clicks.
  41. imshow("Image", im_temp);
  42. // Set the callback function for any mouse event
  43. setMouseCallback("Image", mouseHandler, &data);
  44. waitKey(0);
  45. // Calculate the homography
  46. Mat h = findHomography(data.points, pts_dst);
  47. // Warp source image to destination
  48. warpPerspective(im_src, im_dst, h, size);
  49. // Show image
  50. imshow("Image", im_dst);
  51. waitKey(0);
  52. return 0;
  53. }