import ij.*;
import ij.io.*;
import ij.process.*;
import ij.gui.*;
import ij.text.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import ij.plugin.frame.*;
import java.io.*;
import java.util.*;
import javax.swing.event.*;


/** 
    This plugin implements the Gaussian noise
    @author Leonardi Rosa-BS degree in Computer Science 
    Advisor: Prof. Battiato Sebastiano
    Organization: University of Catania - ITALY
*/
public class Gaussian_Noise extends PlugInFrame implements ActionListener, TextListener
{
    private Font monoFont = new Font("Monospaced", Font.PLAIN, 12);
    private Font sans = new Font("SansSerif", Font.BOLD, 12);
    private Button preview;
    private Button apply;
    private long time;
    private ImageProcessor ip;  
    private ImagePlus imp;
    private int type;
    private TextField devField;
    private double dev=25.0;//standard deviation
    public Gaussian_Noise() 
    {
        super("Gaussian Noise");
        setResizable(true);
    }
    public void run(String arg) 
    {
        imp = WindowManager.getCurrentImage();
        if (imp==null) 
        {
            IJ.beep();
            IJ.showStatus("No image");
            IJ.noImage();
            return;
        }
        ip = imp.getProcessor();
        int imgWidth=ip.getWidth();
        int imgHeight=ip.getHeight();
        type = imp.getType(); 
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        setLayout(gridbag);
        
        // Panel title
        Panel paneltitle = new Panel();
        Label title= new Label("Gaussian Noise", Label.CENTER);
        title.setFont(sans);
        paneltitle.add(title);
        c.gridx = 0;
        int y = 0;
        c.gridy = y++;
        c.fill = GridBagConstraints.BOTH;
        c.anchor = GridBagConstraints.CENTER;
        c.insets = new Insets(5, 10, 0, 10);//top,left,bottom,right
        gridbag.setConstraints(paneltitle, c);
        add(paneltitle);
        
        // panel parameter
        Panel panelPar = new Panel();
        Label devLab = new Label("Standard Deviation: ");
        devLab.setFont(new Font("SansSerif", Font.PLAIN, 12));
        panelPar.add(devLab);
        int digits=2;
        devField = new TextField(IJ.d2s(dev, digits),3);
        devField.addTextListener(this);
        panelPar.add(devField);
        
        
        // panel Preview
        Panel panelPreview = new Panel();
        preview = new Button("Preview");
        preview.addActionListener(this);
        panelPreview.add(preview);
        
        // panel Apply
        Panel panelApply = new Panel();
        apply = new Button("Apply");
        apply.addActionListener(this);
        panelApply.add(apply);
        
        // panel Info & Help
        Panel panelInfoHelp = new Panel();
        Button ih = new Button("Help & Info");
        ih.addActionListener(new InfoHelpViewerGaussianNoise());
        panelInfoHelp.add(ih);
            
        // panel container
        Panel container=new Panel();
        container.setLayout(new GridLayout(4,1));
        c.gridy = y++;
        c.insets = new Insets(10, 0, 0, 10);
        gridbag.setConstraints(container, c);
        container.add(panelPar);
        container.add(panelPreview);
        container.add(panelApply);
        container.add(panelInfoHelp);
        add(container);
        
        // - - - - - - - - - - - - - - - - - -
        pack();
        GUI.center(this);
        show();
    }
    public void actionPerformed(ActionEvent e)
    {
        Object source=e.getSource();
        if(source==preview)
        {
            GaussianNoise gn=null;
            WindowManager.setTempCurrentImage(imp);
            time=System.currentTimeMillis();
            ImagePlus processed=null;
            gn= new GaussianNoise(imp, imp.getTitle(),dev);
            if((type==ImagePlus.GRAY8)||(type==ImagePlus.GRAY16)||(type==ImagePlus.GRAY32)||(type==ImagePlus.COLOR_256))
                processed=gn.createProcessed8bitImage();
            else if(type==ImagePlus.COLOR_RGB)
                processed=gn.createProcessedRGBImage();
            time=System.currentTimeMillis()-time;
            double time_sec=time/1000.0;
            PreviewImageGaussianNoise prew=new PreviewImageGaussianNoise(processed,time_sec);
        }
        if(source==apply)
        {     
            Undo.setup(Undo.COMPOUND_FILTER, imp);
            WindowManager.setTempCurrentImage(imp);
            GaussianNoise gn= new GaussianNoise(imp, imp.getTitle(),dev);
            if((type==ImagePlus.GRAY8)||(type==ImagePlus.GRAY16)||(type==ImagePlus.GRAY32)||(type==ImagePlus.COLOR_256))
                gn.createProcessed8bitImage(imp);
            else if(type==ImagePlus.COLOR_RGB)
                gn.createProcessedRGBImage(imp);
            
            imp.updateAndRepaintWindow();
            imp.changes=true;
            Undo.setup(Undo.COMPOUND_FILTER_DONE, imp);
            close();
        }
    }
    public void textValueChanged(TextEvent e) 
    {
        TextComponent tc = (TextComponent)e.getSource();
        if(tc==devField)
        {
            try
            {
                dev=Double.parseDouble(devField.getText());  
            }
            catch(NumberFormatException exp)
            {
                IJ.error("Number Format Exception","You must enter a number");  
            }
        }   
    }
}
class InfoHelpViewerGaussianNoise implements ActionListener
{
    private String description="HELP ABOUT \"Gaussian noise\"\n\n"+
            "This plugin allows to degrade an image with the Gaussian noise \n"+
            "User can:\n"+
            "1) To insert the standard deviation of gaussian noise to add to the image \n"+
            "2) Click on the button \"Preview\" to view as the image would be if it was processed with the gaussian noise;\n"+
            "3) Click on the button \"Apply\" to definitively apply the impulse noise to the image;\n\n"+
            "ABOUT THE AUTHOR\n"+
                "This plugin was implemented by Leonardi Rosa under Professor Sebastiano Battiato's supervision.\n"+
                "It was a part of a project for the Multimedia Course (MSC Program in Computer Science) at University of Catania (ITALY)\n\n"+
                "CONTACT INFO\n"+
                "For further information contact us:\n"+
                "Prof. Battiato Sebastiano, Ph.d. in Computer Science, e-mail: battiato@dmi.unict.it, web: http://www.dmi.unict.it/~battiato\n"+
                "Leonardi Rosa, BS degree in Computer Science, e-mail: angirosa@tiscali.it\n\n"+
                "LINKS\n"+
                "IPLab - Image Processing Laboratory - University of Catania (Italy), web: http://www.dmi.unict.it/~iplab\n"+
                "Department of Mathematics and Computer Science - University of Catania (Italy), web: http://www.dmi.unict.it/";
  
