OpenCvSharp颜色识别(用Winform实现)

OpenCvSharp颜色识别流程为:

  1. 读取RGB图片
  2. 转化为HSV模型
  3. 输入识别颜色的HSV范围,使用InRange函数进行颜色识别
  4. 图像处理,将识别区域突出显示

界面设计:

OpenCvSharp颜色识别(用Winform实现)

核心代码:

        private Bitmap _ShowHsvProcess(string path,int hMin,int hMax,int sMin,int sMax,int vMin,int vMax)
        {
            Mat src = new Mat(path, ImreadModes.AnyColor);
            Mat hsv = new Mat();
            Cv2.CvtColor(src, hsv, ColorConversionCodes.BGR2HSV);       //转化为HSV

            Mat dst = new Mat();
            Scalar scL = new Scalar(hMin, sMin, vMin);
            Scalar scH = new Scalar(hMax, sMax, vMax);
            Cv2.InRange(hsv, scL, scH, dst);                            //获取HSV处理图片
            var kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(20, 20),
               new OpenCvSharp.Point(-1, -1));
            Cv2.Threshold(dst, dst, 0, 255, ThresholdTypes.Binary);         //二值化
            Cv2.Dilate(dst, dst, kernel);                                   //膨胀
            Cv2.Erode(dst, dst, kernel);                                    //腐蚀
            Cv2.FindContours(dst, out OpenCvSharp.Point[][] contours, out HierarchyIndex[] hierarchy, RetrievalModes.CComp, ContourApproximationModes.ApproxSimple, null);
            if (contours.Length > 0)
            {
                var boxes = contours.Select(Cv2.BoundingRect).Where(w => w.Height >= 10 && w.Width > 10);
                var imgTar = src.Clone();
                foreach (var rect in boxes)
                {
                    Cv2.Rectangle(imgTar, new OpenCvSharp.Point(rect.X, rect.Y), new OpenCvSharp.Point(rect.X + rect.Width, rect.Y + rect.Height), new OpenCvSharp.Scalar(0, 0, 255), 1);
                }
                Bitmap bitmap = BitmapConverter.ToBitmap(imgTar);
                return bitmap;
            }
            else
            {
                Bitmap bitmap = BitmapConverter.ToBitmap(src);
                return bitmap;
            }
        }

效果:

OpenCvSharp颜色识别(用Winform实现)

 

常见颜色的HSV取值范围
 

OpenCvSharp颜色识别(用Winform实现)

具体代码可以进下面的路径进行查看:

https://codechina.csdn.net/lmSwind/opencvsharp_project/-/tree/master/src/OpenCvSharpProject

上一篇:使用OpenCVSharp之Filter2D锐化图片


下一篇:OpenCVSharp学习笔记——环境配置