2012-07-17 23:19:54 jia20003 阅读数 6015

图像处理之应用篇-大米计数续

背景介绍:

请看博客文章《图像处理之简单综合实例(大米计数)

其实拍出来的照片更多的是含有大米颗粒相互接触,甚至于有点重叠的照片

要准确计算大米的颗粒数非常困难,通过图像形态学开闭操作,腐蚀等手

段尝试以后效果不是很好。最终发现一种简单明了但是有微小误差的计数

方法。照相机图片:


算法思想:

主要是利用连通区域发现算法,发现所有连通区域,使用二分法,截取较小

部分的连通区域集合,求取平均连通区域面积,根据此平均连通区域面积,

作为单个大米大小,从而求取出粘连部分的大米颗粒数,完成对整个大米

数目的统计:

缺点:

平均连通区域面积的计算受制于两个因素,一个是最小连通区域集合的选取算法,

二个样本数量。算法结果跟实际结果有一定的误差,但是误差在1%左右。

 

程序算法代码详解

将输入图像转换为黑白二值图像,求得连通区域的算法代码如下:

src = super.filter(src, null);

getRGB(src, 0, 0, width,height, inPixels );

FastConnectedComponentLabelAlgfccAlg = new FastConnectedComponentLabelAlg();

fccAlg.setBgColor(0);

int[] outData = fccAlg.doLabel(inPixels, width, height);

 

获取平均大米颗粒连通区域的代码如下:

Integer[] values =labelMap.values().toArray(new Integer[0]);

Arrays.sort(values);

int minRiceNum = values.length/4;

float sum = 0;

for(int v= offset; v<minRiceNum + offset; v++) {

sum += values[v].intValue();

}

float minMeans = sum / (float)minRiceNum;

System.out.println(" minMeans = " + minMeans);

 

程序时序图如下:


程序运行效果如下:


实际大米颗粒数目为202,正确率为99%

完成大米数目统计的源代码如下(其它相关代码见以前的图像处理系列文章):

public class FindRiceFilter extends BinaryFilter {
	
	private int sumRice;
	private int offset = 10;
	
	public int getSumRice() {
		return this.sumRice;
	}
	
	public void setOffset(int pos) {
		this.offset = pos;
	}

	@Override
	public BufferedImage filter(BufferedImage src, BufferedImage dest) {
		int width = src.getWidth();
        int height = src.getHeight();
        if ( dest == null )
            dest = createCompatibleDestImage( src, null );

        int[] inPixels = new int[width*height];
        int[] outPixels = new int[width*height];
        src = super.filter(src, null);
        getRGB(src, 0, 0, width, height, inPixels );
        FastConnectedComponentLabelAlg fccAlg = new FastConnectedComponentLabelAlg();
		fccAlg.setBgColor(0);
		int[] outData = fccAlg.doLabel(inPixels, width, height);
		
		// labels statistic
		HashMap<Integer, Integer> labelMap = new HashMap<Integer, Integer>();
		for(int d=0; d<outData.length; d++) {
			if(outData[d] != 0) {
				if(labelMap.containsKey(outData[d])) {
					Integer count = labelMap.get(outData[d]);
					count+=1;
					labelMap.put(outData[d], count);
				} else {
					labelMap.put(outData[d], 1);
				}
			}
		}
		
		Integer[] values = labelMap.values().toArray(new Integer[0]);
		Arrays.sort(values);
		int minRiceNum = values.length/4;
		float sum = 0;
		for(int v= offset; v<minRiceNum + offset; v++) {
			sum += values[v].intValue();
		}
		float minMeans = sum / (float)minRiceNum;
		System.out.println(" minMeans = " + minMeans);
		
		// try to find the max connected component
		Integer[] keys = labelMap.keySet().toArray(new Integer[0]);
		Arrays.sort(keys);
		int threshold = 10;
		ArrayList<Integer> listKeys = new ArrayList<Integer>();
		for(Integer key : keys) {
			if(labelMap.get(key) <=threshold){
				listKeys.add(key);
			} else {
				float xx = labelMap.get(key);
				float intPart = (float)Math.floor(xx / minMeans + 0.5f);
				sumRice += intPart;
			}
		}
		System.out.println( "Number of rice  = " + sumRice);
		// sumRice = keys.length - listKeys.size();
		
        // calculate means of pixel  
        int index = 0;    
        for(int row=0; row<height; row++) {  
            int ta = 0, tr = 0, tg = 0, tb = 0;  
            for(int col=0; col<width; col++) {  
                index = row * width + col;  
                ta = (inPixels[index] >> 24) & 0xff;  
                tr = (inPixels[index] >> 16) & 0xff;  
                tg = (inPixels[index] >> 8) & 0xff;  
                tb = inPixels[index] & 0xff;
                if(outData[index] != 0 && validRice(outData[index], listKeys)) {
                	tr = tg = tb = 255;
                } else {
                	tr = tg = tb = 0;
                }
                outPixels[index] = (ta << 24) | (tr << 16) | (tg << 8) | tb;
            }
        }
        setRGB( dest, 0, 0, width, height, outPixels );
        return dest;
	}

