pagenormalizer.cpp 2.7 KB

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