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 impulse (salt-and-pepper) noise
    @author Leonardi Rosa-BS degree in Computer Science 
    Advisor: Prof. Battiato Sebastiano
    Organization: University of Catania - ITALY
*/
public class Noise_Impulse 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 percField;
    private double percentage=0.05;
    public Noise_Impulse() 
    {
        super("Impuse 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("Impulse 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 percentage
        Panel panelPercentage = new Panel();
        Label percLab = new Label("Percentage of the noise: ");
        percLab.setFont(new Font("SansSerif", Font.PLAIN, 12));
        panelPercentage.add(percLab);
        int digits=2;
        percField = new TextField(IJ.d2s(percentage, digits),3);
        percField.addTextListener(this);
        panelPercentage.add(percField);
        
        // 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 InfoHelpViewerImpulseNoise());
        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(panelPercentage);
        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)
        {
            ImpulseNoise in=null;
            WindowManager.setTempCurrentImage(imp);
            time=System.currentTimeMillis();
            ImagePlus processed=null;
            in= new ImpulseNoise(imp, imp.getTitle(),percentage);
            if((type==ImagePlus.GRAY8)||(type==ImagePlus.GRAY16)||(type==ImagePlus.GRAY32)||(type==ImagePlus.COLOR_256))
                processed=in.createProcessed8bitImage();
            else if(type==ImagePlus.COLOR_RGB)
                processed=in.createProcessedRGBImage();
            time=System.currentTimeMillis()-time;
            double time_sec=time/1000.0;
            PreviewImageImpulseNoise prew=new PreviewImageImpulseNoise(processed,time_sec);
        }
        if(source==apply)
        {     
            Undo.setup(Undo.COMPOUND_FILTER, imp);
            WindowManager.setTempCurrentImage(imp);
            ImpulseNoise in= new ImpulseNoise(imp, imp.getTitle(),percentage);
            if((type==ImagePlus.GRAY8)||(type==ImagePlus.GRAY16)||(type==ImagePlus.GRAY32)||(type==ImagePlus.COLOR_256))
                in.createProcessed8bitImage(imp);
            else if(type==ImagePlus.COLOR_RGB)
                in.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==percField)
        {
            try
            {
                percentage=Double.parseDouble(percField.getText());  
            }
            catch(NumberFormatException exp)
            {
                IJ.error("Number Format Exception","You must enter a number");  
            }
        }   
    }
}
class InfoHelpViewerImpulseNoise implements ActionListener
{
    private String description="HELP ABOUT \"Impulse noise\"\n\n"+
            "This plugin allows to degrade an image with the impulse (or salt-and-pepper) noise \n"+
            "User can:\n"+
            "1) To insert the percentage of impulse 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 impulse 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 \" Impulse Noise\"", sb.toString(), 700, 500);
        tw.show();
    }
}
class PreviewImageImpulseNoise implements ActionListener
{
    private ImageCanvas canvas;
    private Panel panelTime;
    private ImagePlus im;
        
    public PreviewImageImpulseNoise(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 ImpulseNoise
{
    private ImagePlus imp;
    private ImageProcessor ip;
    private int width;
    private int height;
    private String title; 
    private double percent;
    Random r = new Random();
    public ImpulseNoise(ImagePlus image, String t, double percentage) 
    {
	    imp=image;
        ip=imp.getProcessor();
        width=ip.getWidth();
        height=ip.getHeight();
        title=t;
        percent=percentage;
    }
    public int rand(int min, int max) 
    {
        return min + (int)(r.nextDouble()*(max-min));
    }
    public byte[] applyTransform(byte[] pixels)
    {
        int n = (int)(percent*width*height);
        byte[] output = pixels;
        int rx, ry;
        int xmin = 0;
        int xmax = width;
        int ymin = 0;
        int ymax = height;
        for (int i=0; i<n/2; i++) 
        {
            rx = rand(xmin, xmax);
            ry = rand(ymin, ymax);
            output[ry*width+rx] = (byte)255;
            rx = rand(xmin, xmax);
            ry = rand(ymin, ymax);
            output[ry*width+rx] = (byte)0;
        }
        return output;
    }
    public int[] applyTransform(int[] pixels)
    {
        int n = (int)(percent*width*height);
        int[] output = pixels;
        int rx, ry;
        int xmin = 0;
        int xmax = width;
        int ymin = 0;
        int ymax = height;
        for (int i=0; i<n/2; i++) 
        {
            rx = rand(xmin, xmax);
            ry = rand(ymin, ymax);
            int c=pixels[ry*width+rx];
            int tmp_red=(c&0xff0000)>>16;
            int tmp_green=(c&0x00ff00)>>8;
            int tmp_blue=c&0x0000ff;
            tmp_red=255;
            tmp_green=255;
            tmp_blue=255;
            output[ry*width+rx] = ((tmp_red&0xff)<<16)+((tmp_green&0xff)<<8)+(tmp_blue&0xff);
            rx = rand(xmin, xmax);
            ry = rand(ymin, ymax);
            tmp_red=0;
            tmp_green=0;
            tmp_blue=0;
            output[ry*width+rx] = ((tmp_red&0xff)<<16)+((tmp_green&0xff)<<8)+(tmp_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];
    }
}