	private boolean validRice(int i, ArrayList<Integer> listKeys) {
		for(Integer key : listKeys) {
			if(key == i) {
				return false;
			}
		}
		return true;
	}

}
转载文章请务必注明出处

2012-05-26 23:13:36 jia20003 阅读数 9686

图像处理之简单综合实例(大米计数)

一位网友给我发了几张灰度图像,说是他们单位的工业相机拍摄的,画质非常的清楚,他们

单位是农业科研单位,特别想知道种子的数量,他想知道的是每次工业相机拍摄种子图片中

有多少颗粒种子,想到了用图像处理的办法解决他们的问题,看了他给我照片,以大米种子

为例。实现了一个简单的算法流程,可以得到种子的数目。

大致算法分为以下三个步骤:

1.      将灰度图像二值化,二值化方法可以参考以前的文章,求取像素平均值,灰度直方图都

          可以

2.      去掉二值化以后的图像中干扰噪声。

3.      得到种子数目,用彩色标记出来。


源图像如下:


程序处理中间结果及最终效果如下:


二值化处理参见以前的文章 - http://blog.csdn.net/jia20003/article/details/7392325

大米计数与噪声块消去算法基于连通组件标记算法,源代码如下:

package com.gloomyfish.rice.analysis;

import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

import com.gloomyfish.face.detection.AbstractBufferedImageOp;
import com.gloomyfish.face.detection.FastConnectedComponentLabelAlg;

public class FindRiceFilter extends AbstractBufferedImageOp {
	
	private int sumRice;
	
	public int getSumRice() {
		return this.sumRice;
	}

	@Override
	public BufferedImage filter(BufferedImage src, BufferedImage dest) {
		int width = src.getWidth();
        int height = src.getHeight();

        if ( dest == null )
            dest = createCompatibleDestImage( src, null );

        int[] inPixels = new int[width*height];
        int[] outPixels = new int[width*height];
        getRGB(src, 0, 0, width, height, inPixels );
        
		FastConnectedComponentLabelAlg fccAlg = new FastConnectedComponentLabelAlg();
		fccAlg.setBgColor(0);
		int[] outData = fccAlg.doLabel(inPixels, width, height);
		// labels statistic
		HashMap<Integer, Integer> labelMap = new HashMap<Integer, Integer>();
		for(int d=0; d<outData.length; d++) {
			if(outData[d] != 0) {
				if(labelMap.containsKey(outData[d])) {
					Integer count = labelMap.get(outData[d]);
					count+=1;
					labelMap.put(outData[d], count);
				} else {
					labelMap.put(outData[d], 1);
				}
			}
		}
		
		// try to find the max connected component
		Integer[] keys = labelMap.keySet().toArray(new Integer[0]);
		Arrays.sort(keys);
		int threshold = 10;
		ArrayList<Integer> listKeys = new ArrayList<Integer>();
		for(Integer key : keys) {
			if(labelMap.get(key) <=threshold){
				listKeys.add(key);
			}
			System.out.println( "Number of " + key + " = " + labelMap.get(key));
		}
		sumRice = keys.length - listKeys.size();
		
        // calculate means of pixel  
        int index = 0;    
        for(int row=0; row<height; row++) {  
            int ta = 0, tr = 0, tg = 0, tb = 0;  
            for(int col=0; col<width; col++) {  
                index = row * width + col;  
                ta = (inPixels[index] >> 24) & 0xff;  
                tr = (inPixels[index] >> 16) & 0xff;  
                tg = (inPixels[index] >> 8) & 0xff;  
                tb = inPixels[index] & 0xff;
                if(outData[index] != 0 && validRice(outData[index], listKeys)) {
                	tr = tg = tb = 255;
                } else {
                	tr = tg = tb = 0;
                }
                outPixels[index] = (ta << 24) | (tr << 16) | (tg << 8) | tb;
            }
        }
        setRGB( dest, 0, 0, width, height, outPixels );
        return dest;
	}

