C#阈值分割处理图像
想用c#编一个可以对图像阈值分割的函数,但是老是运行不正确
private static Bitmap robot(Bitmap curBitmap)
{
Rectangle rect = new Rectangle(0, 0, curBitmap.Width, curBitmap.Height);
System.Drawing.Imaging.BitmapData bmpData = curBitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, curBitmap.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int bytes = curBitmap.Width * curBitmap.Height;
byte[] grayValues = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(ptr, grayValues, 0, bytes);
byte T = 0, S = 0;
byte[] neighb = new byte[bytes];
byte temp = 0;
byte maxGray = 0;
byte minGray = 255;
int[] countPixel = new int[256];
for (int i = 0; i < grayValues.Length; i++)
{
temp = grayValues[i];
countPixel[temp]++;
if (temp > maxGray)
{
maxGray = temp;
}
if (temp < minGray)
{
minGray = temp;
}
}
double mu1, mu2;
int numerator;
double sigma;
double tempMax = 0;
double w1 = 0, w2 = 0;
double sum = 0;
numerator = 0;
for (int i = minGray; i <= maxGray; i++)
{
sum += i * countPixel[i];
}
for (int i = minGray; i < maxGray; i++)
{
w1 += countPixel[i];
numerator += i * countPixel[i];
mu1 = numerator / w1;
w2 = grayValues.Length - w1;
mu2 = (sum - numerator) / w2;
sigma = w1 * w2 * (mu1 - mu2) * (mu1 - mu2);
if (sigma > tempMax)
{
tempMax = sigma;
T = Convert.ToByte(i);
}
} 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);
curBitmap.UnlockBits(bmpData);
return curBitmap;
}
这是程序,处理时总是只能处理上半部分,有没有大神能给改改,或者给一个更好的处理方法。