首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

OpenCvSharp Demo 饱和度、明度、对比度、锐化、阴影、高光、色温实现滤镜效果

  • 25-02-19 03:42
  • 3089
  • 7117
blog.csdn.net

目录

效果

风景-天空滤镜

人像—酷感冷艳滤镜

美食—鲜美滤镜

美食—巧克力滤镜

项目

代码

参考 

下载


效果

风景-天空滤镜

人像—酷感冷艳滤镜

美食—鲜美滤镜

美食—巧克力滤镜

项目

代码

using OpenCvSharp;
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Security.Cryptography;
using System.Windows.Forms;

namespace OpenCvSharp_Demo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
        string startupPath;
        string image_path;

        Stopwatch stopwatch = new Stopwatch();

        Mat image;
        Mat result_image;

        private void Form1_Load(object sender, EventArgs e)
        {
            startupPath = System.Windows.Forms.Application.StartupPath;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = fileFilter;
            if (ofd.ShowDialog() != DialogResult.OK) return;

            pictureBox1.Image = null;
            pictureBox2.Image = null;
            textBox1.Text = "";

            image_path = ofd.FileName;
            pictureBox1.Image = new Bitmap(image_path);
            image = new Mat(image_path);
        }

        byte max2(byte a, byte b)
        {
            return a > b ? a : b;
        }

        byte min2(byte a, byte b)
        {
            return a < b ? a : b;
        }

        byte max3(byte a, byte b, byte c)
        {
            return a > b ? max2(a, c) : max2(b, c);
        }

        byte min3(byte a, byte b, byte c)
        {
            return a < b ? min2(a, c) : min2(b, c);
        }

        ///


        /// 饱和度
        ///

        ///
        ///
        ///
        unsafe Mat Saturation(Mat src, int percent)
        {
            float Increment = percent * 1.0f / 100;
            Mat temp = src.Clone();
            int row = src.Rows;
            int col = src.Cols;
            for (int i = 0; i < row; ++i)
            {
                byte* t = (byte*)temp.Ptr(i);
                byte* s = (byte*)src.Ptr(i);
                for (int j = 0; j < col; ++j)
                {
                    byte b = s[3 * j];
                    byte g = s[3 * j + 1];
                    byte r = s[3 * j + 2];
                    float max = max3(r, g, b);
                    float min = min3(r, g, b);
                    float delta, value;
                    float L, S, alpha;
                    delta = (max - min) / 255;
                    if (delta == 0)
                        continue;
                    value = (max + min) / 255;
                    L = value / 2;
                    if (L < 0.5)
                        S = delta / value;
                    else
                        S = delta / (2 - value);
                    if (Increment >= 0)
                    {
                        if ((Increment + S) >= 1)
                            alpha = S;
                        else
                            alpha = 1 - Increment;
                        alpha = 1 / alpha - 1;
                        t[3 * j + 2] = (byte)(r + (r - L * 255) * alpha);
                        t[3 * j + 1] = (byte)(g + (g - L * 255) * alpha);
                        t[3 * j] = (byte)(b + (b - L * 255) * alpha);
                    }
                    else
                    {
                        alpha = Increment;
                        t[3 * j + 2] = (byte)(L * 255 + (r - L * 255) * (1 + alpha));
                        t[3 * j + 1] = (byte)(L * 255 + (g - L * 255) * (1 + alpha));
                        t[3 * j] = (byte)(L * 255 + (b - L * 255) * (1 + alpha));
                    }
                }
            }
            return temp;
        }

        ///


        /// 明度
        ///

        ///
        ///
        ///
        unsafe Mat Lightness(Mat src, float percent)
        {
            float alpha = percent / 100;
            alpha = Math.Max(-1.0f, Math.Min(1.0f, alpha));
            Mat temp = src.Clone();
            int row = src.Rows;
            int col = src.Cols;
            for (int i = 0; i < row; ++i)
            {

                byte* t = (byte*)temp.Ptr(i);
                byte* s = (byte*)src.Ptr(i);

                for (int j = 0; j < col; ++j)
                {
                    byte b = s[3 * j];
                    byte g = s[3 * j + 1];
                    byte r = s[3 * j + 2];
                    if (alpha >= 0)
                    {
                        t[3 * j + 2] = (byte)(r * (1 - alpha) + 255 * alpha);
                        t[3 * j + 1] = (byte)(g * (1 - alpha) + 255 * alpha);
                        t[3 * j] = (byte)(b * (1 - alpha) + 255 * alpha);
                    }
                    else
                    {
                        t[3 * j + 2] = (byte)(r * (1 + alpha));
                        t[3 * j + 1] = (byte)(g * (1 + alpha));
                        t[3 * j] = (byte)(b * (1 + alpha));
                    }
                }
            }
            return temp;
        }

        ///


        /// 对比度
        ///

        unsafe Mat Contrast(Mat src, int percent)
        {
            float alpha = percent / 100.0f;
            alpha = Math.Max(-1.0f, Math.Min(1.0f, alpha));
            Mat temp = src.Clone();
            int row = src.Rows;
            int col = src.Cols;
            int thresh = 127;
            for (int i = 0; i < row; ++i)
            {
                byte* t = (byte*)temp.Ptr(i);
                byte* s = (byte*)src.Ptr(i);
                for (int j = 0; j < col; ++j)
                {
                    byte b = s[3 * j];
                    byte g = s[3 * j + 1];
                    byte r = s[3 * j + 2];
                    int newb, newg, newr;
                    if (alpha == 1)
                    {
                        t[3 * j + 2] = (byte)(r > thresh ? 255 : 0);
                        t[3 * j + 1] = (byte)(g > thresh ? 255 : 0);
                        t[3 * j] = (byte)(b > thresh ? 255 : 0);
                        continue;
                    }
                    else if (alpha >= 0)
                    {
                        newr = (int)(thresh + (r - thresh) / (1 - alpha));
                        newg = (int)(thresh + (g - thresh) / (1 - alpha));
                        newb = (int)(thresh + (b - thresh) / (1 - alpha));
                    }
                    else
                    {
                        newr = (int)(thresh + (r - thresh) * (1 + alpha));
                        newg = (int)(thresh + (g - thresh) * (1 + alpha));
                        newb = (int)(thresh + (b - thresh) * (1 + alpha));

                    }
                    newr = Math.Max(0, Math.Min(255, newr));
                    newg = Math.Max(0, Math.Min(255, newg));
                    newb = Math.Max(0, Math.Min(255, newb));
                    t[3 * j + 2] = (byte)(newr);
                    t[3 * j + 1] = (byte)(newg);
                    t[3 * j] = (byte)(newb);
                }
            }
            return temp;
        }

        ///


        /// 图像阴影选取
        ///

        ///
        ///
        ///
        unsafe Mat Shadow(Mat input, int light)
        {
            // 生成灰度图
            Mat gray = Mat.Zeros(input.Size(), MatType.CV_32FC1);
            Mat f = input.Clone();
            f.ConvertTo(f, MatType.CV_32FC3);
            Mat[] pics = new Mat[3] { new Mat(), new Mat(), new Mat() };
            Cv2.Split(f, out pics);
            gray = 0.299f * pics[2] + 0.587 * pics[1] + 0.114 * pics[0];
            gray = gray / 255.0f;

            // 确定阴影区
            Mat thresh = Mat.Zeros(gray.Size(), gray.Type());
            thresh = (1.0f - gray).Mul(1.0f - gray);

            // 取平均值作为阈值
            Scalar t = Cv2.Mean(thresh);
            Mat mask = Mat.Zeros(gray.Size(), MatType.CV_8UC1);
            mask.SetTo(new Scalar(255), thresh.GreaterThanOrEqual(t.Val0));


            // 参数设置
            int max = 4;
            float bright = light / 100.0f / max;
            float mid = 1.0f + max * bright;

            // 边缘平滑过渡
            Mat midrate = Mat.Zeros(input.Size(), MatType.CV_32FC1);
            Mat brightrate = Mat.Zeros(input.Size(), MatType.CV_32FC1);
            for (int i = 0; i < input.Rows; ++i)
            {
                byte* m = (byte*)mask.Ptr(i);
                float* th = (float*)thresh.Ptr(i);
                float* mi = (float*)midrate.Ptr(i);
                float* br = (float*)brightrate.Ptr(i);
                for (int j = 0; j < input.Cols; ++j)
                {
                    if (m[j] == 255)
                    {
                        mi[j] = mid;
                        br[j] = bright;
                    }
                    else
                    {
                        mi[j] = (float)((mid - 1.0f) / t[0] * th[j] + 1.0f);
                        br[j] = (float)((1.0f / t[0] * th[j]) * bright);
                    }
                }


            }

            // 阴影提亮,获取结果图
            Mat result = Mat.Zeros(input.Size(), input.Type());
            for (int i = 0; i < input.Rows; ++i)
            {
                float* mi = (float*)midrate.Ptr(i);
                float* br = (float*)brightrate.Ptr(i);
                byte* @in = (byte*)input.Ptr(i);
                byte* r = (byte*)result.Ptr(i);
                for (int j = 0; j < input.Cols; ++j)
                {
                    for (int k = 0; k < 3; ++k)
                    {
                        float temp = (float)(Math.Pow((float)(@in[3 * j + k]) / 255.0f, 1.0f / mi[j]) * (1.0 / (1 - br[j])));
                        if (temp > 1.0f)
                            temp = 1.0f;
                        if (temp < 0.0f)
                            temp = 0.0f;
                        byte utemp = (byte)(255 * temp);
                        r[3 * j + k] = utemp;
                    }

                }
            }
            return result;
        }

        ///


        /// 图像高光选取
        ///

        ///
        ///
        ///
        unsafe Mat HighLight(Mat input, int light)
        {
            // 生成灰度图
            Mat gray = Mat.Zeros(input.Size(), MatType.CV_32FC1);
            Mat f = input.Clone();
            f.ConvertTo(f, MatType.CV_32FC3);
            Mat[] pics = new Mat[3] { new Mat(), new Mat(), new Mat() };
            Cv2.Split(f, out pics);
            gray = 0.299f * pics[2] + 0.587 * pics[1] + 0.114 * pics[0];
            gray = gray / 255.0f;

            // 确定高光区
            Mat thresh = Mat.Zeros(gray.Size(), gray.Type());
            thresh = gray.Mul(gray);
            // 取平均值作为阈值
            Scalar t = Cv2.Mean(thresh);
            Mat mask = Mat.Zeros(gray.Size(), MatType.CV_8UC1);
            mask.SetTo(new Scalar(255), thresh.GreaterThanOrEqual(t.Val0));

            // 参数设置
            int max = 4;
            float bright = light / 100.0f / max;
            float mid = 1.0f + max * bright;

            // 边缘平滑过渡
            Mat midrate = Mat.Zeros(input.Size(), MatType.CV_32FC1);
            Mat brightrate = Mat.Zeros(input.Size(), MatType.CV_32FC1);
            for (int i = 0; i < input.Rows; ++i)
            {

                byte* m = (byte*)mask.Ptr(i);
                float* th = (float*)thresh.Ptr(i);
                float* mi = (float*)midrate.Ptr(i);
                float* br = (float*)brightrate.Ptr(i);

                for (int j = 0; j < input.Cols; ++j)
                {
                    if (m[j] == 255)
                    {
                        mi[j] = mid;
                        br[j] = bright;
                    }
                    else
                    {
                        mi[j] = (float)((mid - 1.0f) / t[0] * th[j] + 1.0f);
                        br[j] = (float)((1.0f / t[0] * th[j]) * bright);
                    }
                }
            }

            // 高光提亮,获取结果图
            Mat result = Mat.Zeros(input.Size(), input.Type());
            for (int i = 0; i < input.Rows; ++i)
            {
                float* mi = (float*)midrate.Ptr(i);
                float* br = (float*)brightrate.Ptr(i);
                byte* @in = (byte*)input.Ptr(i);
                byte* r = (byte*)result.Ptr(i);


                for (int j = 0; j < input.Cols; ++j)
                {
                    for (int k = 0; k < 3; ++k)
                    {
                        float temp = (float)(Math.Pow((float)(@in[3 * j + k]) / 255.0f, 1.0f / mi[j]) * (1.0 / (1 - br[j])));
                        if (temp > 1.0f)
                            temp = 1.0f;
                        if (temp < 0.0f)
                            temp = 0.0f;
                        byte utemp = (byte)(255 * temp);
                        r[3 * j + k] = utemp;
                    }

                }
            }
            return result;
        }

        // 色温调节
        unsafe Mat ColorTemperature(Mat input, int n)
        {
            Mat result = input.Clone();
            int row = input.Rows;
            int col = input.Cols;
            int level = n / 2;
            for (int i = 0; i < row; ++i)
            {
                byte* a = (byte*)input.Ptr(i);
                byte* r = (byte*)result.Ptr(i);
                for (int j = 0; j < col; ++j)
                {
                    int R, G, B;
                    // R通道
                    R = a[j * 3 + 2];
                    R = R + level;
                    if (R > 255)
                    {
                        r[j * 3 + 2] = 255;
                    }
                    else if (R < 0)
                    {
                        r[j * 3 + 2] = 0;
                    }
                    else
                    {
                        r[j * 3 + 2] = (byte)R;
                    }
                    // G通道
                    G = a[j * 3 + 1];
                    G = G + level;
                    if (G > 255)
                    {
                        r[j * 3 + 1] = 255;
                    }
                    else if (G < 0)
                    {
                        r[j * 3 + 1] = 0;
                    }
                    else
                    {
                        r[j * 3 + 1] = (byte)G;
                    }
                    // B通道
                    B = a[j * 3];
                    B = B - level;
                    if (B > 255)
                    {
                        r[j * 3] = 255;
                    }
                    else if (B < 0)
                    {
                        r[j * 3] = 0;
                    }
                    else
                    {
                        r[j * 3] = (byte)B;
                    }
                }
            }
            return result;
        }

        // 图像锐化
        unsafe Mat Sharpen(Mat input, int percent, int type)
        {
            Mat result;
            Mat s = input.Clone();
            InputArray kernel;
            switch (type)
            {
                case 0:
                    kernel =
                    InputArray.Create(new float[3, 3] {
                    { 0, -1, 0 },
                    { -1, 4, -1 },
                    { 0, -1, 0 } });
                    break;
                case 1:
                    kernel =
                    InputArray.Create(new float[3, 3] {
                    {  -1, -1, -1},
                    {  -1, 8, -1 },
                    {  -1, -1, -1 } });

                    break;
                default:
                    kernel =
                    InputArray.Create(new float[3, 3] {
                    {  0, -1, 0},
                    {  -1, 4, -1 },
                    {  0, -1, 0 } });

                    break;
            }
            Cv2.Filter2D(s, s, s.Depth(), kernel);
            result = input + s * 0.01 * percent;
            return result;
        }

        //天空滤镜
        private void button2_Click(object sender, EventArgs e)
        {
            stopwatch.Restart();

            image_path = "test_img\\sky.jpg";
            pictureBox1.Image = new Bitmap(image_path);

            Mat src = Cv2.ImRead(image_path);
            Mat sat = Saturation(src, 35);
            Mat lig = Lightness(sat, 20);
            Mat con = Contrast(lig, 15);
            Mat sdo = Shadow(con, 15);
            Mat hig = HighLight(sdo, -30);
            result_image = ColorTemperature(hig, -40);


            double costTime = stopwatch.Elapsed.TotalMilliseconds;
            textBox1.Text = $"耗时:{costTime:F2}ms";
            pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (pictureBox2.Image == null)
            {
                return;
            }
            Bitmap output = new Bitmap(pictureBox2.Image);
            var sdf = new SaveFileDialog();
            sdf.Title = "保存";
            sdf.Filter = "Images (*.jpg)|*.jpg|Images (*.png)|*.png|Images (*.bmp)|*.bmp|Images (*.emf)|*.emf|Images (*.exif)|*.exif|Images (*.gif)|*.gif|Images (*.ico)|*.ico|Images (*.tiff)|*.tiff|Images (*.wmf)|*.wmf";
            if (sdf.ShowDialog() == DialogResult.OK)
            {
                switch (sdf.FilterIndex)
                {
                    case 1:
                        {
                            output.Save(sdf.FileName, ImageFormat.Jpeg);
                            break;
                        }
                    case 2:
                        {
                            output.Save(sdf.FileName, ImageFormat.Png);
                            break;
                        }
                    case 3:
                        {
                            output.Save(sdf.FileName, ImageFormat.Bmp);
                            break;
                        }
                    case 4:
                        {
                            output.Save(sdf.FileName, ImageFormat.Emf);
                            break;
                        }
                    case 5:
                        {
                            output.Save(sdf.FileName, ImageFormat.Exif);
                            break;
                        }
                    case 6:
                        {
                            output.Save(sdf.FileName, ImageFormat.Gif);
                            break;
                        }
                    case 7:
                        {
                            output.Save(sdf.FileName, ImageFormat.Icon);
                            break;
                        }
                    case 8:
                        {
                            output.Save(sdf.FileName, ImageFormat.Tiff);
                            break;
                        }
                    case 9:
                        {
                            output.Save(sdf.FileName, ImageFormat.Wmf);
                            break;
                        }
                }
                MessageBox.Show("保存成功,位置:" + sdf.FileName);
            }
        }

        //人像—酷感冷艳滤镜
        private void button4_Click(object sender, EventArgs e)
        {
            stopwatch.Restart();

            image_path = "test_img\\test01.jpg";
            pictureBox1.Image = new Bitmap(image_path);

            Mat src = Cv2.ImRead(image_path);
            Mat con = Contrast(src, 25);
            Mat lig = Lightness(con, -30);
            Mat hig = HighLight(lig, 20);
            Mat sha = Sharpen(hig, 50, 0);
            Mat sat = Saturation(sha, 20);
            result_image = ColorTemperature(hig, -40);

            double costTime = stopwatch.Elapsed.TotalMilliseconds;
            textBox1.Text = $"耗时:{costTime:F2}ms";
            pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());

        }

        //美食—鲜美滤镜
        private void button5_Click(object sender, EventArgs e)
        {

            stopwatch.Restart();

            image_path = "test_img\\test02.jpg";
            pictureBox1.Image = new Bitmap(image_path);

            Mat src = Cv2.ImRead(image_path);
            Mat sat = Saturation(src, 25);
            Mat lig = Lightness(sat, 10);
            Mat con = Contrast(lig, 30);
            Mat sha = Sharpen(con, 30, 0);
            Mat sdo = Shadow(sha, -5);
            result_image = HighLight(sdo, 15);

            double costTime = stopwatch.Elapsed.TotalMilliseconds;
            textBox1.Text = $"耗时:{costTime:F2}ms";
            pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());


        }

        //美食—巧克力滤镜
        private void button6_Click(object sender, EventArgs e)
        {
            stopwatch.Restart();

            image_path = "test_img\\test03.jpg";
            pictureBox1.Image = new Bitmap(image_path);

            Mat src = Cv2.ImRead(image_path);
            Mat sat = Saturation(src, 20);
            Mat lig = Lightness(sat, -15);
            Mat con = Contrast(lig, 35);
            Mat sha = Sharpen(con, 10, 0);
            Mat sdo = Shadow(sha, 25);
            result_image = HighLight(sdo, -5);

            double costTime = stopwatch.Elapsed.TotalMilliseconds;
            textBox1.Text = $"耗时:{costTime:F2}ms";
            pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());
        }
    }
}
 

  1. using OpenCvSharp;
  2. using System;
  3. using System.Diagnostics;
  4. using System.Drawing;
  5. using System.Drawing.Imaging;
  6. using System.Security.Cryptography;
  7. using System.Windows.Forms;
  8. namespace OpenCvSharp_Demo
  9. {
  10. public partial class Form1 : Form
  11. {
  12. public Form1()
  13. {
  14. InitializeComponent();
  15. }
  16. string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
  17. string startupPath;
  18. string image_path;
  19. Stopwatch stopwatch = new Stopwatch();
  20. Mat image;
  21. Mat result_image;
  22. private void Form1_Load(object sender, EventArgs e)
  23. {
  24. startupPath = System.Windows.Forms.Application.StartupPath;
  25. }
  26. private void button1_Click(object sender, EventArgs e)
  27. {
  28. OpenFileDialog ofd = new OpenFileDialog();
  29. ofd.Filter = fileFilter;
  30. if (ofd.ShowDialog() != DialogResult.OK) return;
  31. pictureBox1.Image = null;
  32. pictureBox2.Image = null;
  33. textBox1.Text = "";
  34. image_path = ofd.FileName;
  35. pictureBox1.Image = new Bitmap(image_path);
  36. image = new Mat(image_path);
  37. }
  38. byte max2(byte a, byte b)
  39. {
  40. return a > b ? a : b;
  41. }
  42. byte min2(byte a, byte b)
  43. {
  44. return a < b ? a : b;
  45. }
  46. byte max3(byte a, byte b, byte c)
  47. {
  48. return a > b ? max2(a, c) : max2(b, c);
  49. }
  50. byte min3(byte a, byte b, byte c)
  51. {
  52. return a < b ? min2(a, c) : min2(b, c);
  53. }
  54. /// <summary>
  55. /// 饱和度
  56. /// </summary>
  57. /// <param name="src"></param>
  58. /// <param name="percent"></param>
  59. /// <returns></returns>
  60. unsafe Mat Saturation(Mat src, int percent)
  61. {
  62. float Increment = percent * 1.0f / 100;
  63. Mat temp = src.Clone();
  64. int row = src.Rows;
  65. int col = src.Cols;
  66. for (int i = 0; i < row; ++i)
  67. {
  68. byte* t = (byte*)temp.Ptr(i);
  69. byte* s = (byte*)src.Ptr(i);
  70. for (int j = 0; j < col; ++j)
  71. {
  72. byte b = s[3 * j];
  73. byte g = s[3 * j + 1];
  74. byte r = s[3 * j + 2];
  75. float max = max3(r, g, b);
  76. float min = min3(r, g, b);
  77. float delta, value;
  78. float L, S, alpha;
  79. delta = (max - min) / 255;
  80. if (delta == 0)
  81. continue;
  82. value = (max + min) / 255;
  83. L = value / 2;
  84. if (L < 0.5)
  85. S = delta / value;
  86. else
  87. S = delta / (2 - value);
  88. if (Increment >= 0)
  89. {
  90. if ((Increment + S) >= 1)
  91. alpha = S;
  92. else
  93. alpha = 1 - Increment;
  94. alpha = 1 / alpha - 1;
  95. t[3 * j + 2] = (byte)(r + (r - L * 255) * alpha);
  96. t[3 * j + 1] = (byte)(g + (g - L * 255) * alpha);
  97. t[3 * j] = (byte)(b + (b - L * 255) * alpha);
  98. }
  99. else
  100. {
  101. alpha = Increment;
  102. t[3 * j + 2] = (byte)(L * 255 + (r - L * 255) * (1 + alpha));
  103. t[3 * j + 1] = (byte)(L * 255 + (g - L * 255) * (1 + alpha));
  104. t[3 * j] = (byte)(L * 255 + (b - L * 255) * (1 + alpha));
  105. }
  106. }
  107. }
  108. return temp;
  109. }
  110. /// <summary>
  111. /// 明度
  112. /// </summary>
  113. /// <param name="src"></param>
  114. /// <param name="percent"></param>
  115. /// <returns></returns>
  116. unsafe Mat Lightness(Mat src, float percent)
  117. {
  118. float alpha = percent / 100;
  119. alpha = Math.Max(-1.0f, Math.Min(1.0f, alpha));
  120. Mat temp = src.Clone();
  121. int row = src.Rows;
  122. int col = src.Cols;
  123. for (int i = 0; i < row; ++i)
  124. {
  125. byte* t = (byte*)temp.Ptr(i);
  126. byte* s = (byte*)src.Ptr(i);
  127. for (int j = 0; j < col; ++j)
  128. {
  129. byte b = s[3 * j];
  130. byte g = s[3 * j + 1];
  131. byte r = s[3 * j + 2];
  132. if (alpha >= 0)
  133. {
  134. t[3 * j + 2] = (byte)(r * (1 - alpha) + 255 * alpha);
  135. t[3 * j + 1] = (byte)(g * (1 - alpha) + 255 * alpha);
  136. t[3 * j] = (byte)(b * (1 - alpha) + 255 * alpha);
  137. }
  138. else
  139. {
  140. t[3 * j + 2] = (byte)(r * (1 + alpha));
  141. t[3 * j + 1] = (byte)(g * (1 + alpha));
  142. t[3 * j] = (byte)(b * (1 + alpha));
  143. }
  144. }
  145. }
  146. return temp;
  147. }
  148. /// <summary>
  149. /// 对比度
  150. /// </summary>
  151. unsafe Mat Contrast(Mat src, int percent)
  152. {
  153. float alpha = percent / 100.0f;
  154. alpha = Math.Max(-1.0f, Math.Min(1.0f, alpha));
  155. Mat temp = src.Clone();
  156. int row = src.Rows;
  157. int col = src.Cols;
  158. int thresh = 127;
  159. for (int i = 0; i < row; ++i)
  160. {
  161. byte* t = (byte*)temp.Ptr(i);
  162. byte* s = (byte*)src.Ptr(i);
  163. for (int j = 0; j < col; ++j)
  164. {
  165. byte b = s[3 * j];
  166. byte g = s[3 * j + 1];
  167. byte r = s[3 * j + 2];
  168. int newb, newg, newr;
  169. if (alpha == 1)
  170. {
  171. t[3 * j + 2] = (byte)(r > thresh ? 255 : 0);
  172. t[3 * j + 1] = (byte)(g > thresh ? 255 : 0);
  173. t[3 * j] = (byte)(b > thresh ? 255 : 0);
  174. continue;
  175. }
  176. else if (alpha >= 0)
  177. {
  178. newr = (int)(thresh + (r - thresh) / (1 - alpha));
  179. newg = (int)(thresh + (g - thresh) / (1 - alpha));
  180. newb = (int)(thresh + (b - thresh) / (1 - alpha));
  181. }
  182. else
  183. {
  184. newr = (int)(thresh + (r - thresh) * (1 + alpha));
  185. newg = (int)(thresh + (g - thresh) * (1 + alpha));
  186. newb = (int)(thresh + (b - thresh) * (1 + alpha));
  187. }
  188. newr = Math.Max(0, Math.Min(255, newr));
  189. newg = Math.Max(0, Math.Min(255, newg));
  190. newb = Math.Max(0, Math.Min(255, newb));
  191. t[3 * j + 2] = (byte)(newr);
  192. t[3 * j + 1] = (byte)(newg);
  193. t[3 * j] = (byte)(newb);
  194. }
  195. }
  196. return temp;
  197. }
  198. /// <summary>
  199. /// 图像阴影选取
  200. /// </summary>
  201. /// <param name="input"></param>
  202. /// <param name="light"></param>
  203. /// <returns></returns>
  204. unsafe Mat Shadow(Mat input, int light)
  205. {
  206. // 生成灰度图
  207. Mat gray = Mat.Zeros(input.Size(), MatType.CV_32FC1);
  208. Mat f = input.Clone();
  209. f.ConvertTo(f, MatType.CV_32FC3);
  210. Mat[] pics = new Mat[3] { new Mat(), new Mat(), new Mat() };
  211. Cv2.Split(f, out pics);
  212. gray = 0.299f * pics[2] + 0.587 * pics[1] + 0.114 * pics[0];
  213. gray = gray / 255.0f;
  214. // 确定阴影区
  215. Mat thresh = Mat.Zeros(gray.Size(), gray.Type());
  216. thresh = (1.0f - gray).Mul(1.0f - gray);
  217. // 取平均值作为阈值
  218. Scalar t = Cv2.Mean(thresh);
  219. Mat mask = Mat.Zeros(gray.Size(), MatType.CV_8UC1);
  220. mask.SetTo(new Scalar(255), thresh.GreaterThanOrEqual(t.Val0));
  221. // 参数设置
  222. int max = 4;
  223. float bright = light / 100.0f / max;
  224. float mid = 1.0f + max * bright;
  225. // 边缘平滑过渡
  226. Mat midrate = Mat.Zeros(input.Size(), MatType.CV_32FC1);
  227. Mat brightrate = Mat.Zeros(input.Size(), MatType.CV_32FC1);
  228. for (int i = 0; i < input.Rows; ++i)
  229. {
  230. byte* m = (byte*)mask.Ptr(i);
  231. float* th = (float*)thresh.Ptr(i);
  232. float* mi = (float*)midrate.Ptr(i);
  233. float* br = (float*)brightrate.Ptr(i);
  234. for (int j = 0; j < input.Cols; ++j)
  235. {
  236. if (m[j] == 255)
  237. {
  238. mi[j] = mid;
  239. br[j] = bright;
  240. }
  241. else
  242. {
  243. mi[j] = (float)((mid - 1.0f) / t[0] * th[j] + 1.0f);
  244. br[j] = (float)((1.0f / t[0] * th[j]) * bright);
  245. }
  246. }
  247. }
  248. // 阴影提亮,获取结果图
  249. Mat result = Mat.Zeros(input.Size(), input.Type());
  250. for (int i = 0; i < input.Rows; ++i)
  251. {
  252. float* mi = (float*)midrate.Ptr(i);
  253. float* br = (float*)brightrate.Ptr(i);
  254. byte* @in = (byte*)input.Ptr(i);
  255. byte* r = (byte*)result.Ptr(i);
  256. for (int j = 0; j < input.Cols; ++j)
  257. {
  258. for (int k = 0; k < 3; ++k)
  259. {
  260. float temp = (float)(Math.Pow((float)(@in[3 * j + k]) / 255.0f, 1.0f / mi[j]) * (1.0 / (1 - br[j])));
  261. if (temp > 1.0f)
  262. temp = 1.0f;
  263. if (temp < 0.0f)
  264. temp = 0.0f;
  265. byte utemp = (byte)(255 * temp);
  266. r[3 * j + k] = utemp;
  267. }
  268. }
  269. }
  270. return result;
  271. }
  272. /// <summary>
  273. /// 图像高光选取
  274. /// </summary>
  275. /// <param name="input"></param>
  276. /// <param name="light"></param>
  277. /// <returns></returns>
  278. unsafe Mat HighLight(Mat input, int light)
  279. {
  280. // 生成灰度图
  281. Mat gray = Mat.Zeros(input.Size(), MatType.CV_32FC1);
  282. Mat f = input.Clone();
  283. f.ConvertTo(f, MatType.CV_32FC3);
  284. Mat[] pics = new Mat[3] { new Mat(), new Mat(), new Mat() };
  285. Cv2.Split(f, out pics);
  286. gray = 0.299f * pics[2] + 0.587 * pics[1] + 0.114 * pics[0];
  287. gray = gray / 255.0f;
  288. // 确定高光区
  289. Mat thresh = Mat.Zeros(gray.Size(), gray.Type());
  290. thresh = gray.Mul(gray);
  291. // 取平均值作为阈值
  292. Scalar t = Cv2.Mean(thresh);
  293. Mat mask = Mat.Zeros(gray.Size(), MatType.CV_8UC1);
  294. mask.SetTo(new Scalar(255), thresh.GreaterThanOrEqual(t.Val0));
  295. // 参数设置
  296. int max = 4;
  297. float bright = light / 100.0f / max;
  298. float mid = 1.0f + max * bright;
  299. // 边缘平滑过渡
  300. Mat midrate = Mat.Zeros(input.Size(), MatType.CV_32FC1);
  301. Mat brightrate = Mat.Zeros(input.Size(), MatType.CV_32FC1);
  302. for (int i = 0; i < input.Rows; ++i)
  303. {
  304. byte* m = (byte*)mask.Ptr(i);
  305. float* th = (float*)thresh.Ptr(i);
  306. float* mi = (float*)midrate.Ptr(i);
  307. float* br = (float*)brightrate.Ptr(i);
  308. for (int j = 0; j < input.Cols; ++j)
  309. {
  310. if (m[j] == 255)
  311. {
  312. mi[j] = mid;
  313. br[j] = bright;
  314. }
  315. else
  316. {
  317. mi[j] = (float)((mid - 1.0f) / t[0] * th[j] + 1.0f);
  318. br[j] = (float)((1.0f / t[0] * th[j]) * bright);
  319. }
  320. }
  321. }
  322. // 高光提亮,获取结果图
  323. Mat result = Mat.Zeros(input.Size(), input.Type());
  324. for (int i = 0; i < input.Rows; ++i)
  325. {
  326. float* mi = (float*)midrate.Ptr(i);
  327. float* br = (float*)brightrate.Ptr(i);
  328. byte* @in = (byte*)input.Ptr(i);
  329. byte* r = (byte*)result.Ptr(i);
  330. for (int j = 0; j < input.Cols; ++j)
  331. {
  332. for (int k = 0; k < 3; ++k)
  333. {
  334. float temp = (float)(Math.Pow((float)(@in[3 * j + k]) / 255.0f, 1.0f / mi[j]) * (1.0 / (1 - br[j])));
  335. if (temp > 1.0f)
  336. temp = 1.0f;
  337. if (temp < 0.0f)
  338. temp = 0.0f;
  339. byte utemp = (byte)(255 * temp);
  340. r[3 * j + k] = utemp;
  341. }
  342. }
  343. }
  344. return result;
  345. }
  346. // 色温调节
  347. unsafe Mat ColorTemperature(Mat input, int n)
  348. {
  349. Mat result = input.Clone();
  350. int row = input.Rows;
  351. int col = input.Cols;
  352. int level = n / 2;
  353. for (int i = 0; i < row; ++i)
  354. {
  355. byte* a = (byte*)input.Ptr(i);
  356. byte* r = (byte*)result.Ptr(i);
  357. for (int j = 0; j < col; ++j)
  358. {
  359. int R, G, B;
  360. // R通道
  361. R = a[j * 3 + 2];
  362. R = R + level;
  363. if (R > 255)
  364. {
  365. r[j * 3 + 2] = 255;
  366. }
  367. else if (R < 0)
  368. {
  369. r[j * 3 + 2] = 0;
  370. }
  371. else
  372. {
  373. r[j * 3 + 2] = (byte)R;
  374. }
  375. // G通道
  376. G = a[j * 3 + 1];
  377. G = G + level;
  378. if (G > 255)
  379. {
  380. r[j * 3 + 1] = 255;
  381. }
  382. else if (G < 0)
  383. {
  384. r[j * 3 + 1] = 0;
  385. }
  386. else
  387. {
  388. r[j * 3 + 1] = (byte)G;
  389. }
  390. // B通道
  391. B = a[j * 3];
  392. B = B - level;
  393. if (B > 255)
  394. {
  395. r[j * 3] = 255;
  396. }
  397. else if (B < 0)
  398. {
  399. r[j * 3] = 0;
  400. }
  401. else
  402. {
  403. r[j * 3] = (byte)B;
  404. }
  405. }
  406. }
  407. return result;
  408. }
  409. // 图像锐化
  410. unsafe Mat Sharpen(Mat input, int percent, int type)
  411. {
  412. Mat result;
  413. Mat s = input.Clone();
  414. InputArray kernel;
  415. switch (type)
  416. {
  417. case 0:
  418. kernel =
  419. InputArray.Create<float>(new float[3, 3] {
  420. { 0, -1, 0 },
  421. { -1, 4, -1 },
  422. { 0, -1, 0 } });
  423. break;
  424. case 1:
  425. kernel =
  426. InputArray.Create<float>(new float[3, 3] {
  427. { -1, -1, -1},
  428. { -1, 8, -1 },
  429. { -1, -1, -1 } });
  430. break;
  431. default:
  432. kernel =
  433. InputArray.Create<float>(new float[3, 3] {
  434. { 0, -1, 0},
  435. { -1, 4, -1 },
  436. { 0, -1, 0 } });
  437. break;
  438. }
  439. Cv2.Filter2D(s, s, s.Depth(), kernel);
  440. result = input + s * 0.01 * percent;
  441. return result;
  442. }
  443. //天空滤镜
  444. private void button2_Click(object sender, EventArgs e)
  445. {
  446. stopwatch.Restart();
  447. image_path = "test_img\\sky.jpg";
  448. pictureBox1.Image = new Bitmap(image_path);
  449. Mat src = Cv2.ImRead(image_path);
  450. Mat sat = Saturation(src, 35);
  451. Mat lig = Lightness(sat, 20);
  452. Mat con = Contrast(lig, 15);
  453. Mat sdo = Shadow(con, 15);
  454. Mat hig = HighLight(sdo, -30);
  455. result_image = ColorTemperature(hig, -40);
  456. double costTime = stopwatch.Elapsed.TotalMilliseconds;
  457. textBox1.Text = $"耗时:{costTime:F2}ms";
  458. pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());
  459. }
  460. private void button3_Click(object sender, EventArgs e)
  461. {
  462. if (pictureBox2.Image == null)
  463. {
  464. return;
  465. }
  466. Bitmap output = new Bitmap(pictureBox2.Image);
  467. var sdf = new SaveFileDialog();
  468. sdf.Title = "保存";
  469. sdf.Filter = "Images (*.jpg)|*.jpg|Images (*.png)|*.png|Images (*.bmp)|*.bmp|Images (*.emf)|*.emf|Images (*.exif)|*.exif|Images (*.gif)|*.gif|Images (*.ico)|*.ico|Images (*.tiff)|*.tiff|Images (*.wmf)|*.wmf";
  470. if (sdf.ShowDialog() == DialogResult.OK)
  471. {
  472. switch (sdf.FilterIndex)
  473. {
  474. case 1:
  475. {
  476. output.Save(sdf.FileName, ImageFormat.Jpeg);
  477. break;
  478. }
  479. case 2:
  480. {
  481. output.Save(sdf.FileName, ImageFormat.Png);
  482. break;
  483. }
  484. case 3:
  485. {
  486. output.Save(sdf.FileName, ImageFormat.Bmp);
  487. break;
  488. }
  489. case 4:
  490. {
  491. output.Save(sdf.FileName, ImageFormat.Emf);
  492. break;
  493. }
  494. case 5:
  495. {
  496. output.Save(sdf.FileName, ImageFormat.Exif);
  497. break;
  498. }
  499. case 6:
  500. {
  501. output.Save(sdf.FileName, ImageFormat.Gif);
  502. break;
  503. }
  504. case 7:
  505. {
  506. output.Save(sdf.FileName, ImageFormat.Icon);
  507. break;
  508. }
  509. case 8:
  510. {
  511. output.Save(sdf.FileName, ImageFormat.Tiff);
  512. break;
  513. }
  514. case 9:
  515. {
  516. output.Save(sdf.FileName, ImageFormat.Wmf);
  517. break;
  518. }
  519. }
  520. MessageBox.Show("保存成功,位置:" + sdf.FileName);
  521. }
  522. }
  523. //人像—酷感冷艳滤镜
  524. private void button4_Click(object sender, EventArgs e)
  525. {
  526. stopwatch.Restart();
  527. image_path = "test_img\\test01.jpg";
  528. pictureBox1.Image = new Bitmap(image_path);
  529. Mat src = Cv2.ImRead(image_path);
  530. Mat con = Contrast(src, 25);
  531. Mat lig = Lightness(con, -30);
  532. Mat hig = HighLight(lig, 20);
  533. Mat sha = Sharpen(hig, 50, 0);
  534. Mat sat = Saturation(sha, 20);
  535. result_image = ColorTemperature(hig, -40);
  536. double costTime = stopwatch.Elapsed.TotalMilliseconds;
  537. textBox1.Text = $"耗时:{costTime:F2}ms";
  538. pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());
  539. }
  540. //美食—鲜美滤镜
  541. private void button5_Click(object sender, EventArgs e)
  542. {
  543. stopwatch.Restart();
  544. image_path = "test_img\\test02.jpg";
  545. pictureBox1.Image = new Bitmap(image_path);
  546. Mat src = Cv2.ImRead(image_path);
  547. Mat sat = Saturation(src, 25);
  548. Mat lig = Lightness(sat, 10);
  549. Mat con = Contrast(lig, 30);
  550. Mat sha = Sharpen(con, 30, 0);
  551. Mat sdo = Shadow(sha, -5);
  552. result_image = HighLight(sdo, 15);
  553. double costTime = stopwatch.Elapsed.TotalMilliseconds;
  554. textBox1.Text = $"耗时:{costTime:F2}ms";
  555. pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());
  556. }
  557. //美食—巧克力滤镜
  558. private void button6_Click(object sender, EventArgs e)
  559. {
  560. stopwatch.Restart();
  561. image_path = "test_img\\test03.jpg";
  562. pictureBox1.Image = new Bitmap(image_path);
  563. Mat src = Cv2.ImRead(image_path);
  564. Mat sat = Saturation(src, 20);
  565. Mat lig = Lightness(sat, -15);
  566. Mat con = Contrast(lig, 35);
  567. Mat sha = Sharpen(con, 10, 0);
  568. Mat sdo = Shadow(sha, 25);
  569. result_image = HighLight(sdo, -5);
  570. double costTime = stopwatch.Elapsed.TotalMilliseconds;
  571. textBox1.Text = $"耗时:{costTime:F2}ms";
  572. pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());
  573. }
  574. }
  575. }

参考 

OpenCV-美食—巧克力滤镜_opencv美食场景-CSDN博客

OpenCV-美食—鲜美滤镜_opencv实现美食滤镜—让食物更诱人-CSDN博客

OpenCV-人像—酷感冷艳滤镜_opencv和c++实现冷色调-CSDN博客

OpenCV-风景—天空滤镜_风景滤镜参数-CSDN博客

下载

源码下载

天天代码码天天
微信公众号
.NET 人工智能实践
注:本文转载自blog.csdn.net的天天代码码天天的文章"https://lw112190.blog.csdn.net/article/details/143919945"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2492) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2025 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top