	private boolean validRice(int i, ArrayList<Integer> listKeys) {
		for(Integer key : listKeys) {
			if(key == i) {
				return false;
			}
		}
		return true;
	}

}
大米着色处理很简单,只是简单RGB固定着色,源码如下:

package com.gloomyfish.rice.analysis;

import java.awt.image.BufferedImage;

import com.gloomyfish.face.detection.AbstractBufferedImageOp;

public class ColorfulRiceFilter extends AbstractBufferedImageOp {

	@Override
	public BufferedImage filter(BufferedImage src, BufferedImage dest) {
		int width = src.getWidth();
        int height = src.getHeight();

        if ( dest == null )
            dest = createCompatibleDestImage( src, null );

        int[] inPixels = new int[width*height];
        int[] outPixels = new int[width*height];
        getRGB(src, 0, 0, width, height, inPixels );
        
        int index = 0, srcrgb;
        for(int row=0; row<height; row++) {  
            int ta = 255, tr = 0, tg = 0, tb = 0;  
            for(int col=0; col<width; col++) { 
                index = row * width + col;  
//                ta = (inPixels[index] >> 24) & 0xff;  
//                tr = (inPixels[index] >> 16) & 0xff;  
//                tg = (inPixels[index] >> 8) & 0xff;  
//                tb = inPixels[index] & 0xff;  
            	srcrgb = inPixels[index] & 0x000000ff;
            	if(srcrgb > 0 && row < 140) {
            		tr = 0;
            		tg = 255;
            		tb = 0;
            	} else if(srcrgb > 0 && row >= 140 && row <=280) {
            		tr = 0;
            		tg = 0;
            		tb = 255;
            	} else if(srcrgb > 0 && row >=280) {
            		tr = 255;
            		tg = 0;
            		tb = 0;
            	}
            	else {
            		tr = tg = tb = 0;
            	}
            	outPixels[index] = (ta << 24) | (tr << 16) | (tg << 8) | tb;
            }
        }
        setRGB( dest, 0, 0, width, height, outPixels );
        return dest;
	}
}
测试程序UI代码如下:

