Image Comparison in Matlab [ Matrix Laboratory ] Using Histograms



An image histogram is a type of histogram that acts as a graphical representation of the tonal distribution in a digital image. It plots the number of pixels for each tonal value. By looking at the histogram for a specific image a viewer will be able to judge the entire tonal distribution at a glance.
Image histograms are present on many modern digital cameras. Photographers can use them as an aid to show the distribution of tones captured, and whether image detail has been lost to blown-out highlights or blacked-out shadows.

Using Matlab We Can get Histogram of any Image :  hist()

Syntax :

  • hist(data) creates a histogram bar plot of data. Elements in data are sorted into 10 equally spaced bins along the x-axis between the minimum and maximum values of data. Bins are displayed as rectangles such that the height of each rectangle indicates the number of elements in the bin.
  • hist(data,nbins) sorts data into the number of bins specified by nbins.
  • hist(data,xvalues) uses the values in vector xvalues to determine the bin intervals and sorts data into the number of bins determined by length(xvalues). To specify the bin centers, set xvalues equal to a vector of evenly spaced values. The first and last bins extend to cover the minimum and maximum values in data.
  • hist(axes_handle,___) plots into the axes specified by axes_handle instead of into the current axes (gca). The option axes_handle can precede any of the input argument combinations in the previous syntaxes.
  • nelements = hist(___) returns a row vector, nelements, indicating the number of elements in each bin.
  • [nelements,centers] = hist(___) returns an additional row vector, centers, indicating the location of each bin center on the x-axis. To plot the histogram, you can use bar(centers,nelements).

Simple Program Using Matlab to Compare 1 Image with other 4 Images :

% read two images
Image1 = imread('i1.jpg'); % Image 1
Image2 = imread('i2.jpg'); % Image 2
%  convert images to type double (range from from 0 to 1 instead of from 0 to 255)
Imaged1 = im2double(Image1);
Imaged2 = im2double(Image2);
% reduce three channel [ RGB ]  to one channel [ grayscale ]
Imageg1 = rgb2gray(Imaged1);
Imageg2 = rgb2gray(Imaged2);
% Calculate the Normalized Histogram of Image 1 and Image 2
hn1 = imhist(Imageg1)./numel(Imageg1);
hn2 = imhist(Imageg2)./numel(Imageg2);
 subplot(2,2,1);subimage(Image1)
 subplot(2,2,2);subimage(Image2)
 subplot(2,2,3);plot(hn1)
 subplot(2,2,4);plot(hn2)
% Calculate the histogram error
f = sum((hn1 - hn2).^2);
disp(f) %display the result to console

Using GUI:

Type Guide in Command Window


Open Existing GUI
Browse and Select File Downloaded from below


You Will get like this 
Press Run Button



Output Will be...

Load Image By Right Clicking each corresponding button for each Image. 



And Click Compare button, Which Compares Image 1 with all other images [ 2,3,4,5 ].

And You will get Results under the Images.

Higher Value =  More Difference
Lesser Value =  Lesser Difference
0 = No Difference

Download Links :

  1. compare.m : Click Here to Download 
  2. compare.fig : Click Here to Download

Image Processing using Java




Program :

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Dialog;
import java.awt.image.DataBufferByte;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;


class Global {
public static int flag=0;
public static Image image=null;
public static BufferedImage bimage=null;
public static BufferedImage insertimage=null;
public static int imageinsertstatus=0;
}

