ssim in c# (opencvsharp)

最近一直在做一个电脑屏幕内容的识别软件(具体内容后面的post再说),需要进行屏幕相同位置、不同时间点的截屏比对,进行判断该位置是否发生了改变。于是用到了opencvsharp和ssim。经过一番网上搜索,发现还没有C#版的ssim,特此把代码分享到这里,希望能帮到有缘人。

public class SSIMResult
    {
        public double score {
            get
            {
                return (mssim.Val0 + mssim.Val1 + mssim.Val2) / 3;
            }
        }
        public Scalar mssim;
        public Mat diff;
    }


public static SSIMResult getMSSIM(Mat i1, Mat i2)
        {
            const double C1 = 6.5025, C2 = 58.5225;
            /***************************** INITS **********************************/
            MatType d = MatType.CV_32F;

            Mat I1 = new Mat(), I2 = new Mat();
            i1.ConvertTo(I1, d);           // cannot calculate on one byte large values
            i2.ConvertTo(I2, d);

            Mat I2_2 = I2.Mul(I2);        // I2^2
            Mat I1_2 = I1.Mul(I1);        // I1^2
            Mat I1_I2 = I1.Mul(I2);        // I1 * I2

            /***********************PRELIMINARY COMPUTING ******************************/

            Mat mu1 = new Mat(), mu2 = new Mat();   //
            Cv2.GaussianBlur(I1, mu1, new OpenCvSharp.Size(11, 11), 1.5);
            Cv2.GaussianBlur(I2, mu2, new OpenCvSharp.Size(11, 11), 1.5);

            Mat mu1_2 = mu1.Mul(mu1);
            Mat mu2_2 = mu2.Mul(mu2);
            Mat mu1_mu2 = mu1.Mul(mu2);

            Mat sigma1_2 = new Mat(), sigma2_2 = new Mat(), sigma12 = new Mat();

            Cv2.GaussianBlur(I1_2, sigma1_2, new OpenCvSharp.Size(11, 11), 1.5);
            sigma1_2 -= mu1_2;

            Cv2.GaussianBlur(I2_2, sigma2_2, new OpenCvSharp.Size(11, 11), 1.5);
            sigma2_2 -= mu2_2;

            Cv2.GaussianBlur(I1_I2, sigma12, new OpenCvSharp.Size(11, 11), 1.5);
            sigma12 -= mu1_mu2;

            / FORMULA 
            Mat t1, t2, t3;

            t1 = 2 * mu1_mu2 + C1;
            t2 = 2 * sigma12 + C2;
            t3 = t1.Mul(t2);              // t3 = ((2*mu1_mu2 + C1).*(2*sigma12 + C2))

            t1 = mu1_2 + mu2_2 + C1;
            t2 = sigma1_2 + sigma2_2 + C2;
            t1 = t1.Mul(t2);               // t1 =((mu1_2 + mu2_2 + C1).*(sigma1_2 + sigma2_2 + C2))

            Mat ssim_map = new Mat();
            Cv2.Divide(t3, t1, ssim_map);      // ssim_map =  t3./t1;

            Scalar mssim = Cv2.Mean(ssim_map);// mssim = average of ssim map



            SSIMResult result = new SSIMResult();
            result.diff = ssim_map;
            result.mssim = mssim;


            return result;
        }

SSIMResult作为ssim的结果,包括3个member variables:

diff : 这是两幅图片的对比差异,32F,取值在-1和1之间

mssim :是BGRA四个通道的差异值,0-1,约接近1越相近

score : 是BGR三个通道差异值的平均,作为两个图片的整体差异值

你可能感兴趣的:(computer,vision,opencv,opencvsharp,ssim,图像处理,图像相似度)