package com.gloomyfish.rice.analysis;

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.Image;
import java.awt.MediaTracker;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MainFrame extends JComponent implements ActionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1518574788794973574L;
	public final static String BROWSE_CMD = "Browse...";
	public final static String NOISE_CMD = "Remove Noise";
	public final static String FUN_CMD = "Colorful Rice";
	
	private BufferedImage rawImg;
	private BufferedImage resultImage;
	private MediaTracker tracker;
	private Dimension mySize;
	
	// JButtons
	private JButton browseBtn;
	private JButton noiseBtn;
	private JButton colorfulBtn;

	// rice number....
	private int riceNum = -1;
	
	
	public MainFrame() {
		JPanel btnPanel = new JPanel();
		btnPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		browseBtn = new JButton("Browse...");
		noiseBtn = new JButton("Remove Noise");
		colorfulBtn = new JButton("Colorful Rice");
		
		browseBtn.setToolTipText("Please select image file...");
		noiseBtn.setToolTipText("find connected region and draw red rectangle");
		colorfulBtn.setToolTipText("Remove the minor noise region pixels...");
		
		// buttons
		btnPanel.add(browseBtn);
		btnPanel.add(noiseBtn);
		btnPanel.add(colorfulBtn);
		
		// setup listener...
		browseBtn.addActionListener(this);
		noiseBtn.addActionListener(this);
		colorfulBtn.addActionListener(this);
		
		browseBtn.setEnabled(true);
		noiseBtn.setEnabled(true);
		colorfulBtn.setEnabled(true);
		
//		minX = minY =  10000;
//		maxX = maxY = -1;
		
		mySize = new Dimension(500, 300);
		JFrame demoUI = new JFrame("Rice Detection Demo");
		demoUI.getContentPane().setLayout(new BorderLayout());
		demoUI.getContentPane().add(this, BorderLayout.CENTER);
		demoUI.getContentPane().add(btnPanel, BorderLayout.SOUTH);
		demoUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		demoUI.pack();
		demoUI.setVisible(true);
	}
	
	public void paint(Graphics g) {
		Graphics2D g2 = (Graphics2D) g;
		if(rawImg != null) {
			Image scaledImage = rawImg.getScaledInstance(200, 200, Image.SCALE_FAST);
			g2.drawImage(scaledImage, 0, 0, 200, 200, null);
		}
		if(resultImage != null) {
			Image scaledImage = resultImage.getScaledInstance(200, 200, Image.SCALE_FAST);
			g2.drawImage(scaledImage, 210, 0, 200, 200, null);
		}
		
		g2.setPaint(Color.RED);
		if(riceNum > 0) {
			g2.drawString("Number of Rice : " + riceNum, 100, 300);
		} else {
			g2.drawString("Number of Rice : Unknown", 100, 300);
		}
	}
	public Dimension getPreferredSize() {
		return mySize;
	}
	
	public Dimension getMinimumSize() {
		return mySize;
	}
	
	public Dimension getMaximumSize() {
		return mySize;
	}
	
	public static void main(String[] args) {
		new MainFrame();
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if(BROWSE_CMD.equals(e.getActionCommand())) {
			JFileChooser chooser = new JFileChooser();
			chooser.showOpenDialog(null);
			File f = chooser.getSelectedFile();
			BufferedImage bImage = null;
			if(f == null) return;
			try {
				bImage = ImageIO.read(f);
				
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			
			tracker = new MediaTracker(this);
			tracker.addImage(bImage, 1);
			
			// blocked 10 seconds to load the image data
			try {
				if (!tracker.waitForID(1, 10000)) {
					System.out.println("Load error.");
					System.exit(1);
				}// end if
			} catch (InterruptedException ine) {
				ine.printStackTrace();
				System.exit(1);
			} // end catch
			BinaryFilter bfilter = new BinaryFilter();
			rawImg = bfilter.filter(bImage, null);
			repaint();
		} else if(NOISE_CMD.equals(e.getActionCommand())) {
			FindRiceFilter frFilter = new FindRiceFilter();
			resultImage = frFilter.filter(rawImg, null);
			riceNum = frFilter.getSumRice();
			repaint();
		} else if(FUN_CMD.equals(e.getActionCommand())) {
			ColorfulRiceFilter cFilter = new ColorfulRiceFilter();
			resultImage = cFilter.filter(resultImage, null);
			repaint();
		} else {
			// do nothing...
		}
		
	}
}
关于连通组件标记算法,我实现一个优化过的快速版本,可以参见

http://blog.csdn.net/jia20003/article/details/7596443



2015-07-24 10:12:15 mao0514 阅读数 2528

一位网友给我发了几张灰度图像,说是他们单位的工业相机拍摄的,画质非常的清楚,他们

单位是农业科研单位,特别想知道种子的数量,他想知道的是每次工业相机拍摄种子图片中

有多少颗粒种子,想到了用图像处理的办法解决他们的问题,看了他给我照片,以大米种子

为例。实现了一个简单的算法流程,可以得到种子的数目。

大致算法分为以下三个步骤:

1.      将灰度图像二值化,二值化方法可以参考以前的文章,求取像素平均值,灰度直方图都

          可以

2.      去掉二值化以后的图像中干扰噪声。

3.      得到种子数目,用彩色标记出来。


源图像如下:


程序处理中间结果及最终效果如下:


二值化处理参见以前的文章 - http://blog.csdn.net/jia20003/article/details/7392325

