
// ProjMap.java
// Andrew Davison, ad@coe.psu.ac.th, April 2023

/* Use projective mapping to undistort the address part of
   a picture of a package.

   Usage:
     > compile ProjMap.java
     > run ProjMap

   Based on an example from:
     Digital Image Processing – An Algorithmic Introduction 
     Wilhelm Burger and Mark J. Burge, 
     Springer, 2022, 3rd ed.
     https://imagingbook.com/

   But I used the plugin version by Martin Schlüter
   available at https://ij.ms3d.de/geometric_mappings.php
   which I installed into ImageJ's plugins/ directory as
   GeometricMappings/

   Also, run.bat sets the "plugins.dir" flag:
      -Dplugins.dir="ImageJ/plugins"
*/


import ij.*;
import ij.gui.*;
import ij.plugin.*;
import ij.plugin.filter.*;
import ij.process.*;


public class ProjMap
{
  private static final int LEN = 512;


  public static void main(String[] args)
  {
    ImagePlus boxImp = IJ.openImage("PostalPackage.jpg");
    boxImp.show();

    // hardwired ROI coordinates for the top of the package
    int[] xpts1 = {327, 987, 757, 20}; 
    int[] ypts1 = {70, 211, 593, 345};
    boxImp.setRoi( new PolygonRoi(xpts1, ypts1, 4, Roi.POLYGON));

    // to hold the projective mapping
    ImagePlus addrImp = IJ.createImage("Address", "RGB black", LEN, LEN, 1);
    addrImp.show();  
         // must be visible so that run() can execute
    
    // the ROI is the entire image rectangle
    int[] xpts2 =  {0, LEN-1, LEN-1, 0};  
    int[] ypts2 =  {0, 0, LEN-1, LEN-1}; 
    addrImp.setRoi( new PolygonRoi(xpts2, ypts2, 4, Roi.POLYGON));

    IJ.run(boxImp, "Projective Mapping", 
        "actual=PostalPackage.jpg target=Address interpolation=Bilinear");
        // Plugins --> Geometric Mappings --> Projective Mapping
    addrImp.updateAndDraw();

    ImageUtils.waitGone(addrImp);
    System.exit(0);
  } /* main */


}  // end of ProjMap class
