Search code examples
c#computer-visionemgucv

EmguCV Detect Image Blurriness


I am attempting to detect an image's blurriness using EmguCV. Right now I am attempting to do an FFT of the gray image, but I am stuck because my program just hangs after calling CvInvoke.cvCopy. See below:

 _capturedFrames.ForEach(x =>
 {
    using(var gray = x.Convert<Gray, float>())
    {
       IntPtr complexImage = CvInvoke.cvCreateImage(gray.Size, IPL_DEPTH.IPL_DEPTH_32F, 2);

       CvInvoke.cvSetZero(complexImage);  // Initialize all elements to Zero
       CvInvoke.cvSetImageCOI(complexImage, 1);
       CvInvoke.cvCopy(gray.Ptr, complexImage, IntPtr.Zero);
       CvInvoke.cvSetImageCOI(complexImage, 0);

       var dft = new Matrix<float>(gray.Rows, gray.Cols, 2);
       CvInvoke.cvDFT(complexImage, dft, CV_DXT.CV_DXT_FORWARD, 0);

       double min;
       double max;
       Point minLoc;
       Point maxLoc;
       dft.MinMax(out min, out max, out minLoc, out maxLoc);

       if (max > overallMax)
       {
          overallMax = max;
          index = _capturedFrames.IndexOf(x);
       }

       CvInvoke.cvReleaseImage(ref complexImage);
    }
 });

The objective of the code above is to loop through a collection of images in memory and find the index of the sharpest image. Lets just pretend the method above was working... Is this a robust way of detecting the sharpest image? Are FFTs reliable for this purpose?


Solution

  • Figured it out y'all. See the corrected code below. Note the gray.NumberOfChannels property.

    _capturedFrames.ForEach(x =>
     {
        using(var gray = x.Convert<Gray, float>())
        {
           IntPtr complexImage = CvInvoke.cvCreateImage(gray.Size, IPL_DEPTH.IPL_DEPTH_32F, gray.NumberOfChannels);
    
           CvInvoke.cvSetZero(complexImage);  // Initialize all elements to Zero
           //CvInvoke.cvSetImageCOI(complexImage, 1);
           CvInvoke.cvCopy(gray.Ptr, complexImage, IntPtr.Zero);
           //CvInvoke.cvSetImageCOI(complexImage, 0);
    
           var dft = new Matrix<float>(gray.Rows, gray.Cols, gray.NumberOfChannels);
           CvInvoke.cvDFT(complexImage, dft, CV_DXT.CV_DXT_FORWARD, 0);
    
           double min;
           double max;
           Point minLoc;
           Point maxLoc;
           dft.MinMax(out min, out max, out minLoc, out maxLoc);
    
           if (max > overallMax)
           {
              overallMax = max;
              index = _capturedFrames.IndexOf(x);
           }
    
           CvInvoke.cvReleaseImage(ref complexImage);
        }
     });