目录
效果
测试图片来自网络,侵权联系删除!
处理步骤
1、读取照片
2、图片转换为灰度图
3、图片的二值化处理
4、腐蚀膨胀
5、颜色替换
项目
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenCvSharp;
namespace OPenCVDemo01
{
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<byte>(r, c) == 255)
{
Vec3b vec3B = dilate.At<Vec3b>(r, c);
//此处替换颜色,为BGR通道,不是RGB通道
vec3B.Item0 = 255;
vec3B.Item1 = 255;
vec3B.Item2 = 255;
img.Set<Vec3b>(r, c, vec3B);
}
}
}
Cv2.ImShow("白底.png", img);
//窗口等待的命令,0表示无限等待
Cv2.WaitKey(0);
}
}
}