I am work on an ASP.NetCore 5
project that requires users to upload document using a normal file picker, so i have to check if the document the user is uploading is blurry before resampling it and saving it to a database.
I did some research and found out that imagemagick.net would help me accomplish all of that, but can't seem to find a way around it
CodePudding user response:
I just googled a bit around and fiddled some Stackoverflow / Blog answers to this together:
public static class ImageExtensions
{
// as seen here: https://pyimagesearch.com/2015/09/07/blur-detection-with-opencv/
public static bool IsBlurry(this Image image, double threshold = 100.0)
{
var mat = GetMatFromSDImage(image);
var varianceOfLaplacian = VarianceOfLaplacian(mat);
return varianceOfLaplacian < threshold;
}
// as seen here: https://stackoverflow.com/questions/58005091/how-to-get-the-variance-of-laplacian-in-c-sharp
private static double VarianceOfLaplacian(Mat mat)
{
using var laplacian = new Mat();
CvInvoke.Laplacian(mat, laplacian, DepthType.Cv64F);
var mean = new MCvScalar();
var stddev = new MCvScalar();
CvInvoke.MeanStdDev(laplacian, ref mean, ref stddev);
return stddev.V0 * stddev.V0;
}
// as found here https://stackoverflow.com/questions/40384487/system-drawing-image-to-emgu-cv-mat
private static Mat GetMatFromSDImage(Image image)
{
int stride = 0;
Bitmap bmp = new Bitmap(image);
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height);
System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat);
System.Drawing.Imaging.PixelFormat pf = bmp.PixelFormat;
if (pf == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
{
stride = bmp.Width * 4;
}
else
{
stride = bmp.Width * 3;
}
Image<Bgra, byte> cvImage = new Image<Bgra, byte>(bmp.Width, bmp.Height, stride, (IntPtr)bmpData.Scan0);
bmp.UnlockBits(bmpData);
return cvImage.Mat;
}
}
I noted the origin of the snippets, as nothing has been implemented by me here ;) It does require the Emgu.CV package not imagemagick.
I hope this helps, it passed the few tests, i just did.