
// Whiten.java
// Andrew Davison, ad@coe.psu.ac.th, Oct. 2022

/* Remove the yellowing from a picture of a book
   page by using contrast enhancement or by changing
   the min and max intensities on the grayscale 
   version of the page.

   Usage:
     > compile Whiten.java
     > run Whiten Whiten <fnm> [<min> <Max>]
   e.g.
     > run Whiten page.png
     > run Whiten page.png 0 200

*/

import java.io.*;
import java.awt.image.BufferedImage;


import ij.*;
import ij.process.*;
import ij.plugin.*;


public class Whiten
{
  private static final double CONTRAST_DEFAULT = 10;


  public static void main(String args[])
  {
    boolean useContrast = false;
    double min = 0;   // values between 0-255
    double max = 0;

    if (args.length == 1)
      useContrast = true;
    else if (args.length == 3) {
      min = ImageUtils.getDouble(args[1]);
      max = ImageUtils.getDouble(args[2]);
    }
    else {
      System.out.println("Usage: run Whiten <fnm> [<min> <Max>]");
      System.exit(0);
    }

    ImagePlus imp = new ImagePlus(args[0]);
    imp.show();
    ImagePlus dupImp = imp.duplicate();

    // convert to grayscale
    ImageConverter ic = new ImageConverter(dupImp);
    ic.convertToGray8();     // Type --> 8-bit
    System.out.println("- converted to 8-bit grayscale");

    // enhance contrast 
    if (useContrast) {
      ContrastEnhancer ce = new ContrastEnhancer();
      ce.stretchHistogram(dupImp, CONTRAST_DEFAULT);
      System.out.println("- whiten using contrast: " + CONTRAST_DEFAULT);
         // Process --> Enhance contrast
    }
    else {
      ImageProcessor ip = dupImp.getProcessor();
      ip.setMinAndMax(min, max);  
        // Image --> Adjust --> Brightness/Contrast
      System.out.println("- whiten using min-max: " + min + " - " + max);
    }

    dupImp.show();

    ImageUtils.waitGone(dupImp);
    System.exit(0);
  }  // end of main()


} // end  of Whiten class

