灰度圖像的直方圖
阿新 • • 發佈:2018-02-01
bst line [] 數據 mat == str body system
主要代碼如下:
package chapter6;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
/**
Created by LENOVO on 18-2-1.
*/
public class Histogram extends AbstractBufferedImageOp {public BufferedImage filter(BufferedImage src,BufferedImage dest){
int[] histogram = new int[256];
int width = src.getWidth();
int height = src.getHeight();
if(dest == null){
dest = creatCompatibleDestImage(src,null);
}
int[] inPixels = new int[width*height];
getRGB(src,0,0,width,height,inPixels);//獲取直方圖數據 for(int i=0;i<histogram.length;i++){ histogram[i] = 0; } int index = 0; for(int row=0;row<height;row++){ int tr = 0; for(int col=0;col<width;col++){ index = row*width+col; tr = (inPixels[index] >> 16) & 0xff; histogram[tr] ++; } } double maxFrequency = 0;//計算像素出現的最大頻率值 for(int i=0;i<histogram.length;i++){ maxFrequency = Math.max(histogram[i],maxFrequency); } //繪制直方圖 Graphics2D g2d = dest.createGraphics(); g2d.setPaint(Color.LIGHT_GRAY); g2d.fillRect(0,0,width,height); //繪制XY軸 g2d.setPaint(Color.black); g2d.drawLine(50,50,50,height-50); g2d.drawLine(50,height-50,width-50,height-50); //繪制XY軸標題 g2d.drawString("0",50,height-30); g2d.drawString("255",width-50,height-30); g2d.drawString("0",20,height-50); g2d.drawString(""+maxFrequency,20,50); //繪制坐標軸刻度 double xunit = (width-100)/255; double yunit = (height-100)/maxFrequency; for(int i=0;i<histogram.length;i++){ double xp = 50+xunit*i; double yp = yunit*histogram[i]; Rectangle2D rect2d = new Rectangle2D.Double(xp,height-50-yp,xunit,yp); g2d.fill(rect2d); } System.out.print(maxFrequency); return dest;
}
}
測試代碼同上
灰度圖像的直方圖