    public void actionPerformed(ActionEvent e) 
    {
        StringBuffer sb = new StringBuffer();
        sb.append(description);
        TextWindow tw = new TextWindow("About \"Gaussian Noise\"", sb.toString(), 700, 500);
        tw.show();
    }
}
class PreviewImageGaussianNoise implements ActionListener
{
    private ImageCanvas canvas;
    private Panel panelTime;
    private ImagePlus im;
        
    public PreviewImageGaussianNoise(ImagePlus img, double time)
    {
        im=img;
        canvas=new ImageCanvas(im);
        ImageWindow imgWin=new ImageWindow(im);
        imgWin.setResizable(false);
        imgWin.setSize(canvas.getSize().width+150,canvas.getSize().height+150);
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        imgWin.setLayout(gridbag);
        
        //Panel Canvas
        c.gridx = 0;
        int y=0;
        c.gridy = y++;
        c.insets = new Insets(10, 10, 0, 10);
        gridbag.setConstraints(canvas, c);
        imgWin.add(canvas);
        
        //Panel Time
        Panel panelTime = new Panel();
        c.gridy = y++;
        c.insets = new Insets(2, 10, 0, 10);
        gridbag.setConstraints(panelTime, c);
        Label timeLab = new Label("Elapsed Time: ");
        timeLab.setFont(new Font("SansSerif", Font.PLAIN, 12));
        panelTime.add(timeLab);
        Label timeLab2 = new Label(new Double(time).toString()+" seconds");
        timeLab2.setFont(new Font("SansSerif", Font.PLAIN, 12));
        panelTime.add(timeLab2);
        imgWin.add(panelTime);
        
        Panel panelHisto = new Panel();
        c.gridy = y++;
        c.insets = new Insets(2, 10, 0, 10);
        gridbag.setConstraints(panelHisto, c);
        Button histo = new Button("View Histogram");
        histo.addActionListener(this);
        panelHisto.add(histo);
        imgWin.add(panelHisto);
        imgWin.show();
    }
      
