Hello, I am working on image processing(designing a UI) using C#.Net and VS 2012. I have added Convolution filter to my form. I have added a kernel matrix in back-end but now i want to add new matrix(of any size-3*3, 5*5, 7*7 etc) during run time. I don't know what to do and how to do. Can anyone help me, please.
(When we click on the Convolution button a new form appears and asks to enter new matrix. Here I am facing problem, I am unable to design format to enter the matrix in row-column format(creating different cells to enter data)).
What I have tried:
//Code for convolution
private static double[,] kernel
{
get
{
return new double[,]
{
{ 0, 1, 0 },
{ 1, -4, 1 },
{ 0, 1, 0 }
};
}
}
private void btnConvolution_Click(object sender, EventArgs e)
{
newBitmap = (Bitmap)pictureBox1.Image;
int width = newBitmap.Width;
int height = newBitmap.Height;
BitmapData srcData = newBitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
int bytes = srcData.Stride * srcData.Height;
byte[] buffer = new byte[bytes];
byte[] result = new byte[bytes];
Marshal.Copy(srcData.Scan0, buffer, 0, bytes);
newBitmap.UnlockBits(srcData);
int colorChannels = 3;
double[] rgb = new double[colorChannels];
int foff = (kernel.GetLength(0) - 1) / 2;
int kcenter = 0;
int kpixel = 0;
for (int y = foff; y < height - foff; y++)
{
for (int x = foff; x < width - foff; x++)
{
for (int c = 0; c < colorChannels; c++)
{
rgb[c] = 0.0;
}
kcenter = y * srcData.Stride + x * 4;
for (int fy = -foff; fy <= foff; fy++)
{
for (int fx = -foff; fx <= foff; fx++)
{
kpixel = kcenter + fy * srcData.Stride + fx * 4;
for (int c = 0; c < colorChannels; c++)
{
rgb[c] += (double)(buffer[kpixel + c]) * kernel[fy + foff, fx + foff];
}
}
}
for (int c = 0; c < colorChannels; c++)
{
if (rgb[c] > 255)
{
rgb[c] = 255;
}
else if (rgb[c] < 0)
{
rgb[c] = 0;
}
}
for (int c = 0; c < colorChannels; c++)
{
result[kcenter + c] = (byte)rgb[c];
}
result[kcenter + 3] = 255;
}
}
Bitmap resultImage = new Bitmap(width, height);
BitmapData resultData = resultImage.LockBits(new Rectangle(0, 0, width, height),
ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
Marshal.Copy(result, 0, resultData.Scan0, bytes);
resultImage.UnlockBits(resultData);
newBitmap = (Bitmap)resultImage.Clone();
pictureBox1.Image = newBitmap;
btnUndo.Enabled = true;
undostack.Push(pictureBox1.Image);
}
}