/**
	* Dilate_SE function with a configurable 3x3 structuring element (hot spot in center)
	*
	* The code is a modified version of a sample code which is available in origin 
	* as part of the book "Digital Image Processing - An Algorithmic Introduction using Java"
	* by Wilhelm Burger and Mark J. Burge.
	*
	* For direct use of the Dilate_SE filter from the Plugins menu, the fixed coded structuring element
	* can be changed in the java code before compilation. 
	*
	* The Dilate_SE filter can be utilized as a macro function:
	* run("Dilate SE", "000110000");
	* The 3x3 structuring element is passed as a string with exactly 9 elements (0 or 1).
	* 
	* The logic of the structuring element string is
	* A  B  C
	* D  E  F   = ABCDEFGHI
	* G  H  I
	* 
	* A horizontal dilation can be defined as
	* 0  0  0
	* 1  1  0  = 000110000
	* 0  0  0
 	* 
	* A vertical dilation can be defined as
	* 0  1  0
	* 0  1  0  = 010010000
	* 0  0  0
	* 
	* A diagonal dilation can be defined as
	* 1  0  0
	* 0  1  0  = 100010000
	* 0  0  0
	* 
	* Author: Peter Haub 02/2011
	**/

import ij.IJ;
import ij.ImagePlus;
import ij.Macro;
import ij.plugin.filter.PlugInFilter;
import ij.process.Blitter;
import ij.process.ImageProcessor;

public class Dilate_SE implements PlugInFilter{
	ImagePlus imp;
	
	int[][] H = {{0,0,0},{1,1,0},{0,0,0}}; // structuring element
	
	public int setup(String arg, ImagePlus imp) {
		this.imp = imp;
		return DOES_ALL;
	}
	
	public void run(ImageProcessor ip) {
		String options = Macro.getOptions();
		if (options != null){
			if (options.length() == 10){
				for (int i=0; i<(options.length()-1); i++){
					H[i/3][i-(i/3)*3] = Integer.parseInt(options.substring(i, i+1));
				}
			}
			else {
				IJ.log("Option string invalid");
				return;
			}
		}
		
		//assume that the hot spot of structuring element is at its center (ic,jc)
		int ic = (H[0].length - 1) / 2;
		int jc = (H.length - 1) / 2;
		int N = H.length * H[0].length;
		
		ImageProcessor tmp = ip.createProcessor(ip.getWidth(),ip.getHeight());
		
		int k = 0;
		IJ.showProgress(k,N);
		for (int j=0; j<H.length; j++){
			for (int i=0; i<H[j].length; i++){
				if (H[j][i] > 0) {	// this pixel is set
					//copy image into position (i-ic,j-jc)
					tmp.copyBits(ip,i-ic,j-jc,Blitter.MAX);
				}
				IJ.showProgress(k++,N);
			}
		}
		ip.copyBits(tmp,0,0,Blitter.COPY);
	}
}