    public void actionPerformed(ActionEvent e) 
    {
        HistogramWindow isto=new HistogramWindow(im.getTitle(),im,256);
        isto.show();
    }
}
class GaussianNoise
{
    private ImagePlus imp;
    private ImageProcessor ip;
    private int width;
    private int height;
    private String title; 
    private double devStd;//deviation standard
    Random r = new Random();
    public GaussianNoise(ImagePlus image, String t, double dev) 
    {
	    imp=image;
        ip=imp.getProcessor();
        width=ip.getWidth();
        height=ip.getHeight();
        title=t;
        devStd=dev;
    }
    public byte[] applyTransform(byte[] pixels)
    {
        byte[] output = new byte[pixels.length];
        double ran1;    
        int src;
        int result = 0;
        for (int i = 0; i < output.length; i++)
        {
            src = pixels[i]&0xff;
    
            //Generate amount to be added
            //nextGaussian(): Returns the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence.
            ran1 = (devStd*(r.nextGaussian()));      
            result = (int)(src + ran1);
      
            if(result < 0) 
                result = 0;
            if(result > 255) 
                result = 255;
      
            //Convert back to 32 bit integer value
            output[i]=(byte)result;
        }
        return output;
    }
    public int[] applyTransform(int[] pixels)
    {
        int[] output = new int[pixels.length];
        double ran1=0;    
        int result_red = 0;
        int result_green = 0;
        int result_blue = 0;
        for (int i = 0; i < output.length; i++)
        {
            int c=pixels[i];
            int red=(c&0xff0000)>>16;
            int green=(c&0x00ff00)>>8;
            int blue=(c&0x0000ff);
            
            //Generate amount to be added
            ran1 = (devStd*(r.nextGaussian()));      
            result_red=(int)(red + ran1);
            result_green=(int)(green + ran1);
            result_blue=(int)(blue + ran1);
    
            if(result_red < 0) 
                result_red = 0;
            if(result_green < 0) 
                result_green = 0;
            if(result_blue < 0) 
                result_blue = 0;
            if(result_red > 255) 
                result_red = 255;
            if(result_green > 255) 
                result_green = 255;
            if(result_blue > 255) 
                result_blue = 255;
            
            output[i] = ((result_red&0xff)<<16)+((result_green&0xff)<<8)+(result_blue&0xff);
        }
        return output;
    }
    public ImagePlus createProcessed8bitImage()
    {
        ImageProcessor processed_ip = ip.crop();
        ImagePlus processed= imp.createImagePlus();
        processed.setProcessor(title, processed_ip);
        byte[] processed_pixels = (byte[])processed_ip.getPixels();
        byte[] output=applyTransform(processed_pixels);
        for (int i=0; i<output.length; i++) 
            processed_pixels[i]=(byte)(output[i]);
        return processed;
    }
    public void createProcessed8bitImage(ImagePlus img)
    {
        byte[] processed_pixels = (byte[])ip.getPixels();
        byte[] output=applyTransform(processed_pixels);
        for (int i=0; i<output.length; i++) 
            processed_pixels[i]=(byte)(output[i]);
    }
    public ImagePlus createProcessedRGBImage()
    {
        ImageProcessor processed_ip = ip.crop();
        ImagePlus processed= imp.createImagePlus();
        processed.setProcessor(title, processed_ip);
        int[] processed_pixels = (int[])processed_ip.getPixels();
        int[] output= applyTransform(processed_pixels);
        for (int i=0; i<output.length; i++) 
            processed_pixels[i]=output[i];
        return processed;
    }
    public void createProcessedRGBImage(ImagePlus img)
    {
        int[] processed_pixels = (int[])(img.getProcessor()).getPixels();
        int[] output= applyTransform(processed_pixels);
        for (int i=0; i<output.length; i++) 
            processed_pixels[i]=output[i];
    }
}