public class ImageProcessing{
public static void main(String[] args) throws IOException{

final JFrame f = new JFrame("Image Processing");
f.setVisible(true);
f.setSize(700,700);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel mainPanel=new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

final JLabel p=new JLabel();
p.setPreferredSize(new Dimension(600, 600));
p.setAlignmentX(Component.CENTER_ALIGNMENT);
mainPanel.add(p);


f.addMouseListener(new MouseListener() {
    @Override
    public void mouseClicked(MouseEvent e) {
        if( Global.insertimage != null)
        {
                ImageIcon icon = (ImageIcon)p.getIcon();
                Image img = (Image) icon.getImage();
                BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
                Graphics2D bGr = bimage.createGraphics();
                bGr.drawImage(img, 0, 0, null);
                bGr.dispose();
                BufferedImage sourceImage = bimage;
                BufferedImage overlayImage = Global.insertimage;
                Graphics2D g2Source = sourceImage.createGraphics();
                g2Source.drawImage(overlayImage, e.getX()-20, e.getY()-26,null);
                g2Source.dispose(); 
                p.setIcon(new ImageIcon(sourceImage));
                Global.insertimage = null;
        }
     }
    @Override
    public void mouseExited(MouseEvent e) {}
    @Override
    public void mouseEntered(MouseEvent e) {}
    @Override
    public void mouseReleased(MouseEvent e) {}
    @Override
    public void mousePressed(MouseEvent e) {}
});

mainPanel.add(Box.createRigidArea(new Dimension(0, 10)));

JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));


JButton openBtn = new JButton("Load Picture");
buttonPane.add(openBtn);

openBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0)
        {
                Global.flag=0;
                Global.image=null;
                Global.bimage=null;
                Global.insertimage=null;
                Global.imageinsertstatus=0;
                JFileChooser fc = new JFileChooser();
                BufferedImage image=null;
                Image dimg=null;
                fc.setCurrentDirectory(new File("."));
                int retVal = fc.showOpenDialog(null);
                if (retVal == 0)
                {
                    File file = fc.getSelectedFile();
                    try { image = ImageIO.read(file); dimg= image.getScaledInstance(600, 600,Image.SCALE_SMOOTH); Global.image=dimg;Global.bimage=image; }
                    catch (IOException e1) { e1.printStackTrace(); }
                }
                p.setIcon(new ImageIcon(dimg));

        }
});

buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
JButton svBtn = new JButton("Save Picture");
buttonPane.add(svBtn);

svBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0)
        {
        if( Global.image != null)
        {
                JFileChooser fc = new JFileChooser();
                int returnVal = fc.showSaveDialog(null);
                if (returnVal == JFileChooser.APPROVE_OPTION)
                {
                File file = fc.getSelectedFile();
                ImageIcon icon = (ImageIcon)p.getIcon();
                Image img = (Image) icon.getImage();   
                BufferedImage bimg = new BufferedImage(img.getWidth(null), img.getHeight(null),BufferedImage.TYPE_INT_RGB);
                Graphics2D gg = bimg.createGraphics();
                gg.drawImage(img, 0, 0, null);
                try { ImageIO.write(bimg, "jpg", file); JOptionPane.showMessageDialog(f,"File Saved","Message",JOptionPane.PLAIN_MESSAGE);}
                catch (IOException e1) { e1.printStackTrace(); }
                }
        }
        else
        {
        JOptionPane.showMessageDialog(f,"Image Not Loaded..","Message",JOptionPane.PLAIN_MESSAGE);
        }
    }
});

buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
JButton CBtn = new JButton("Change Colour");
Global.flag=0;
buttonPane.add(CBtn);
CBtn.addActionListener(new ActionListener() {
     @Override
     public void actionPerformed(ActionEvent arg0) {
         if( Global.image != null)
        {
            if (Global.flag == 0 ) {
                ImageIcon icon = (ImageIcon)p.getIcon();
                Image img = (Image) icon.getImage();   
                BufferedImage bimg = new BufferedImage(img.getWidth(null), img.getHeight(null),BufferedImage.TYPE_BYTE_GRAY);
                Graphics2D gg = bimg.createGraphics();
                gg.drawImage(img, 0, 0, null);
                p.setIcon(new ImageIcon(bimg));
                Global.flag = 1;
            } else {
                p.setIcon(new ImageIcon(Global.image));
                Global.flag = 0;
            }
        }
        else
        {
            JOptionPane.showMessageDialog(f,"Image Not Loaded..","Message",JOptionPane.PLAIN_MESSAGE);
        }
    }
});
mainPanel.add(buttonPane);

buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));

JButton GetBin = new JButton("Get Binary");
buttonPane.add(GetBin);
GetBin.addActionListener(new ActionListener() {
     @Override
     public void actionPerformed(ActionEvent arg0)
     {
         if( Global.image != null)
        {
            JFrame jf= new JFrame("Image in Binary");
            JTextArea comp = new JTextArea();
            JScrollPane sp=new JScrollPane(comp);
            comp.setBounds(20,20,200,50);
            //comp.setLineWrap(true);     //Gets Slow - For Horizontal
            jf.add(new JScrollPane(comp));
            jf.setSize(400,200);
            jf.setVisible(true);
            ImageIcon icon = (ImageIcon)p.getIcon();
            Image img = (Image) icon.getImage();
            BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
            Graphics2D bGr = bimage.createGraphics();
            bGr.drawImage(img, 0, 0, null);
            bGr.dispose();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] imageInByte=null;
            try {
                ImageIO.write( bimage, "jpg", baos );
                baos.flush();
                imageInByte = baos.toByteArray();
                baos.close();
                }
            catch (IOException e1) { e1.printStackTrace(); }
            StringBuilder sb = new StringBuilder(imageInByte.length * Byte.SIZE);
            for( int i = 0; i < Byte.SIZE * imageInByte.length; i++ )
            sb.append((imageInByte[i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? '0' : '1');
            comp.append(""+sb);
        }
        else
        {
            JOptionPane.showMessageDialog(f,"Image Not Loaded..","Message",JOptionPane.PLAIN_MESSAGE);
        }
    }
});

buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
JButton IBtn = new JButton("Insert Snap");
Global.imageinsertstatus =0;
buttonPane.add(IBtn);
  IBtn.addActionListener(new ActionListener() {
     @Override
     public void actionPerformed(ActionEvent arg0) {
        if( Global.image != null)
        {
            JFileChooser fc = new JFileChooser();
            BufferedImage image=null;
            Image dimg=null;
                fc.setCurrentDirectory(new File("."));
                int retVal = fc.showOpenDialog(null);
                if (retVal == 0)
                {
                    File file = fc.getSelectedFile();
                    try { image = ImageIO.read(file); dimg= image.getScaledInstance(600, 600,Image.SCALE_SMOOTH); Global.insertimage=image;}
                    catch (IOException e1) { e1.printStackTrace(); }
                    JOptionPane.showMessageDialog(f,"Please Select Position,  where to insert Image","Message",JOptionPane.PLAIN_MESSAGE);
                    Global.imageinsertstatus = 0;
                }
        }
        else
        {
            JOptionPane.showMessageDialog(f,"Image Not Loaded..","Message",JOptionPane.PLAIN_MESSAGE);
        }
       }
  });

mainPanel.add(buttonPane);

buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
JButton EBtn = new JButton("Exit");
buttonPane.add(EBtn);
EBtn.addActionListener(new ActionListener() {
     @Override
     public void actionPerformed(ActionEvent arg0) {
        System.exit(0);
       }
  });

buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
mainPanel.add(buttonPane);
mainPanel.add(Box.createRigidArea(new Dimension(0, 10)));
f.add(mainPanel);
f.pack();
}
}

 

Java program to display the record of a particular regno read from the keyboard.




Click Here to Know the Steps to Connect database in Linux Environment System


