10th
September
2008
Detecting Blank Images with C#
posted in Dotnet/.NET - C#, Programming |
Recently I needed a way to find blank images among a large batch of images. I had tens of thousands of images to work with so I came up with this c# function to tell me whether an image is blank.
The basic idea behind this function is that blank images will have highly uniform pixel values throughout the whole image. To measure the degree of uniformity (or variability), the function calculates the standard deviation of all pixel values. An image is determined to be blank if the standard deviation falls below a certain threshold.
Here’s the code. In order to compile, the project to which this code resides must have “Allow Unsafe Code” checked.
public static bool IsBlank(string imageFileName)
{
double stdDev = GetStdDev(imageFileName);
return stdDev < 100000;
}
/// <summary>
/// Get the standard deviation of pixel values.
/// </summary>
/// <param name="imageFileName">Name of the image file.</param>
/// <returns>Standard deviation.</returns>
public static double GetStdDev(string imageFileName)
{
double total = 0, totalVariance = 0;
int count = 0;
double stdDev = 0;
// First get all the bytes
using (Bitmap b = new Bitmap(imageFileName))
{
BitmapData bmData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadOnly, b.PixelFormat);
int stride = bmData.Stride;
IntPtr Scan0 = bmData.Scan0;
unsafe
{
byte* p = (byte*)(void*)Scan0;
int nOffset = stride - b.Width * 3;
for (int y = 0; y < b.Height; ++y)
{
for (int x = 0; x < b.Width; ++x)
{
count++;
byte blue = p[0];
byte green = p[1];
byte red = p[2];
int pixelValue = Color.FromArgb(0, red, green, blue).ToArgb();
total += pixelValue;
double avg = total / count;
totalVariance += Math.Pow(pixelValue - avg, 2);
stdDev = Math.Sqrt(totalVariance / count);
p += 3;
}
p += nOffset;
}
}
b.UnlockBits(bmData);
}
return stdDev;
}
This entry was posted
on Wednesday, September 10th, 2008 at 10:39 pm and is filed under Dotnet/.NET - C#, Programming.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.
posted on September 11th, 2008 at 9:08 am
posted on September 14th, 2008 at 9:43 pm
posted on October 21st, 2008 at 8:01 am
posted on March 2nd, 2009 at 1:33 pm
posted on March 2nd, 2009 at 1:56 pm
posted on March 2nd, 2009 at 3:52 pm
posted on March 2nd, 2009 at 6:47 pm
posted on April 24th, 2009 at 2:33 am
posted on April 24th, 2009 at 7:18 am
posted on April 29th, 2009 at 6:00 am
posted on April 29th, 2009 at 9:55 pm
posted on May 3rd, 2009 at 9:33 pm
posted on May 26th, 2009 at 6:46 pm
posted on May 26th, 2009 at 6:51 pm
posted on May 26th, 2009 at 7:55 pm
posted on May 26th, 2009 at 8:05 pm
posted on May 26th, 2009 at 8:09 pm
posted on May 26th, 2009 at 9:06 pm
posted on June 24th, 2009 at 9:26 am