Threshold Image Java Code

Here is the code, that I wrote to threshold the image at required level. Thresholding image is very easy. At first you have to grab pixel of each red, green and blue and then sum then together then find the average. Check that against some threshold. That is all.

So, talking politely. These are the basic pseudocode.

1. Start set THRESHOLD = 30
red = getRedPixelFromImage(row,column)

green = getGreenPixelFromImage(row,column)

blue = getBluePixelFromImage(row,column)

2. avg = (red+green+blue)/3

3. if(avg<THRESHOLD)

paint white

else

paint black.

4. end

I have used the above psuedocode. It works for me and have tested the result with the threshold of Adobe Photoshop and found its working great.

Below is the main code for Image Thresholding.

public static BufferedImage Threshold(BufferedImage img,int requiredThresholdValue) {
		int height = img.getHeight();
		int width = img.getWidth();
		BufferedImage finalThresholdImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB) ;
		
		int red = 0;
		int green = 0;
		int blue = 0;
		
		for (int x = 0; x < width; x++) {
			try {

				for (int y = 0; y < height; y++) {
					int color = img.getRGB(x, y);

					red = ImageOperations.getRed(color);
					green = ImageOperations.getGreen(color);
					blue = ImageOperations.getBlue(color);

					if((red+green+green)/3 < (int) (requiredThresholdValue)) {
							finalThresholdImage.setRGB(x,y,ImageOperations.mixColor(0, 0,0));
						}
						else {
							finalThresholdImage.setRGB(x,y,ImageOperations.mixColor(255, 255,255));
						}
					
				}
			} catch (Exception e) {
				 e.getMessage();
			}
		}
		
		return finalThresholdImage;
	}

red = ImageOperations.getRed(color);
green = ImageOperations.getGreen(color);
blue = ImageOperations.getBlue(color);

These are the line that gets the red, green and blue pixels. ImageOperations is the name of class and getRed(color) is the method inside that class. Actually these are the classes that I have been using in my project. I thought it might be handy for you and have published it here.

You can find the full source code below. Save it as ImageOperations.java

/** Filename : ImageOperations.java **/
/**
 * 
 */
//package mts;

import java.awt.image.BufferedImage;

/**
 * @author Asee Shrestha
 *
 */

/** 
 * Thresholds the image at the given ThresholdValue 
 * @params requiredThresholdValue The threshold value by which the image is to be threshold
 */
public class ImageOperations {
	
	public static BufferedImage Threshold(BufferedImage img,int requiredThresholdValue) {
		
		int height = img.getHeight();
		int width = img.getWidth();
		BufferedImage finalThresholdImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB) ;
		
		int red = 0;
		int green = 0;
		int blue = 0;
		
		for (int x = 0; x < width; x++) {
//			System.out.println("Row: " + x);
			try {

				for (int y = 0; y < height; y++) {
					int color = img.getRGB(x, y);
					
					red = ImageOperations.getRed(color);
					green = ImageOperations.getGreen(color);
					blue = ImageOperations.getBlue(color);
				
//					System.out.println("Threshold : " + requiredThresholdValue);
						if((red+green+green)/3 < (int) (requiredThresholdValue)) {
							finalThresholdImage.setRGB(x,y,ImageOperations.mixColor(0, 0,0));
						}
						else {
							finalThresholdImage.setRGB(x,y,ImageOperations.mixColor(255, 255,255));
						}
					
				}
			} catch (Exception e) {
				 e.getMessage();
			}
		}
		
		return finalThresholdImage;
	}

	private static int mixColor(int red, int green, int blue) {
		return red<<16|green<<8|blue;
	}

	public static int getRed(int color) {
		return (color & 0x00ff0000)  >> 16;
	}
	
	public static int getGreen(int color) {
		return	(color & 0x0000ff00)  >> 8;
	}
	
	public static int getBlue(int color) {
		return (color & 0x000000ff)  >> 0;
		
	}

}

Save the code provided below as DrawToPanel.java

/** Filename : DrawToPanel.java **/
//package mts;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;


