Emgucv实现Unsharp Mask USM锐化算法

USM算法是PS常用的算法,原理可以在网上看看,这样主要是实现的代码。
opencv实现USM算法的代码是:

void ImageSharp(Mat &src, Mat &dst, int nAmount = 200)
{
    double sigma = 3;
    int threshold = 1;
    float amount = nAmount / 100.0f;
    Mat imgBlurred;
    GaussianBlur(src, imgBlurred, Size(), sigma, sigma);
    Mat lowContrastMask = abs(src - imgBlurred)"ddd", lowContrastMask);
    dst = src*(1 + amount) + imgBlurred*(-amount);
    src.copyTo(dst, lowContrastMask);
}

改写成Emgucv的实现代码:

     private void GetMat(Imagebyte> srcimg, Imagebyte> imgBlurred, ref Mat dst, int nAmount = 200)
        {
            float amount = nAmount / 100f;
            using (Imagebyte> dst_temp = new Imagebyte>(srcimg.Width, srcimg.Height))
            {
                for (int v = 0; v < srcimg.Height; v++)
                {
                    for (int u = 0; u < srcimg.Width; u++)
                    {
                        byte a = srcimg.Data[v, u, 0]; //Get Pixel Color | fast way
                        byte b = imgBlurred.Data[v, u, 0];
                        int c = (int)(a * (1 + amount) - (amount * b));
                        if (c < 0) c = 0;
                        if (c > 255) c = 255;
                        dst_temp.Data[v, u, 0] = (byte)c;
                    }
                }
                dst = dst_temp.Mat.Clone();
            }
        }
        /// 
        /// 获取锐化图像
        /// 
        /// 源图像
        /// 输出图像
        /// 数量
        /// 
        /// 阈值
        public  void getSharpenImage(Mat src, ref Mat dst, int nAmount = 200, double sigma = 3, int threshold = 0)
        {

            float amount = nAmount / 100.0F;
            using (Mat imgBlurred = new Mat())
            {
                CvInvoke.GaussianBlur(src, imgBlurred, new Size(0, 0), sigma, sigma);
                using (Mat mask_temp = new Mat())
                {
                    CvInvoke.AbsDiff(src, imgBlurred, mask_temp);
                    using (Mat lowcontrastmask = new Mat())
                    {
                        CvInvoke.Threshold(mask_temp, lowcontrastmask, threshold, 255, ThresholdType.BinaryInv);
                        GetMat(src.ToImagebyte>(), imgBlurred.ToImagebyte>(), ref dst);
                        src.CopyTo(dst, lowcontrastmask);
                    }
                }
            }
        }

原图:

锐化之后:

你可能感兴趣的:(Image,Process,ASP.NET)