我学习图像处理并从简单的东西开始,我写了一个程序,将全彩色图像转换为它的黑白版本。
我使用了C#和Windows Forms。我使用PictureBox加载图像。然后我点击一个按钮进行转换,这里是它的事件处理程序:
private void button1_Click(object sender, EventArgs e)
{
Color kolor, kolor_wynik;
byte r, g, b, avg, prog;
prog = 85;
int h = MainPictureBox.Height;
int w = MainPictureBox.Width;
Bitmap bitmap = new Bitmap(MainPictureBox.Image); //needed for GetPixel()
Graphics graphics = MainPictureBox.CreateGraphics();
for (int j = 0; j < h; j++)
{
for (int i = 0; i < w; i++)
{
kolor = bitmap.GetPixel(i, j);
r = kolor.R;
g = kolor.G;
b = kolor.B;
avg = (byte)((r + g + b) / 3);
if (avg > prog)
kolor_wynik = Color.White;
else
kolor_wynik = Color.Black;
Pen pen = new Pen(kolor_wynik);
graphics.DrawEllipse(pen, i, j, 1, 1);
}
}
}
程序完成它的工作,但问题是 - 它真的很慢。将400x400图像转换为黑白图像大约需要21秒。
现在,如果我没有用VB 6.0编写这个程序,我不会那么惊讶:
Private Sub Command2_Click()
Dim kolor As Long ' kolor
Dim kolor_wynik As Long ' kolor
Dim r, g, b, avg As Byte
Dim prog As Byte
prog = 85
h = Picture1.ScaleHeight
w = Picture1.ScaleWidth
For j = 0 To h Step 1
For i = 0 To w Step 1
kolor = Picture1.Point(i, j)
r = kolor And &HFF
g = (kolor And &HFF00&) / &H100&
b = (kolor And &HFF0000) / &H10000
avg = (r + g + b) / 3
If (avg > prog) Then
kolor_wynik = vbWhite
Else
kolor_wynik = vbBlack
End If
Picture1.PSet (i, j), kolor_wynik
Next i
Next j
End Sub
这两种算法非常类似,但VB 6.0版本几乎立即完成了工作(我只能在Windows XP上测试它,而Windows 10上的C#版本)。
这种行为的原因是什么?我想在C#中做一些事情,但事实证明我必须切换到VB 6.0(这不是我想做的事情)。
答案 0 :(得分:-1)
C#代码处理每像素更改。虽然你的VB6只是一个超级快速的移位。
您可以在C#中执行相同操作。