java 灰度直方图_灰度图像的直方图

这个Java代码段展示了如何创建一个`Histogram`类,用于处理BufferedImage图像并生成灰度直方图。首先,它从源图像中获取像素,计算每个灰度级的频率,并存储到直方图数组中。接着,找到最大频率,然后使用Graphics2D绘制直方图,包括坐标轴、标题和坐标刻度。最后,返回包含直方图的图像。
摘要由CSDN通过智能技术生成

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[i] = 0;

}

int index = 0;

for(int row=0;row

int tr = 0;

for(int col=0;col

index = row*width+col;

tr = (inPixels[index] >> 16) & 0xff;

histogram[tr] ++;

}

}

double maxFrequency = 0;//计算像素出现的最大频率值

for(int i=0;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

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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值