
// Convolves.java
// Andrew Davison, ad@coe.psu.ac.th, April 2023

/* Three convolution examples (uncomment the one you want
   to try), and conversion to grayscale if the input image
   is RGB.

   Usage:
     > compile Convolves.java
     > run Convolves <fnm>
   e.g.
     > run Convolves boats.png
     > run Convolves frankenburg-1918.png

*/

import ij.*;
import ij.plugin.filter.*;


public class Convolves
{

  public static void main(String[] args)
  {
    if (args.length != 1) {
      System.out.println("Usage: run Convolves <fnm>");
      return;
    }

    ImagePlus imp = new ImagePlus(args[0]);

    if (imp.isRGB()) {   // only for grayscale 
      System.out.println("Converting RGB to grayscale");
      IJ.run(imp, "8-bit", "");
    }
     
    imp.show();
    IJ.wait(2000);   // so changes can be seen


    float[] kernel = { -1, -1, -1, -1, -1,  // edge detection
                       -1, -1, -1, -1, -1,
                       -1, -1, 24, -1, -1,
                       -1, -1, -1, -1, -1,
                       -1, -1, -1, -1, -1   };

/*
    float[] kernel = {   // sharpen
       0, -1,  0,
      -1,  5, -1,
       0, -1,  0
    };
*/

/*
    float n9 = 1f/9f;
    float[] kernel = {  // box blur (normalized)
      n9, n9, n9,
      n9, n9, n9,
      n9, n9, n9
    };
*/

    int size = (int)Math.sqrt(kernel.length);
    if (size*size != kernel.length)
      System.out.println("Kernel size error");

    Convolver cv = new Convolver();
    cv.setNormalize(true);
    boolean res = cv.convolve(imp.getProcessor(), kernel, size, size);
    imp.updateAndDraw();
    if (!res)
      System.out.println("Convolution failed");

  } /* main */


}  // end of Convolves class
