C# 使用FFT识别模糊图像

6
我正在寻找一种在C#中识别图像是否模糊的方法。我看到了这篇文章,但我没有看到适用于我的情况的方法。
我发现AForge.dll可以将FFT应用于我的图像。我正在寻找一种简单的方法来确定图像是否模糊(我对数学不是很熟悉)。
以下是我的代码:
Bitmap  Picture;

// I'm working with images sized between 130x130 and 150x150
Bitmap tmp = new Bitmap(pictureFile);

// Crop to be 128x128
Bitmap cropped = cropBitmap(tmp, 128, 128);
using (MemoryStream ms = new MemoryStream())
{
    cropped.Save(ms, ImageFormat.Gif);
    ms.Position = 0;
    // Save in grayscale
    Picture = new Bitmap(ms);
}

// Create the ComplexImage with AForge.dll
ComplexImage output = ComplexImage.FromBitmap(Picture);
// Apply FFT
output.ForwardFourierTransform();
Bitmap result = output.ToBitmap();

// to be continued...

你的情况与你提到的帖子有何不同?你是否只是在将基于opencv、Mathematica和Matlab的解决方案转换为C#时遇到了麻烦?如果是这种情况,你卡在哪里了(例如,你尝试过openCV .net包装器吗)?否则,能否详细说明一下你的情况有何不同? - SleuthEye
1
考虑到模糊算法使用周围像素的平均值,您应该能够检测到这种平均值以统一的RGB分布形式应用于整个图像。 - Krythic
可能是如何检测图像是否模糊?的重复问题。 - Zze
1个回答

8

这应该可以解决问题。

calcBlurriness() 的结果越小(接近于零),图像就越清晰。

using OpenCvSharp;    
namespace BlurDetectSO {
    class Program
    {

        static float calcBlurriness(Mat src)
        {
            Mat Gx = new Mat();
            Mat Gy = new Mat();
            Cv2.Sobel(src, Gx, MatType.CV_32F, 1, 0);
            Cv2.Sobel(src, Gy, MatType.CV_32F, 0, 1);
            double normGx = Cv2.Norm(Gx);
            double normGy = Cv2.Norm(Gy);
            double sumSq = normGx * normGx + normGy * normGy;
            return (float)(1.0 / (sumSq / (src.Size().Height * src.Size().Width) + 1e-6));
        }

        static void Main(string[] args)
        {
            Mat src = Cv2.ImRead("lenna.png", ImreadModes.GrayScale);
            Mat dst = new Mat();

            var blurIndex = calcBlurriness(src);

            //test: find edges...
            //Cv2.Canny(src, dst, 50, 200);
            //using (new Window("src image", src))
            //using (new Window("dst image", dst))
            //{Cv2.WaitKey();}
        }
    }
}

注:

  • 正如您所看到的,我使用了.NET封装程序OpenCVSharp(有些人改用Emgucv - 看起来更复杂,但可能更先进)。
  • 我进行了一些测试。这种方法在某些类型的图像中效果不佳。我观察到在包含某种自然噪声并可被解释为模糊的图像中存在问题。
  • 这是我的第一个OpenCV尝试。所以,请谨慎使用。改编自此示例

我从Nuget获取了OpenCVSharp,但类名与您的示例不对应。也许您可以分享一下您使用的Nuget包是哪个?似乎有几个端口可用。 - Savage
看起来是由shimat开发的OpenCVSharp4? - Savage
1
@Savage Puh,那是在2018年,幸运的是,我仍然在我的笔记本电脑上保存了样例。我使用了由shimat提供的OpenCvSharp3-AnyCPU.3.3.1.20171117.nupkg包。我注意到的唯一改变是属性ImreadModes.GrayScale被重命名为Grayscale - wp78de

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接