我學習了圖像處理,並從一些簡單的事情開始,我寫了一個程序將全色圖像轉換爲黑白版本。在Windows窗體中對圖像進行二進制化非常慢 - 爲什麼?
我使用C#和Windows窗體。我用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);
}
}
}
程序,它的工作,但問題是 - 這實在是太慢了。大約需要21秒將400x400圖像轉換爲黑白圖像。現在
,我就不會那麼奇怪爲什麼,如果我不也有這樣的計劃寫在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(這不是我想要做的)。
不是迭代像素,而是使用'Imaging.ColorMatrix'。黑色和白色通常不是什麼人的意思 - 他們看起來很奇怪,像一個負面的。如果您的意思是灰度,請參閱:[將圖像轉換爲灰度的更快方法](http://stackoverflow.com/a/23595488/1070452) – Plutonix
您是否嘗試過使用[FillRectangle](https://msdn.microsoft.com/zh-cn/ -us/library/system.drawing.graphics.fillrectangle(v = vs.110).aspx)而不是'DrawEllipse'? – Pikoh
是的,Get/SetPixel由於鎖定而無法執行,請參閱http://stackoverflow.com/questions/24701703/c-sharp-faster-alternatives-to-setpixel-and-getpixel-for-bitmaps-for-windows- f/http://stackoverflow.com/questions/1563038/fast-work-with-bitmaps-in-c-sharp –