import java.io.*;
import java.sql.*;
class jdbc4
{
        public static void main(String args[])throws SQLException
        {
                int reg;
        String name,address;
                try
                {
                        DataInputStream in=new DataInputStream(System.in);
                        Class.forName("com.mysql.jdbc.Driver").newInstance();
                        Connection con=DriverManager.getConnection("jdbc:mysql://localhost/student","root","password");
                        Statement stm=con.createStatement();

                        String s2="select * from student;";
                        ResultSet rs1=stm.executeQuery(s2);
                        System.out.println("Reg_no    Name   Address");
                        System.out.println("---------------------------------");
                        while(rs1.next())
                        {
                                   reg=rs1.getInt("reg");
                                name=rs1.getString("name");
                                address=rs1.getString("address");
                                System.out.println(reg + "\t" + name + "\t" + address + "\t");
                        }

                       System.out.println("Enter the regno");
                        reg=Integer.parseInt(in.readLine());
                        System.out.println("Reg_no   Name    Address");
                        System.out.println("---------------------------------");

                        String s1="select * from student where reg=" + reg + ";";

                        ResultSet rs=stm.executeQuery(s1);
                        while(rs.next())
                        {
                                   reg=rs.getInt("reg");
                                name=rs.getString("name");
                                address=rs.getString("address");
                                System.out.println(reg + "\t" + name + "\t" + address + "\t");
                        }



                stm.close();
                con.close();
                }
                catch(Exception e)
                {
e.printStackTrace();
}
        }
}
Click Here to Know the Steps to Connect database in Linux Environment System


Java program to display all the records in a table.




Click Here to Know the Steps to Connect database in Linux Environment System


import java.io.*;
import java.sql.*;
class jdbc3
{
        public static void main(String args[])throws SQLException
        {
                int reg;
                String name,address;
                try
                {
                        DataInputStream in=new DataInputStream(System.in);
                        Class.forName("com.mysql.jdbc.Driver").newInstance();
                        Connection con=DriverManager.getConnection("jdbc:mysql://localhost/student","root","password");

                        Statement stm=con.createStatement();

                        System.out.println("Reg_no  Name    Address");
                        System.out.println("-------------------------------");

                        String s1="select * from student";
                        ResultSet rs=stm.executeQuery(s1);
                        while(rs.next())
                        {
                               reg=rs.getInt("reg");
                                name=rs.getString("name");
                                address=rs.getString("address");
                                System.out.println(reg + "\t" + name + "\t" + address + "\t");
                        }


                stm.close();
                con.close();
                }
                catch(Exception e)
                {
e.printStackTrace();
}
        }
}
Click Here to Know the Steps to Connect database in Linux Environment System

Java program to delete a record from the database. The regno of the record has to be deleted is read from the keyboard.




Click Here to Know the Steps to Connect database in Linux Environment System


