搜尋此網誌

2009年4月24日 星期五

C# picturebox1與picturebox2 影像處理問題

如果說實際上原圖與修改過後的圖要放在同一個form裡做比較,如果拿我之前寫的GetPixel與SetPixel方式下去改,以當下直覺寫法可能會為

private void btnGray_Click(object sender, EventArgs e)
{
try
{
Bitmap bm1 = (Bitmap)pictureBox1.Image;
Bitmap bm2 = bm1;
int w1 = pictureBox1.Image.Width;
int h1 = pictureBox1.Image.Width;
int x;
int y;
for (y = 0; y <= h1 - 1; y++)
{
for (x = 0; x <= w1 - 1; x++)
{
Color c1 = bm1.GetPixel(x, y);
int r1 = c1.R;
int g1 = c1.G;
int b1 = c1.B;
int avg1 = (r1 + g1 + b1) / 3;
bm2.SetPixel(x, y, Color.FromArgb(avg1, avg1, avg1));
}
}
pictureBox2.Image = bm2;
}

catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}


而立即顯示出來的圖可能是沒有問題或是怪怪的...















而當我按下Refresh按鍵時會發現...
















實質上bm2=bm1以為是另外複製一個圖片到picturebox2上,但當我們在做影像處理時在記憶體中是用相同的區塊...

所以可以寫成這樣...

private void btnProcess_Click(object sender, EventArgs e)
{
Bitmap p1 = (Bitmap)pictureBox1.Image;
Bitmap p2 = new Bitmap(p1.Height, p1.Width);
int avg;
for (int i = 0; i < p1.Height; i++)
{
for (int j = 0; j < p1.Width; j++)
{
avg = (p1.GetPixel(i,j).R + p1.GetPixel(i,j).G + p1.GetPixel(i,j).B)/3;
p2.SetPixel(i, j, Color.FromArgb(avg, avg, avg));
}
}
pictureBox2.Image = p2;
}

當我按完Process再按Refresh時,picturebox1還是保持彩色圖片...

沒有留言:

張貼留言