直方图匹配2

直方图匹配的代码如下:

//直方图匹配(规定)将原图像按照给定直方图匹配,这个函数中给定的直方图图片形式,第二个参数为给定的直方图
static public Image<Gray, Byte> histogrammatching(Image<Gray, Byte> input,Image<Gray,Byte> MachingImage)
{
var result = input.CopyBlank();

int[] srcgraylevel = new int[256];
int[] dstgraylevel = new int[256];
byte[] newgray = new byte[256];


//求原图像上每个灰度级上的像素个数,结果存储在srcgraylevel数组中
for (int i = 0; i < input.Width; i++)
{
for (int j = 0; j < input.Height; j++)
{
srcgraylevel[input.Data[j, i, 0]]++;
}
}


//求匹配图像上每个灰度级上的像素个数,结果存储到dstgraylevel数组中
for (int i = 0; i < MachingImage.Width; i++)
{
for (int j = 0; j < MachingImage.Height; j++)
{
dstgraylevel[MachingImage.Data[j, i, 0]]++;
}
}

int srcsum=0;//原图像像素累积分布
for (int i = 0; i <= 255; i++)
{
int dstsum=0;//匹配图像像素的累积分布
int graydifference1=int.MaxValue,graydifference2=0;//记录两个图像中像素累积分布的差值
newgray[i] = 0;

if (srcgraylevel[i] > 0)
{
srcsum = srcsum + srcgraylevel[i];

int lastgraylevel = 0;
for (int j = 0; j <= 255; j++)
{

if (dstgraylevel[j] > 0)
{
dstsum = dstsum + dstgraylevel[j];
graydifference2 = dstsum - srcsum;
graydifference2 = Math.Abs(graydifference2);
if (graydifference2 <= graydifference1)
{
graydifference1 = graydifference2;
lastgraylevel=j;
}
else
{
newgray[i] = (byte)(lastgraylevel);
break;
}
}
}
}


}


//将原图像中的每个点替换成新的灰度,得到直方图规定化的结果
for (int i = 0; i < input.Width; i++)
{
for (int j = 0; j < input.Height; j++)
{

result.Data[j, i, 0] = newgray[input.Data[j, i, 0]];

}
}


return result;
}


}
}

 

 

posted @ 2014-01-12 00:24  老笨wjr  阅读(320)  评论(0编辑  收藏  举报