/**
 * @author Asee Shrestha
 * 
 */
public class DrawToPanel {
	static final double SCALE_FACTOR = .8;	// In percentage
	static final double DIVISION_FACTOR = .8; 	//In percentage
	static final int WINDOW_WIDTH = 640;		
	static final int WINDOW_HEIGHT = 480;
	static int THRESHOLD = 80;		
	static double pThreshold = 0; 
	BufferedImage bi=null;
	BufferedImage si = null;

	/** Change this path to the image location on your harddisk **/
	String imagePath = "F:\\just";   /** image name are just1.jpg, just2.jpg so adjust them accordingly, 1.jpg and 2.jpg are appended by the program itself beause I coded them so.**/
	int red, green, blue, alpha, gray;

	DrawToPanel(String title) {

		Dimension size = new Dimension((int) (WINDOW_WIDTH * DIVISION_FACTOR),
				(int) (WINDOW_HEIGHT * DIVISION_FACTOR));

		JFrame window = new JFrame();
		window.setTitle(title);

		JLabel lblDrawingPanel = new JLabel("Drawing Panel");
		DrawPanel drawingPanel = new DrawPanel();
		drawingPanel.add(lblDrawingPanel,BorderLayout.EAST);
		
		
		JLabel lblRef = new JLabel("Reference Panel ");
		ReferencePanel referencePanel = new ReferencePanel();

		JPanel buttons = new JPanel();
		buttons.setLayout(new FlowLayout(FlowLayout.LEFT));
		drawingPanel.setPreferredSize(size);

		referencePanel.setPreferredSize(size);
		referencePanel.add(lblRef,BorderLayout.WEST);

		JButton btnOk = new JButton(" OK ");
		JButton btnCancel = new JButton(" Cancel ");

		window.add(drawingPanel, BorderLayout.EAST);
		window.add(referencePanel, BorderLayout.WEST);

		buttons.add(btnOk);
		buttons.add(btnCancel);

		window.add(buttons, BorderLayout.SOUTH);

		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		window.pack();
		window.setVisible(true);

	}

	class DrawPanel extends JPanel {
		/** This paint method actually puts the image inside JPanel **/
		public void paint(Graphics g) {

			Graphics2D g2d = (Graphics2D) g;
			try {
				 bi = ImageIO.read(new File(imagePath + "1.jpg"));
				 si = ImageIO.read(new File(imagePath + "2.jpg"));
				 
				BufferedImage imageToThreshold =  ImageOperations.Threshold(si, THRESHOLD);
				
				 g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
				 g2d.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
				 g2d.drawImage(imageToThreshold, 10, 10, (int) (WINDOW_WIDTH * SCALE_FACTOR),(int) (WINDOW_HEIGHT * SCALE_FACTOR), Color.WHITE, null);

			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
		}
	}
	
	/**
	 * JPanel to displays the Reference Image.
	 * @author Asee Shrestha
	 *
	 */

	class ReferencePanel extends JPanel {
		public void paint(Graphics g) {
			Graphics2D g2d = (Graphics2D) g;
			try {
				 bi = ImageIO.read(new File(imagePath + "1.jpg"));
				g2d.drawImage(bi, 10, 10, (int) (WINDOW_WIDTH * SCALE_FACTOR),
						(int) (WINDOW_HEIGHT * SCALE_FACTOR), Color.RED, null);
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}
		}
	}
}

Source code for test. Save it as Test.java

/**
 * Filename : Test.java
 */
//package mts;

import java.awt.Dimension;

import javax.swing.JFrame;

/**
 * @author Asee Shrestha
 *
 */
public class Test {

	public static void main(String[] args) {
		DrawToPanel d = new DrawToPanel("Sample Window");
		
		
	}

}

Do not use above codes for commercial use, you can use them for educational purpose only. Since these are not the optimized code, they may crash your system, so i don't recommend them using for production phase. I will not be responsible in any kind for damaged caused by using above code to your system.

Leave a Reply

Your email address will not be published. Required fields are marked *