import java.io.*;
import java.sql.*;
class jdbc2
{
        public static void main(String args[])throws SQLException
        {
                int reg;
        String name,address;
                try
                {
                        DataInputStream in=new DataInputStream(System.in);
                        Class.forName("com.mysql.jdbc.Driver").newInstance();
                        Connection con=DriverManager.getConnection("jdbc:mysql://localhost/student","root","password");
                        Statement stm=con.createStatement();

                        String s1="select * from student;";
                        ResultSet rs=stm.executeQuery(s1);
            while(rs.next())
                        {
                               reg=rs.getInt("reg");
                                name=rs.getString("name");
                                address=rs.getString("address");
                                System.out.println(reg + "\t" + name + "\t" + address + "\t");
                        }

                        System.out.println("Enter the register number");
                        reg=Integer.parseInt(in.readLine());

                        String s="Delete from student where reg="+reg+";";
                        stm.executeUpdate(s);
                        System.out.println("Record is deleted");

                        String s2="select * from student;";
                        ResultSet rs1=stm.executeQuery(s2);
                        while(rs1.next())
                        {
                               reg=rs1.getInt("reg");
                                name=rs1.getString("name");
                                address=rs1.getString("address");
                                System.out.println(reg + "\t" + name + "\t" + address + "\t");
                        }


                stm.close();
                con.close();
                }
                catch(Exception e)
                {
e.printStackTrace();

}
}
Click Here to Know the Steps to Connect database in Linux Environment System


Java program to read regno, name and address from the keyboard and insert into the database.





Click Here to Know the Steps to Connect database in Linux Environment System



import java.io.*;
import java.sql.*;
class jdbc1
{
public static void main(String args[]) throws SQLException
         {
                 int reg;
                 String name,address;
                try
                 {
                        DataInputStream in=new DataInputStream(System.in);
                        Class.forName("com.mysql.jdbc.Driver").newInstance();
                        Connection con=DriverManager.getConnection("jdbc:mysql://localhost/student","root","password");
                        System.out.println("Enter the register number");
                        reg=Integer.parseInt(in.readLine());
                         System.out.println("Enter the student name");
                        name=in.readLine();
                        System.out.println("Enter the address");
                        address=in.readLine();
                        Statement stm=con.createStatement();
                String s="insert into student values(" + reg + ",'" + name + "','" + address + "');";
                                stm.executeUpdate(s);
                                System.out.println("Record is inserted");
                         String s1="select * from student";
                         ResultSet rs=stm.executeQuery(s1);
                        while(rs.next())
                        {
                              reg=rs.getInt("reg");
                                name=rs.getString("name");
                                address=rs.getString("address");
                                System.out.println(reg + "\t" + name + "\t" + address + "\t");
                        }

                stm.close();
                con.close();
                }
                catch(Exception e)
                {
e.printStackTrace();
}
        }
}



Click Here to Know the Steps to Connect database in Linux Environment System



JAVA Swing Program to implement desktop calculator.




import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * In this applet, the user can type in two real numbers.  The
 * user can click on buttons labeled +, - , *, and / to perform
 * basic arithmetic operations on the numbers.  When the user
 * clicks on a button the answer is displayed.  The applet
 * should be about 300 by 160 pixels.
 * Note that this class also contains a main() routine, so that
 * it can be run as a stand-alone application.  When it is run
 * in this way, it opens a window that shows that same panel that
 * is used in the applet version.
 */
public class SimpleCalc extends JApplet {
  
   /**
    * This main() routine makes it possible to run the SimpleCalc1 class
    * as a stand-alone application.  This routine just opens a window that
    * uses an object of type CalcPanel as its content pane, where CalcPanel
    * is the nested class defined below.
    */
   public static void main(String[] args) {
      JFrame window = new JFrame("Simple Calculator");
      CalcPanel content = new CalcPanel();
      window.setContentPane(content);
      window.pack();  // Sizes window to preferred size of contents.
      window.setLocation(100,100);
      window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
      window.setVisible(true);
   }
  
  
   /**
    * The init() method for the applet just sets the content pane
    * of the applet to be an object of type CalcPanel, where CalcPanel
    * is the nested class defined below.
    */
   public void init() {
      setContentPane( new CalcPanel() );
   }
  
  
   public static class CalcPanel extends JPanel implements ActionListener {
     
      private JTextField xInput, yInput;  // Input boxes for the numbers.
     
