主要代码如下:
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;
}
}
测试代码同上