大米计数与噪声块消去算法基于连通组件标记算法,源代码如下:

  1. package com.gloomyfish.rice.analysis;  
  2.   
  3. import java.awt.image.BufferedImage;  
  4. import java.util.ArrayList;  
  5. import java.util.Arrays;  
  6. import java.util.HashMap;  
  7.   
  8. import com.gloomyfish.face.detection.AbstractBufferedImageOp;  
  9. import com.gloomyfish.face.detection.FastConnectedComponentLabelAlg;  
  10.   
  11. public class FindRiceFilter extends AbstractBufferedImageOp {  
  12.       
  13.     private int sumRice;  
  14.       
  15.     public int getSumRice() {  
  16.         return this.sumRice;  
  17.     }  
  18.   
  19.     @Override  
  20.     public BufferedImage filter(BufferedImage src, BufferedImage dest) {  
  21.         int width = src.getWidth();  
  22.         int height = src.getHeight();  
  23.   
  24.         if ( dest == null )  
  25.             dest = createCompatibleDestImage( src, null );  
  26.   
  27.         int[] inPixels = new int[width*height];  
  28.         int[] outPixels = new int[width*height];  
  29.         getRGB(src, 00, width, height, inPixels );  
  30.           
  31.         FastConnectedComponentLabelAlg fccAlg = new FastConnectedComponentLabelAlg();  
  32.         fccAlg.setBgColor(0);  
  33.         int[] outData = fccAlg.doLabel(inPixels, width, height);  
  34.         // labels statistic  
  35.         HashMap<Integer, Integer> labelMap = new HashMap<Integer, Integer>();  
  36.         for(int d=0; d<outData.length; d++) {  
  37.             if(outData[d] != 0) {  
  38.                 if(labelMap.containsKey(outData[d])) {  
  39.                     Integer count = labelMap.get(outData[d]);  
  40.                     count+=1;  
  41.                     labelMap.put(outData[d], count);  
  42.                 } else {  
  43.                     labelMap.put(outData[d], 1);  
  44.                 }  
  45.             }  
  46.         }  
  47.           
  48.         // try to find the max connected component  
  49.         Integer[] keys = labelMap.keySet().toArray(new Integer[0]);  
  50.         Arrays.sort(keys);  
  51.         int threshold = 10;  
  52.         ArrayList<Integer> listKeys = new ArrayList<Integer>();  
  53.         for(Integer key : keys) {  
  54.             if(labelMap.get(key) <=threshold){  
  55.                 listKeys.add(key);  
  56.             }  
  57.             System.out.println( "Number of " + key + " = " + labelMap.get(key));  
  58.         }  
  59.         sumRice = keys.length - listKeys.size();  
  60.           
  61.         // calculate means of pixel    
  62.         int index = 0;      
  63.         for(int row=0; row<height; row++) {    
  64.             int ta = 0, tr = 0, tg = 0, tb = 0;    
  65.             for(int col=0; col<width; col++) {    
  66.                 index = row * width + col;    
  67.                 ta = (inPixels[index] >> 24) & 0xff;    
  68.                 tr = (inPixels[index] >> 16) & 0xff;    
  69.                 tg = (inPixels[index] >> 8) & 0xff;    
  70.                 tb = inPixels[index] & 0xff;  
  71.                 if(outData[index] != 0 && validRice(outData[index], listKeys)) {  
  72.                     tr = tg = tb = 255;  
  73.                 } else {  
  74.                     tr = tg = tb = 0;  
  75.                 }  
  76.                 outPixels[index] = (ta << 24) | (tr << 16) | (tg << 8) | tb;  
  77.             }  
  78.         }  
  79.         setRGB( dest, 00, width, height, outPixels );  
  80.         return dest;  
  81.     }  
  82.   
  83.     private boolean validRice(int i, ArrayList<Integer> listKeys) {  
  84.         for(Integer key : listKeys) {  
  85.             if(key == i) {  
  86.                 return false;  
  87.             }  
  88.         }  
  89.         return true;  
  90.     }  
  91.   
  92. }  
