lines.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. #include<cmath>
  2. #include<algorithm>
  3. #include<unistd.h>
  4. #include<fstream>
  5. #include<iomanip>
  6. #ifdef HAS_OPENCV3
  7. #include <opencv2/core.hpp> //Any OPENCV3 code
  8. #else
  9. #include <opencv2/core/core.hpp> //Any Opencv2 code
  10. #endif
  11. #include"lines.h"
  12. #include "geometry.h"
  13. #include "cvutils.h"
  14. using namespace cv;
  15. #define likely(x) __builtin_expect(!!(x), 1)
  16. #define unlikely(x) __builtin_expect(!!(x), 0)
  17. // all those colors are still visible on b/w (the first component is not so low)
  18. auto WHITE = cv::Scalar(255,255,255);
  19. auto BLUE = cv::Scalar(200,50,50);
  20. auto MAGENTA = cv::Scalar(110,10,200);
  21. auto BROWN = cv::Scalar(90,100,60);
  22. auto BLACK = cv::Scalar(0,0,0);
  23. auto YELLOW = cv::Scalar(20,200,200);
  24. void usage(char* program, std::ostream &buf) {
  25. buf << "Usage: " << program << "[options] IMAGE-INPUT" << std::endl;
  26. buf << "Identify the image as a book in perspective, get deperspectivized content" << std::endl;
  27. buf << std::endl;
  28. buf << "Options:" << std::endl;
  29. buf << " -p PROFILE Save the transformation matrix in PROFILE" << std::endl;
  30. buf << " -l LEFTPAGE Save the left page in LEFTPAGE" << std::endl;
  31. buf << " -r RIGHTPAGE Save the right page in RIGHTPAGE" << std::endl;
  32. buf << " -h HELP Show this help and exit" << std::endl;
  33. }
  34. class Options
  35. {
  36. public:
  37. char *left;
  38. char *right;
  39. char *profile;
  40. char *input;
  41. Options();
  42. Options(int argc, char*argv[]);
  43. bool parse(int argc, char*argv[]);
  44. ~Options();
  45. };
  46. Options::Options()
  47. {
  48. left = right = profile = input = NULL;
  49. }
  50. Options::~Options()
  51. {
  52. if(left == NULL) {
  53. free(left);
  54. }
  55. if(right == NULL) {
  56. free(right);
  57. }
  58. if(profile == NULL) {
  59. free(profile);
  60. }
  61. //input doesn't need to be free-d: it points to argv[argc-1]
  62. }
  63. Options::Options(int argc, char *argv[])
  64. {
  65. left = right = profile = input = NULL;
  66. parse(argc, argv);
  67. }
  68. /* Options::parse parse arguments, return true if help is requested */
  69. bool Options::parse(int argc, char *argv[])
  70. {
  71. int c;
  72. while((c=getopt(argc, argv, "p:l:r:h")) != -1)
  73. {
  74. switch(c)
  75. {
  76. case 'l':
  77. left = strdup(optarg);
  78. break;
  79. case 'r':
  80. right = strdup(optarg);
  81. break;
  82. case 'p':
  83. profile = strdup(optarg);
  84. break;
  85. case 'h':
  86. return true;
  87. break;
  88. default:
  89. throw std::runtime_error("Parsing error: invalid argument");
  90. }
  91. }
  92. if(optind >= argc) {
  93. std::cerr << "Error: " << argv[0] << " needs an argument" << std::endl;
  94. throw std::runtime_error("Parsing error: argument needed");
  95. }
  96. input = argv[optind++];
  97. if(optind < argc) {
  98. std::cerr << "Error: too many arguments supplied" << std::endl;
  99. throw std::runtime_error("Parsing error: too many arguments");
  100. }
  101. return false;
  102. }
  103. int main(int argc, char *argv[])
  104. {
  105. Options args;
  106. try{
  107. if(args.parse(argc, argv)) {
  108. usage(argv[0], std::cout);
  109. return EXIT_SUCCESS;
  110. }
  111. } catch(std::runtime_error) {
  112. usage(argv[0], std::cerr);
  113. return EXIT_FAILURE;
  114. }
  115. cv::Mat img;
  116. img=cv::imread(args.input,CV_LOAD_IMAGE_GRAYSCALE);
  117. if( img.empty() ) {
  118. std::cerr << "Error opening image, aborting" << std::endl;
  119. return EXIT_FAILURE;
  120. }
  121. //dotwidth is just a simple size so that lines and dots are visible on big images
  122. //but not huge on small images
  123. #ifdef _DEBUG
  124. unsigned short dotwidth = img.cols >> 6; // divide by 64, so efficient
  125. #endif
  126. std::vector< std::vector<cv::Point> > contours;
  127. std::vector<cv::Vec4i> hierarchy; //this is not really useful
  128. cv::findContours(img,contours,hierarchy,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_SIMPLE);
  129. if( 0==contours.size() ) {
  130. std::cerr << "No contours found" << std::endl;
  131. return EXIT_FAILURE;
  132. }
  133. auto contour = contours[0];
  134. if( 1!=contours.size() )
  135. {
  136. // choosing the biggest contour in the image
  137. // you can test it with files/2contours.png
  138. for(auto cont: contours) {
  139. if(cont.size() > contour.size())
  140. contour = cont;
  141. }
  142. }
  143. //hull: points forming an external convex border
  144. std::vector<cv::Point> hull;
  145. cv::convexHull(cv::Mat(contour),hull,false);
  146. //because of the "butterfly" shape of a book, the most distant points in the hull
  147. //are the one between the corner.
  148. unsigned *maxdistances = max2_distance(hull);
  149. cv::Point corn_1, corn_2, corn_3, corn_4;
  150. corn_1 = hull[maxdistances[0]];
  151. corn_2 = hull[(maxdistances[0]+1)%hull.size()];
  152. corn_3 = hull[maxdistances[1]];
  153. corn_4 = hull[(maxdistances[1]+1)%hull.size()];
  154. #ifdef _DEBUG
  155. img = cv::imread(args.input,CV_LOAD_IMAGE_COLOR); // uncomment to this to display image with colors
  156. std::cout << "Maxdist1:" << maxdistances[0] << " " << corn_1 << corn_2 << std::endl;
  157. std::cout << "Maxdist2:" << maxdistances[1] << " " << corn_3 << corn_4 << std::endl;
  158. cv::namedWindow("win", CV_GUI_NORMAL);
  159. // cv::imshow("4 corners",img);
  160. // cv::waitKey(0);
  161. #endif
  162. std::vector<cv::Point> verticals[2];
  163. // Between the two corners on the same side, the longest line is the vertical border of the book
  164. verticals[0] = find_longest_line(hull, (maxdistances[0]+1)%hull.size(), maxdistances[1]);
  165. std::cout << maxdistances[1] << std::endl;
  166. std::cout << maxdistances[1]+1 << std::endl;
  167. std::cout << (maxdistances[1]+1)%hull.size() << std::endl;
  168. verticals[1] = find_longest_line(hull, (maxdistances[1]+1)%hull.size(), maxdistances[0]);
  169. free(maxdistances);
  170. // theta is the angle of the line connecting point 1 and 2; it will be the
  171. // rotation of our new coordinate system
  172. auto cs = CoordinateSystem(corn_1, corn_2);
  173. assert(cs.map(corn_1).x == 0);
  174. assert(cs.map(corn_1).y == 0);
  175. assert(cs.map(corn_2).x > 0);
  176. assert(cs.map(corn_2).y == 0);
  177. cv::Vec<double,3> diag1, diag2;
  178. diag1 = get_line(cs.map(corn_1), cs.map(corn_3));
  179. diag2 = get_line(cs.map(corn_4), cs.map(corn_2));
  180. std::cout << "mapped diag1: " << diag1 << std::endl;
  181. std::cout << "mapped diag2: " << diag2 << std::endl;
  182. std::vector<cv::Point> points1, points2;
  183. for(cv::Point p: contour)
  184. { // the point is interesting where it is above both lines or below both lines
  185. cv::Point mapped = cs.map(p);
  186. if(is_above_line(diag1, mapped)) {
  187. if(is_above_line(diag2, mapped)) {
  188. points1.push_back(p);
  189. }
  190. } else {
  191. if(!is_above_line(diag2, mapped)) {
  192. points2.push_back(p);
  193. }
  194. }
  195. }
  196. cv::Point middle1 = further_point_from_line(get_line(corn_1, corn_2), points2);
  197. cv::Point middle2 = further_point_from_line(get_line(corn_3, corn_4), points1);
  198. // we now have all the points of the two trapezoid (middle1 and middle2 are shared)
  199. cv::Mat trasf[2]; //transformation matrix
  200. double xsize = dist(corn_1, middle1), ysize=dist(middle1, middle2);
  201. cv::Point2f trapezoid[2][4] = {
  202. {corn_1, middle1, middle2, corn_4},
  203. {corn_2, corn_3, middle2, middle1}};
  204. cv::Point2f outsizes[4] = {cv::Point2f(0, 0), cv::Point(xsize, 0),
  205. cv::Point(xsize, ysize), cv::Point(0, ysize)};
  206. cv::Mat rect[2]; //final pages, transformed in a nice rectangle
  207. //we are rereading in full color to get colored output
  208. img = cv::imread(args.input,CV_LOAD_IMAGE_COLOR);
  209. for(int i=0; i < 2; i++) {
  210. trasf[i] = cv::getPerspectiveTransform(trapezoid[i], outsizes);
  211. assert(9==trasf[i].total()); // 3x3
  212. cv::warpPerspective(img, rect[i], trasf[i], cv::Size(xsize, ysize));
  213. }
  214. if(args.profile) {
  215. // format: each line is a tab-delimited 3x3 transformation matrix (as get by getPerspectiveTransform)
  216. // first three elements is the first line, etc
  217. std::ofstream profilebuf;
  218. profilebuf.open(args.profile);
  219. for(int t=0; t<2; t++) {
  220. for(int i=0; i<3; i++) {
  221. double* row= trasf[t].ptr<double>(i);
  222. for(int j=0; j < 3; j++) {
  223. profilebuf << std::fixed << std::setprecision(16);
  224. profilebuf << row[j] << "\t"; //yes, there's a trailing tab
  225. }
  226. }
  227. profilebuf << std::endl;
  228. }
  229. profilebuf.close();
  230. }
  231. #ifdef _DEBUG
  232. cv::line(img, corn_1, middle1, MAGENTA, dotwidth>>3);
  233. cv::line(img, corn_2, middle1, MAGENTA, dotwidth>>3);
  234. cv::line(img, middle1, middle2, BLACK, dotwidth>>4);
  235. cv::line(img, corn_3, middle2, MAGENTA, dotwidth>>3);
  236. cv::line(img, corn_4, middle2, MAGENTA, dotwidth>>3);
  237. cv::line(img, corn_2, corn_3, BLUE, dotwidth>>4);
  238. cv::line(img, corn_1, corn_4, BLUE, dotwidth>>4);
  239. std::cout << middle1 << middle2 << std::endl;
  240. cv::imshow("win",img);
  241. while(1)
  242. {
  243. if( (char)cv::waitKey(0) == 113 )
  244. break;
  245. }
  246. #endif
  247. //TODO: distinguish left and right
  248. std::vector<int> params;
  249. if(args.left || args.right) {
  250. params.push_back(CV_IMWRITE_PNG_COMPRESSION);
  251. params.push_back(9);
  252. if(args.left) {
  253. cv::imwrite(args.left, rect[0], params);
  254. }
  255. if(args.right) {
  256. cv::imwrite(args.right, rect[1], params);
  257. }
  258. }
  259. return EXIT_SUCCESS;
  260. }
  261. // vim: set noet ts=4 sw=4: