1 回答

TA貢獻1775條經驗 獲得超11個贊
問題在這里:
for (int col = -1; col <= 1; col++)
for (int row = -1; row <= 1; row++)
{
r += plos[0] * Gauss[Index];
g += plos[1] * Gauss[Index];
b += plos[2] * Gauss[Index];
Index++;
}
如果我理解得不錯的話,高斯算法是要去取周圍的點的值,計算出當前點的值的。
但是你這個地方9次讀取原像素顏色時,都是讀的本點的。加權累計之后的平均數,當然還是等于本點的值。
-----------------------
調好的程序在下面。
中間對于指針的變化方面有bug.我改為計算偏移的方式了。
還有,這個程序處理完之后,會自動為圖片加一個黑邊。原因是沒有處理最外的像素。如果要處理最邊上的像素,就要在值舊值時考慮是不是已經越出邊界。
-----------------------
private void Image_Soften()
{
try
{
int Height = this.pictureBox1.Image.Height;
int Width = this.pictureBox1.Image.Width;
Bitmap bitmap = new Bitmap(Width, Height, PixelFormat.Format32bppRgb);
Bitmap MyBitmap = (Bitmap)this.pictureBox1.Image;
BitmapData oldData = MyBitmap.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb);
BitmapData newData = bitmap.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);
unsafe
{
byte* plos = (byte*)(oldData.Scan0.ToPointer());
byte* pbg = (byte*)(newData.Scan0.ToPointer());
//高斯模板
int[] Gauss = { 1, 2, 1, 2, 4, 2, 1, 2, 1 };
for (int i = 1; i < Width - 1; i++)
{
for (int j = 1; j < Height - 1; j++)
{
int r = 0, g = 0, b = 0;
int Index = 0;
for (int col = -1; col <= 1; col++)
{
for (int row = -1; row <= 1; row++)
{
int off = ((j + row) *(Width) + (i + col)) * 4;
r += plos[off + 0] * Gauss[Index];
g += plos[off + 1] * Gauss[Index];
b += plos[off + 2] * Gauss[Index];
Index++;
}
}
r /= 16;
g /= 16;
b /= 16;
//處理顏色值溢出
r = r > 255 ? 255 : r;
r = r < 0 ? 0 : r;
g = g > 255 ? 255 : g;
g = g < 0 ? 0 : g;
b = b > 255 ? 255 : b;
b = b < 0 ? 0 : b;
int off2 = (j * Width + i) * 4;
pbg[off2 + 0] = (byte)r;
pbg[off2 + 1] = (byte)g;
pbg[off2 + 2] = (byte)b;
}
}
bitmap.UnlockBits(newData);
MyBitmap.UnlockBits(oldData);
this.pictureBox1.Image = bitmap;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "信息提示");
}
}
- 1 回答
- 0 關注
- 117 瀏覽
添加回答
舉報