        private JLabel answer;  // JLabel for displaying the answer, or an
                              //    error message if appropriate.
     
     
      public CalcPanel() {
                 
         /* Assign a background color to the panel and its
          content panel.  This color will show through in the gaps
          between components. */
        
         setBackground(Color.GRAY);
        
         /* Add an empty border around the panel, which will also
          * appear in the gray background color. */
        
         setBorder( BorderFactory.createEmptyBorder(5,5,5,5) );
        
         /* Create the input boxes, and make sure that the background
          color is white.  (They are likely to be white by default.) */
        
         xInput = new JTextField("0", 10);
         xInput.setBackground(Color.WHITE);
         yInput = new JTextField("0", 10);
         yInput.setBackground(Color.WHITE);
        
         /* Create panels to hold the input boxes and labels "x =" and
          "y = ".  These panels use the default FlowLayout layout manager. */
        
         JPanel xPanel = new JPanel();
         xPanel.add( new JLabel(" x = "));
         xPanel.add(xInput);
        
         JPanel yPanel = new JPanel();
         yPanel.add( new JLabel(" y = "));
         yPanel.add(yInput);
        
         /* Create a panel to hold the four buttons for the four
          operations.  A GridLayout is used so that the buttons
          will all have the same size and will fill the panel.
          The main panel servers as ActionListener for the buttons. */
        
         JPanel buttonPanel = new JPanel();
         buttonPanel.setLayout(new GridLayout(1,4));
        
         JButton plus = new JButton("+");
         plus.addActionListener(this);
         buttonPanel.add(plus);
        
         JButton minus = new JButton("-");
         minus.addActionListener(this);
         buttonPanel.add(minus);
        
         JButton times = new JButton("*");
         times.addActionListener(this);
         buttonPanel.add(times);
        
         JButton divide = new JButton("/");
         divide.addActionListener(this);
         buttonPanel.add(divide);
        
         /* Create the label for displaying the answer in red
          on a white background.  The label is set to be
          "opaque" to make sure that the white background
          is painted. */
        
         answer = new JLabel("x + y = 0", JLabel.CENTER);
         answer.setForeground(Color.red);
         answer.setBackground(Color.white);
         answer.setOpaque(true);
        
         /* Set up the layout for the main panel, using a GridLayout,
          and add all the components that have been created. */
        
         setLayout(new GridLayout(4,1,3,3));
         add(xPanel);
         add(yPanel);
         add(buttonPanel);
         add(answer);
        
         /* Try to give the input focus to xInput, which is the natural
          place for the user to start. */
        
         xInput.requestFocus();
        
      }  // end constructor
     
           
      /**
       * When the user clicks a button, get the numbers from the input boxes
       * and perform the operation indicated by the button.  Put the result in
       * the answer label.  If an error occurs, an error message is put in the label.
       */
      public void actionPerformed(ActionEvent evt) {
        
         double x, y;  // The numbers from the input boxes.
        
         /* Get a number from the xInput JTextField.  Use
          xInput.getText() to get its contents as a String.
          Convert this String to a double.  The try...catch
          statement will check for errors in the String.  If
          the string is not a legal number, the error message
          "Illegal data for x." is put into the answer and
          the actionPerformed() method ends. */
        
         try {
            String xStr = xInput.getText();
            x = Double.parseDouble(xStr);
         }
         catch (NumberFormatException e) {
            // The string xStr is not a legal number.
            answer.setText("Illegal data for x.");
            xInput.requestFocus();
            return;
         }
        
         /* Get a number from yInput in the same way. */
        
         try {
            String yStr = yInput.getText();
            y = Double.parseDouble(yStr);
         }
         catch (NumberFormatException e) {
            answer.setText("Illegal data for y.");
            yInput.requestFocus();
            return;
         }
        
         /* Perform the operation based on the action command
          from the button.  Note that division by zero produces
          an error message. */
        
         String op = evt.getActionCommand();
         if (op.equals("+"))
            answer.setText( "x + y = " + (x+y) );
         else if (op.equals("-"))
            answer.setText( "x - y = " + (x-y) );
         else if (op.equals("*"))
            answer.setText( "x * y = " + (x*y) );
         else if (op.equals("/")) {
            if (y == 0)
               answer.setText("Can't divide by zero!");
            else
               answer.setText( "x / y = " + (x/y) );
         }
        
      } // end actionPerformed()
     
   } // end nested class CalcPanel
  

}  // end class SimpleCalculator


HTML code to load Applet.
Make Sure that JAVA configured Properly.

<html>
<body>
<applet code=SimpleCalc.class width=300 height=200>
</applet>
</body>
</html>

Name

Email *

Message *

Whoom We Are

Need to Enter Information

What We Do

Need to Enter Information