pagenormalizer.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #include "pagenormalizer.h"
  2. #include <iostream>
  3. #include <fstream>
  4. PageNormalizer::PageNormalizer() {
  5. width = height = 0;
  6. }
  7. PageNormalizer::PageNormalizer(const std::string inFile,const std::string outFile,const std::string whiteRef,const std::string blackRef,const std::string settingsFile) {
  8. // Read settings from text-file
  9. ReadSettings( settingsFile.c_str() );
  10. inImage = CImg<>( inFile.c_str() ); // Input image (Not manipulated)
  11. refImages[0] = CImg<>( whiteRef.c_str() ); // White
  12. refImages[1] = CImg<>( blackRef.c_str() ); // Black
  13. width = inImage.width();
  14. height = inImage.height();
  15. printf("Crop:%d,%d-%d,%d\n",cropX0,cropY0,cropX1,cropY1);
  16. outImage = CImg<>(cropX1-cropX0,cropY1-cropY0,1,3);
  17. NormalizeImage();
  18. outImage.save_jpeg( outFile.c_str() );
  19. }
  20. void PageNormalizer::NormalizeImage()
  21. {
  22. for(int y=cropY0;y<cropY1;y++)
  23. {
  24. for(int x=cropX0; x<cropX1;x++) {
  25. int wh = GetWhiteness(x,y);
  26. int bh = GetBlackness(x,y);
  27. double whiteFactor = 255.0 / ( wh - bh );
  28. int ch0 = ( inImage(x,y,0,0) - bh ) * whiteFactor;
  29. int ch1 = ( inImage(x,y,0,1) - bh ) * whiteFactor;
  30. int ch2 = ( inImage(x,y,0,2) - bh ) * whiteFactor;
  31. if( ch0 < 0 ) ch0=0; if( ch1 < 0 ) ch1=0; if( ch2 < 0 ) ch2=0;
  32. if( ch0 > 255 ) ch0=255; if( ch1 > 255 ) ch1=255; if( ch2 > 255 ) ch2=255;
  33. outImage(x-cropX0,y-cropY0,0,0) = (unsigned char) ch0;
  34. outImage(x-cropX0,y-cropY0,0,1) = (unsigned char) ch1;
  35. outImage(x-cropX0,y-cropY0,0,2) = (unsigned char) ch2;
  36. }
  37. }
  38. }
  39. int PageNormalizer::GetWhiteness(unsigned int x,unsigned int y) {
  40. return( refImages[0](x,y,0,0) );
  41. }
  42. int PageNormalizer::GetBlackness(unsigned int x,unsigned int y) {
  43. return( refImages[1](x,y,0,0) );
  44. }
  45. void PageNormalizer::ReadSettings(const std::string inFile)
  46. {
  47. std::cout << "Reading settings from: " << inFile << std::endl;
  48. std::string line;
  49. std::ifstream myfile( inFile.c_str() );
  50. if (myfile.is_open())
  51. {
  52. auto rowNum = -1;
  53. while( std::getline( myfile,line ) )
  54. {
  55. switch( rowNum ) {
  56. case -1: if( line.find("START:") == 0 ) rowNum = 0; break;
  57. case 1: cropX0 = std::stoi(line);break;
  58. case 2: cropY0 = std::stoi(line);break;
  59. case 3: cropX1 = std::stoi(line);break;
  60. case 4: cropY1 = std::stoi(line);break;
  61. }
  62. if( rowNum >= 0 ) rowNum++;
  63. }
  64. myfile.close();
  65. }
  66. else std::cout << "Unable to open file";
  67. }