在c#中转换灰度图像到二进制图像(0 1图像)
本文关键字:图像 二进制 转换 灰度图像 | 更新日期: 2023-09-27 18:12:23
我有一些代码行。我只想把灰度图像转换成二值图像。看起来很简单,但我不明白哪里出错了!你能告诉我哪里不对吗?
private void convert()
{
try
{
OpenFileDialog op = new OpenFileDialog();
op.InitialDirectory = "D:/";
op.Filter = "All Files|*.*|JPEGs|*.jpg|Bitmaps|*.bmp|GIFs|*.gif";
op.FilterIndex = 1;
if (op.ShowDialog() == DialogResult.OK)
{
pictureBox3.Image = Image.FromFile(op.FileName);
pictureBox3.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox3.BorderStyle = BorderStyle.Fixed3D;
Bitmap img = new Bitmap(op.FileName);
int width = img.Width;
int height = img.Height;
string t = "";
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
if (img.GetPixel(j, i).A > 100 && img.GetPixel(j, i).B > 100 && img.GetPixel(j, i).G > 100 && img.GetPixel(j, i).R > 100)
{
t = t + "0";
}
else
{
t = t + "1";
}
}
t = t + "'r'n";
}
textBox1.Text = t;
}
}
catch { };
}
谢谢!
- 你把
i
和j
错写成了GetPixel(width, height)
img.GetPixel(j, i).A > 100
是冗余的-
catch { };
这是你的主要问题。你隐藏了一个异常和惊人的 - 使用
StringBuilder
:
private void Convert()
{
OpenFileDialog op = new OpenFileDialog();
op.InitialDirectory = "D:/";
op.Filter = "All Files|*.*|JPEGs|*.jpg|Bitmaps|*.bmp|GIFs|*.gif";
op.FilterIndex = 1;
if (op.ShowDialog() == DialogResult.OK)
{
pictureBox3.Image = Image.FromFile(op.FileName);
pictureBox3.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox3.BorderStyle = BorderStyle.Fixed3D;
Bitmap img = new Bitmap(op.FileName);
StringBuilder t = new StringBuilder();
for (int i = 0; i < img.Width; i++)
{
for (int j = 0; j < img.Height; j++)
{
t.Append((img.GetPixel(i, j).R > 100 && img.GetPixel(i, j).G > 100 &&
img.GetPixel(i, j).B > 100) ? 0 : 1);
}
t.AppendLine();
}
textBox1.Text = t.ToString();
}
}