C#阈值分割处理图像

LBY_LPLFC 2016-03-04 02:21:28
想用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;
}
这是程序,处理时总是只能处理上半部分,有没有大神能给改改,或者给一个更好的处理方法。
...全文
524 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
橘子皮... 2019-05-22
  • 打赏
  • 举报
回复
https://docs.microsoft.com/zh-cn/dotnet/api/system.drawing.imaging.imagelockmode?redirectedfrom=MSDN&view=netframework-4.8
橘子皮... 2019-05-22
  • 打赏
  • 举报
回复
LockBits 这个方法是不是线程安全的??
qq_44025096 2019-05-21
  • 打赏
  • 举报
回复
int bytes = curBitmap.Width * curBitmap.Height;改成int bytes = bmpData.Height* bmpData.Stride ;
LBY_LPLFC 2016-03-04
  • 打赏
  • 举报
回复
能具体点吧,没听懂
xuzuning 2016-03-04
  • 打赏
  • 举报
回复
您忘了每个像素是由三原色组成的

111,098

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