C# OpenCv 证件照换底色

using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OPenCVDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //读取照片
            Mat img = Cv2.ImRead("2.png");
            Cv2.ImShow("原图.png", img);

            //图像缩放
            //Mat mg = new Mat();
            //Cv2.Resize(img, mg, new Size(200,200), 0.5, 0.5);
            //Cv2.ImShow("mg.png", mg);

            //图片转换为灰度图
            Mat hsv = new Mat();
            Cv2.CvtColor(img, hsv, ColorConversionCodes.BGR2HSV);
            Cv2.ImShow("hsv.png", hsv);

            //var channels = Cv2.Split(hsv);
            //Cv2.ImShow("B", channels[0]);
            //Cv2.ImShow("G", channels[1]);
            //Cv2.ImShow("R", channels[2]);

            //图片的二值化处理
            Mat mask = new Mat();
            Scalar lower_blue = new Scalar(90, 70, 70);
            Scalar upper_blue = new Scalar(110, 255, 255);
            Cv2.InRange(hsv, lower_blue, upper_blue, mask);
            Cv2.ImShow("mask.png", mask);

            //腐蚀膨胀
            Mat erode = new Mat();
            Cv2.Erode(mask, erode, 1);

            Mat dilate = new Mat();
            Cv2.Erode(erode, dilate, 1);
            Cv2.ImShow("dilate.png", dilate);

            for (int r = 0; r < img.Rows; r++)
            {
                for (int c = 0; c < img.Cols; c++)
                {
                    if (dilate.At(r, c) == 255)
                    {
                        Vec3b vec3B = dilate.At(r, c);
                        //此处替换颜色,为BGR通道,不是RGB通道
                        vec3B.Item0 = 255;
                        vec3B.Item1 = 255;
                        vec3B.Item2 = 255;

                        img.Set(r, c, vec3B);
                    }
                }
            }
            Cv2.ImShow("白底.png", img);

            //窗口等待的命令,0表示无限等待
            Cv2.WaitKey(0);
        }
    }
}

C# OpenCv 证件照换底色_第1张图片

附件下载

你可能感兴趣的:(C#,opencv,c#,人工智能,C#,证件照换底色)