private void 图片二值化ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (m_Bitmap!=null)
{
Rectangle rect = new Rectangle(0, 0, m_Bitmap.Width, m_Bitmap.Height);
BitmapData bmpData = m_Bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, m_Bitmap.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int bytes = m_Bitmap.Width * m_Bitmap.Height*3;
byte[] grayValues = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(ptr, grayValues, 0, bytes);
byte temp = 0;
byte T = 0;
byte maxGray = 0;
byte minGray = 255;
int[] countPixel = new int[256];
double mu1, mu2;
double numerator, denominator;
//计算直方图
for (int i = 0; i < grayValues.Length; i++)
{
temp = grayValues[i];
countPixel[temp]++;
if (temp > maxGray)
{
//最大灰度等级
maxGray = temp;
}
if (temp < minGray)
{
//最小灰度等级
minGray = temp;
}
}
//迭代法
byte oldT;
//初始阈值
T = oldT = Convert.ToByte((maxGray + minGray) / 2);
//迭代过程
do
{
oldT = T;
numerator = denominator = 0;
//迭代法公式1
for (int i = minGray; i <T; i++)
{
numerator += i * countPixel[i];
denominator += countPixel[i];
}
mu1 = numerator / denominator;
numerator = denominator = 0;
for (int i = T; i < maxGray; i++)
{
numerator += i * countPixel[i];
denominator += countPixel[i];
}
mu2 = numerator / denominator;
//迭代法公式2
T = Convert.ToByte((mu1 + mu2)/2);
}
while (T!=oldT);
//图像二值化
for (int i = 0; i < bytes ; i++)
{
if (grayValues[i]<T)
{
grayValues[i] = 0;
}
else
{
grayValues[i] = 255;
}
}
System.Runtime.InteropServices.Marshal.Copy(grayValues, 0, ptr, bytes);
m_Bitmap.UnlockBits(bmpData);
pictureBox1.Image = m_Bitmap;
}
}
07-13
2158
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
12-31
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交