Sunday, February 2, 2014

How to reduce noise from image (jpg or Png) in Asp.net C#

Hello,


You can use the code above.


Parameters: Image as bitmap, level of noise and radius of noise.



public static Bitmap NoiseReduction(Bitmap original, int level, int radius)
{
int width = original.Width;
int height = original.Height;

Bitmap source = null;

source = original.PixelFormat != PixelFormat.Format8bppIndexed
? BitmapManipulator.ConvertToGrayScale8bpp(original, false)
: original;


Bitmap destination = BitmapManipulator.CreateGrayscaleImage(width, height);

BitmapData srcData = source.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly,
source.PixelFormat);
BitmapData dstData = destination.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly,
destination.PixelFormat);

int stride = srcData.Stride;
byte pxVal;
int matrixWidth = (radius*2 + 1)*(radius*2 + 1);
var pxM = new byte[matrixWidth];
int meanIndex = (matrixWidth - 1)/2;
unsafe
{
var srcScan0 = (byte*) srcData.Scan0;
var dstScan0 = (byte*) dstData.Scan0;

for (int l = 0; l < level; l++)
{
for (int y = radius; y < height - radius; y++)
{
byte* srcRow = srcScan0 + (y*stride);
byte* dstRow = dstScan0 + (y*stride);
for (int x = radius; x < width - radius; x++)
{
pxVal = srcRow[x];
int mIndex = 0;
for (int k = y - radius; k < y + radius + 1; k++)
{
byte* srcRowMatrix = srcScan0 + (k*stride);
for (int j = x - radius; j < x + radius + 1; j++)
{
pxM[mIndex++] = srcRowMatrix[j];
}
}
Array.Sort(pxM);
dstRow[x] = pxM[meanIndex];
}
}
}
}

destination.UnlockBits(dstData);
source.UnlockBits(srcData);

// Dispose of fastOriginal if not originally supplied bitmap
if (source != original)
source.Dispose();

// Return
return destination;
}







João Sousa (MCTS) Senior Software Engineer


(if my reply answers your question, please propose it as an answer because it will help other users)





No comments:

Post a Comment