大米着色处理很简单,只是简单RGB固定着色,源码如下:

  1. package com.gloomyfish.rice.analysis;  
  2.   
  3. import java.awt.image.BufferedImage;  
  4.   
  5. import com.gloomyfish.face.detection.AbstractBufferedImageOp;  
  6.   
  7. public class ColorfulRiceFilter extends AbstractBufferedImageOp {  
  8.   
  9.     @Override  
  10.     public BufferedImage filter(BufferedImage src, BufferedImage dest) {  
  11.         int width = src.getWidth();  
  12.         int height = src.getHeight();  
  13.   
  14.         if ( dest == null )  
  15.             dest = createCompatibleDestImage( src, null );  
  16.   
  17.         int[] inPixels = new int[width*height];  
  18.         int[] outPixels = new int[width*height];  
  19.         getRGB(src, 00, width, height, inPixels );  
  20.           
  21.         int index = 0, srcrgb;  
  22.         for(int row=0; row<height; row++) {    
  23.             int ta = 255, tr = 0, tg = 0, tb = 0;    
  24.             for(int col=0; col<width; col++) {   
  25.                 index = row * width + col;    
  26. //                ta = (inPixels[index] >> 24) & 0xff;    
  27. //                tr = (inPixels[index] >> 16) & 0xff;    
  28. //                tg = (inPixels[index] >> 8) & 0xff;    
  29. //                tb = inPixels[index] & 0xff;    
  30.                 srcrgb = inPixels[index] & 0x000000ff;  
  31.                 if(srcrgb > 0 && row < 140) {  
  32.                     tr = 0;  
  33.                     tg = 255;  
  34.                     tb = 0;  
  35.                 } else if(srcrgb > 0 && row >= 140 && row <=280) {  
  36.                     tr = 0;  
  37.                     tg = 0;  
  38.                     tb = 255;  
  39.                 } else if(srcrgb > 0 && row >=280) {  
  40.                     tr = 255;  
  41.                     tg = 0;  
  42.                     tb = 0;  
  43.                 }  
  44.                 else {  
  45.                     tr = tg = tb = 0;  
  46.                 }  
  47.                 outPixels[index] = (ta << 24) | (tr << 16) | (tg << 8) | tb;  
  48.             }  
  49.         }  
  50.         setRGB( dest, 00, width, height, outPixels );  
  51.         return dest;  
  52.     }  
  53. }  
