OpenCvSharp 识别颜色
安装
- 新建winform程序
- 安装OpenCvSharp包
install-package OpenCvSharp4.Windows
开发
在 Form1窗体上添加一个按钮,在Click事件中添加如下代码:
public partial class Form4 : Form { public Form4() { InitializeComponent(); } private const string WINDOWS_NAME = "识别颜色"; Mat img = new Mat(); Mat mask = new Mat(); Mat hsvMat = new Mat(); private static int lowH = 98; private static int lowS = 193; private static int lowV = 0; private static int hightH = 150; private static int hightS = 255; private static int hightV = 255; private TrackbarCallbackNative callbackNative; private void button1_Click(object sender, EventArgs e) { //选择图片 OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.RestoreDirectory = true; string imgName = ""; if (openFileDialog.ShowDialog() == DialogResult.OK) { imgName = openFileDialog.FileName; } img = Cv2.ImRead(imgName, ImreadModes.AnyColor);// new Mat("",); img.Resize(new OpenCvSharp.Size(500, 500)); Cv2.CvtColor(img, hsvMat, ColorConversionCodes.BGR2HSV); onThresholdValueChange(1,img.Ptr()); callbackNative = onThresholdValueChange; Cv2.CreateTrackbar("lowH", WINDOWS_NAME, ref lowH, 255, callbackNative, img.Ptr()); Cv2.CreateTrackbar("lowS", WINDOWS_NAME, ref lowS, 255, callbackNative, img.Ptr()); Cv2.CreateTrackbar("lowV", WINDOWS_NAME, ref lowV, 255, callbackNative, img.Ptr()); Cv2.CreateTrackbar("hightH", WINDOWS_NAME, ref hightH, 255, callbackNative, img.Ptr()); Cv2.CreateTrackbar("hightS", WINDOWS_NAME, ref hightS, 255, callbackNative, img.Ptr()); Cv2.CreateTrackbar("hightV", WINDOWS_NAME, ref hightV, 255, callbackNative, img.Ptr()); } private void onThresholdValueChange(int pos, IntPtr userData) { var lowPurple = new Scalar(lowH, lowS, lowV); var highPurple = new Scalar(hightH, hightS, hightV); Cv2.InRange(hsvMat, lowPurple, highPurple, mask); var kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(20, 20), new OpenCvSharp.Point(-1, -1)); Cv2.Threshold(mask, mask, 0, 255, ThresholdTypes.Binary); //二值化 Cv2.Dilate(mask, mask, kernel); //膨胀 Cv2.Erode(mask, mask, kernel);//腐蚀 OpenCvSharp.Point[][] contours; HierarchyIndex[] hierarchy; Cv2.FindContours(mask, out contours, out 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 = img.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(153, 153, 0), 2); } Cv2.ImShow(WINDOWS_NAME, imgTar); } else { Cv2.ImShow(WINDOWS_NAME, img); } } }
效果如下:
可以把托盘中没有瓶子的 位置都给识别出来
腐蚀
我们不生产代码,我们只是代码的搬运工