Эквализация гистограммы изображения - C#
Формулировка задачи:
В результате эквализации гистограммы на носу появляются черные пятна. Где косяк?)
public Bitmap equalizing(Bitmap bmp)
{
Rectangle rect = new Rectangle(0, 0, Bmp.Width, Bmp.Height);
System.Drawing.Imaging.BitmapData bmpData = Bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, Bmp.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int bytes = bmpData.Stride * Bmp.Height;
byte[] grayValues = new byte[bytes];
int[] R = new int[256];
byte[] N = new byte[256];
byte[] left = new byte[256];
byte[] right = new byte[256];
System.Runtime.InteropServices.Marshal.Copy(ptr, grayValues, 0, bytes);
for (int i=0; i<grayValues.Length; i++)
{
++R[grayValues[i]];
}
byte z=0;
int Hint=0;
int Havg = grayValues.Length / R.Length;
for (int i = 0; i < N.Length-1; i++)
{
N[i] = 0;
}
for (int j = 0; j < R.Length; j++)
{
left[j] = z;
Hint += R[j];
while (Hint > Havg)
{
Hint -= Havg;
z++;
}
right[j] = z;
N[j] =(byte) ((left[j] + right[j]) / 2);
}
for (int i = 0; i<grayValues.Length; i++)
{
if (left[grayValues[i]] == right[grayValues[i]]) grayValues[i] = (byte)left[grayValues[i]];
else grayValues[i] = (byte)N[grayValues[i]];
}
System.Runtime.InteropServices.Marshal.Copy(grayValues, 0, ptr, bytes);
Bmp.UnlockBits(bmpData);
return Bmp;
}Решение задачи: «Эквализация гистограммы изображения»
textual
Листинг программы
private void эквализацияГистограммыToolStripMenuItem_Click(object sender, EventArgs e)
{
if (Bmp == null) mesBoxDownloadError();
else
{
equalizing(Bmp);
pictureBox1.Image = (Bitmap)Bmp;
Bitmap copy = new Bitmap(Bmp);
copy = Bmp.Clone(new Rectangle(0, 0, Bmp.Width, Bmp.Height), Bmp.PixelFormat);
bmstackz.Push(copy);
bmstackr.Clear();
}
}
public Bitmap equalizing(Bitmap bmp)
{
Rectangle rect = new Rectangle(0, 0, Bmp.Width, Bmp.Height);
System.Drawing.Imaging.BitmapData bmpData = Bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, Bmp.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int bytes = bmpData.Stride * Bmp.Height;
byte[] grayValues = new byte[bytes];
int[] R = new int[256];
byte[] N = new byte[256];
byte[] left = new byte[256];
byte[] right = new byte[256];
System.Runtime.InteropServices.Marshal.Copy(ptr, grayValues, 0, bytes);
for (int i=0; i<grayValues.Length; i++) ++R[grayValues[i]];
int z=0;
int Hint=0;
int Havg = grayValues.Length / R.Length;
for (int i = 0; i < N.Length-1; i++)
{
N[i] = 0;
}
for (int j = 0; j < R.Length; j++)
{
if (z > 255) left[j] = 255;
else left[j] = (byte)z;
Hint += R[j];
while (Hint > Havg)
{
Hint -= Havg;
z++;
}
if (z > 255) right[j] = 255;
else right[j] = (byte)z;
N[j] =(byte) ((left[j] + right[j]) / 2);
}
for (int i = 0; i<grayValues.Length; i++)
{
if (left[grayValues[i]] == right[grayValues[i]]) grayValues[i] = left[grayValues[i]];
else grayValues[i] = N[grayValues[i]];
}
System.Runtime.InteropServices.Marshal.Copy(grayValues, 0, ptr, bytes);
Bmp.UnlockBits(bmpData);
return Bmp;
}