测试程序UI代码如下:

  1. package com.gloomyfish.rice.analysis;  
  2.   
  3. import java.awt.BorderLayout;  
  4. import java.awt.Color;  
  5. import java.awt.Dimension;  
  6. import java.awt.FlowLayout;  
  7. import java.awt.Graphics;  
  8. import java.awt.Graphics2D;  
  9. import java.awt.Image;  
  10. import java.awt.MediaTracker;  
  11. import java.awt.event.ActionEvent;  
  12. import java.awt.event.ActionListener;  
  13. import java.awt.image.BufferedImage;  
  14. import java.io.File;  
  15. import java.io.IOException;  
  16.   
  17. import javax.imageio.ImageIO;  
  18. import javax.swing.JButton;  
  19. import javax.swing.JComponent;  
  20. import javax.swing.JFileChooser;  
  21. import javax.swing.JFrame;  
  22. import javax.swing.JPanel;  
  23.   
  24. public class MainFrame extends JComponent implements ActionListener {  
  25.     /** 
  26.      *  
  27.      */  
  28.     private static final long serialVersionUID = 1518574788794973574L;  
  29.     public final static String BROWSE_CMD = "Browse...";  
  30.     public final static String NOISE_CMD = "Remove Noise";  
  31.     public final static String FUN_CMD = "Colorful Rice";  
  32.       
  33.     private BufferedImage rawImg;  
  34.     private BufferedImage resultImage;  
  35.     private MediaTracker tracker;  
  36.     private Dimension mySize;  
  37.       
  38.     // JButtons  
  39.     private JButton browseBtn;  
  40.     private JButton noiseBtn;  
  41.     private JButton colorfulBtn;  
  42.   
  43.     // rice number....  
  44.     private int riceNum = -1;  
  45.       
  46.       
  47.     public MainFrame() {  
  48.         JPanel btnPanel = new JPanel();  
  49.         btnPanel.setLayout(new FlowLayout(FlowLayout.LEFT));  
  50.         browseBtn = new JButton("Browse...");  
  51.         noiseBtn = new JButton("Remove Noise");  
  52.         colorfulBtn = new JButton("Colorful Rice");  
  53.           
  54.         browseBtn.setToolTipText("Please select image file...");  
  55.         noiseBtn.setToolTipText("find connected region and draw red rectangle");  
  56.         colorfulBtn.setToolTipText("Remove the minor noise region pixels...");  
  57.           
  58.         // buttons  
  59.         btnPanel.add(browseBtn);  
  60.         btnPanel.add(noiseBtn);  
  61.         btnPanel.add(colorfulBtn);  
  62.           
  63.         // setup listener...  
  64.         browseBtn.addActionListener(this);  
  65.         noiseBtn.addActionListener(this);  
  66.         colorfulBtn.addActionListener(this);  
  67.           
  68.         browseBtn.setEnabled(true);  
  69.         noiseBtn.setEnabled(true);  
  70.         colorfulBtn.setEnabled(true);  
  71.           
  72. //      minX = minY =  10000;  
  73. //      maxX = maxY = -1;  
  74.           
  75.         mySize = new Dimension(500300);  
  76.         JFrame demoUI = new JFrame("Rice Detection Demo");  
  77.         demoUI.getContentPane().setLayout(new BorderLayout());  
  78.         demoUI.getContentPane().add(this, BorderLayout.CENTER);  
  79.         demoUI.getContentPane().add(btnPanel, BorderLayout.SOUTH);  
  80.         demoUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  81.         demoUI.pack();  
  82.         demoUI.setVisible(true);  
  83.     }  
  84.       
  85.     public void paint(Graphics g) {  
  86.         Graphics2D g2 = (Graphics2D) g;  
  87.         if(rawImg != null) {  
  88.             Image scaledImage = rawImg.getScaledInstance(200200, Image.SCALE_FAST);  
  89.             g2.drawImage(scaledImage, 00200200null);  
  90.         }  
  91.         if(resultImage != null) {  
  92.             Image scaledImage = resultImage.getScaledInstance(200200, Image.SCALE_FAST);  
  93.             g2.drawImage(scaledImage, 2100200200null);  
  94.         }  
  95.           
  96.         g2.setPaint(Color.RED);  
  97.         if(riceNum > 0) {  
  98.             g2.drawString("Number of Rice : " + riceNum, 100300);  
  99.         } else {  
  100.             g2.drawString("Number of Rice : Unknown"100300);  
  101.         }  
  102.     }  
  103.     public Dimension getPreferredSize() {  
  104.         return mySize;  
  105.     }  
  106.       
  107.     public Dimension getMinimumSize() {  
  108.         return mySize;  
  109.     }  
  110.       
  111.     public Dimension getMaximumSize() {  
  112.         return mySize;  
  113.     }  
  114.       
  115.     public static void main(String[] args) {  
  116.         new MainFrame();  
  117.     }  
  118.       
  119.     @Override  
  120.     public void actionPerformed(ActionEvent e) {  
  121.         if(BROWSE_CMD.equals(e.getActionCommand())) {  
  122.             JFileChooser chooser = new JFileChooser();  
  123.             chooser.showOpenDialog(null);  
  124.             File f = chooser.getSelectedFile();  
  125.             BufferedImage bImage = null;  
  126.             if(f == nullreturn;  
  127.             try {  
  128.                 bImage = ImageIO.read(f);  
  129.                   
  130.             } catch (IOException e1) {  
  131.                 e1.printStackTrace();  
  132.             }  
  133.               
  134.             tracker = new MediaTracker(this);  
  135.             tracker.addImage(bImage, 1);  
  136.               
  137.             // blocked 10 seconds to load the image data  
  138.             try {  
  139.                 if (!tracker.waitForID(110000)) {  
  140.                     System.out.println("Load error.");  
  141.                     System.exit(1);  
  142.                 }// end if  
  143.             } catch (InterruptedException ine) {  
  144.                 ine.printStackTrace();  
  145.                 System.exit(1);  
  146.             } // end catch  
  147.             BinaryFilter bfilter = new BinaryFilter();  
  148.             rawImg = bfilter.filter(bImage, null);  
  149.             repaint();  
  150.         } else if(NOISE_CMD.equals(e.getActionCommand())) {  
  151.             FindRiceFilter frFilter = new FindRiceFilter();  
  152.             resultImage = frFilter.filter(rawImg, null);  
  153.             riceNum = frFilter.getSumRice();  
  154.             repaint();  
  155.         } else if(FUN_CMD.equals(e.getActionCommand())) {  
  156.             ColorfulRiceFilter cFilter = new ColorfulRiceFilter();  
  157.             resultImage = cFilter.filter(resultImage, null);  
  158.             repaint();  
  159.         } else {  
  160.             // do nothing...  
  161.         }  
  162.           
  163.     }  
  164. }  
没有更多推荐了,返回首页