我正在尝试对灰度图像进行简单的二维卷积。
内核
{ -1, -1, -1 },
{ -1, 8, -1 },
{ -1, -1, -1 }
卷积法
public static Bitmap Convolve(Bitmap originalBitmap, int[,] kernel)
{
int kernelSize = (int)Math.Sqrt(kernel.Length);
int newWidth = originalBitmap.Width - kernelSize + 1;
int newHeight = originalBitmap.Height - kernelSize + 1;
int[] newPixels = new int[newWidth* newHeight];
int newPixelsIndex = 0;
for (int row = 0; row < newHeight; row++)
{
for (int column = 0; column < newWidth; column++)
{
var convolutedPixelValue = 0;
// Convolution kernel
for(int kernelRow = 0; kernelRow < kernelSize; kernelRow++)
{
for(int kernelColumn = 0; kernelColumn < kernelSize; kernelColumn++) {
convolutedPixelValue = convolutedPixelValue + originalBitmap.GetPixel(column + kernelColumn, row + kernelRow).R * kernel[kernelRow, kernelColumn];;
}
}
newPixels[newPixelsIndex] = convolutedPixelValue;
newPixelsIndex++;
}
}
newPixels = NormalizeValues(newPixels, 0, 255);
return CreateBitmapFromArray(newPixels, newWidth, newHeight);
}
以及标准化值的方法。评论部分用于对比,结果在第三张图片上。
public static int[] NormalizeValues(int[] inputArray, int minValue, int maxValue)
{
int minArrayValue = inputArray.Min();
int maxArrayValue = inputArray.Max();
for (int i = 0; i < inputArray.Length; i++)
{
int currentValue = inputArray[i];
inputArray[i] = (int)(((double)(currentValue - minArrayValue) / (double)(maxArrayValue - minArrayValue)) * (double)(maxValue - minValue) + minValue);
//if (inputArray[i] > 127)
//{
// inputArray[i] = 255;
//}
//else
//{
// inputArray[i] = 0;
//}
}
return inputArray;
}
我的问题是为什么我的卷积这么奇怪。当我在互联网上尝试卷积时,我得到了更好的对比度图像。
我怎样才能实现它?