
// BGRemover.java
// Andrew Davison, April 2023, ad@coe.psu.ac.th

/*  Subtract a background image from an image to
    get just the foregound, and report its center.
*/


import ij.*;
import ij.process.*;
import ij.plugin.*;


public class BGRemover
{

  public static void main(String[]args)
  {
    ImagePlus imp = new ImagePlus("adChair.jpg");
    imp.show();

    ImagePlus bgImp = new ImagePlus("chair.jpg");
    bgImp.show();

    // background subtraction
    ImagePlus fgImp = ImageCalculator.run(imp, bgImp, "subtract create");
      // Process --> image Calculator
    fgImp.setTitle("Foreground");
    fgImp.show();
    reportMass(fgImp);

    // also test when there's no difference
    ImagePlus noImp = ImageCalculator.run(bgImp, bgImp, "subtract create");
    noImp.setTitle("Nothing");
    noImp.show();
    reportMass(noImp);   // will report (0,0)

    ImageUtils.waitGone("Foreground"); 
    System.exit(0);
  }  // end of main()


  private static void reportMass(ImagePlus imp)
  {
    ImageStatistics stats = imp.getStatistics(
                             ImageStatistics.CENTER_OF_MASS); 
    int xm = (int)stats.xCenterOfMass;
    int ym = (int)stats.yCenterOfMass; 
    System.out.println("Center of mass for " + imp.getTitle() +
                           ": (" + xm + ", " + ym + ")");
  }  // end of reportMass()


} // end of BGRemover class
