Sunday, March 13, 2011

ImageJ 3: Histogram

ตัวอย่างนี้จะเป็นการลองสร้าง Histogram ของรูปสีเทารูปนี้ครับ


ผลลัพธ์ที่อยากได้คือ Histogram ประมาณนี้

ImageJ มีฟังก์ชันในการคำนวณ Histogram ให้คือ getHistogram(); ซึ่งจะใช้หรือเขียนฟังก์ชันเองก็ได้ตามตัวอย่างต่อไปนี้ครับ
//Plugin to compute histogram
import ij.ImagePlus;
import ij.plugin.filter.PlugInFilter;
import ij.process.ImageProcessor;
import ij.process.ByteProcessor;

public class My_Histogram implements PlugInFilter 
{
 public int setup(String arg, ImagePlus im) 
 {
  return DOES_8G + NO_CHANGES;  //accept only 8-bit grayscale image
 }

 public void run(ImageProcessor ip) 
 {
  int[] H = new int[256];
  /*
  int MN = ip.getPixelCount();
  for(int p=0;p<MN;p++)
  {
   int v = ip.get(p);
   H[v] += 1;
  }
  */
  H = ip.getHistogram(); //built-in method   
 }
}

ส่วนการแสดงผล จำเป็นต้องสร้างหน้าต่างขึ้นมาใหม่ แล้ววาดจุดสีดำลงไปครับ ซึ่งโค้ดทั้งหมดต่อไปนี้ ยังอยู่ใน method run() ครับ
//find max of histogram bin
  int max=H[0];
  for(int b=1;b<256;b++)
  {
   if(max<H[b])
    max=H[b];
  }
  
  //create the image of histogram
  //prepare blank area of w=256 h=100
  ImageProcessor histip = new ByteProcessor(256,100); 
  histip.setValue(255) ; // white = 255 
  histip.fill(); // clear this image 
  //draw histogram bins    
  for(int b=0;b<256;b++)
  {
   int hh = (int)(100.0*H[b]/max); //normalized bin's height
   for(int r=0;r<hh;r++)
   {
    histip.set(b,99-r,0); //plot black points
   }
  }
  
  // display the histogram image: 
  ImagePlus histim = new ImagePlus("Histogram", histip); 
  histim.show();

No comments:

Post a Comment