/// <summary> /// Draws all blobs to the specified image. /// </summary> /// <param name="img">The target image to be drawn.</param> public void RenderBlobs(Mat img) { if (img == null) throw new ArgumentNullException("img"); /* if (img.Empty()) throw new ArgumentException("img is empty"); if (img.Type() != MatType.CV_8UC3) throw new ArgumentException("img must be CV_8UC3");*/ if (Blobs == null || Blobs.Count == 0) throw new OpenCvSharpException("Blobs is empty"); if (Labels == null) throw new OpenCvSharpException("Labels is empty"); int height = Labels.GetLength(0); int width = Labels.GetLength(1); img.Create(new Size(width, height), MatType.CV_8UC3); Scalar[] colors = new Scalar[Blobs.Count]; colors[0] = Scalar.All(0); for (int i = 1; i < Blobs.Count; i++) { colors[i] = Scalar.RandomColor(); } using (var imgt = new MatOfByte3(img)) { var indexer = imgt.GetIndexer(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int labelValue = Labels[y, x]; indexer[y, x] = colors[labelValue].ToVec3b(); } } } }
/// <summary> /// utility function: convert one image to another with optional vertical flip /// </summary> /// <param name="src"></param> /// <param name="dst"></param> /// <param name="flags"></param> public static void ConvertImage(Mat src, Mat dst, ConvertImageModes flags = ConvertImageModes.None) { if (src == null) throw new ArgumentNullException("src"); if (dst == null) throw new ArgumentNullException("dst"); src.ThrowIfDisposed(); dst.ThrowIfDisposed(); dst.Create(src.Size(), MatType.CV_8UC3); NativeMethods.imgcodecs_cvConvertImage_Mat(src.CvPtr, dst.CvPtr, (int)flags); GC.KeepAlive(src); GC.KeepAlive(dst); }