public void Run()
        {
            Mat src = new Mat("Data/Image/shapes.png", ImreadModes.Color);
            Mat gray = src.CvtColor(ColorConversionCodes.BGR2GRAY);
            Mat binary = gray.Threshold(0, 255, ThresholdTypes.Otsu | ThresholdTypes.Binary);
            Mat labelView = src.EmptyClone();
            Mat rectView = binary.CvtColor(ColorConversionCodes.GRAY2BGR);

            ConnectedComponents cc = Cv2.ConnectedComponentsEx(binary);
            if (cc.LabelCount <= 1)
                return;

            // draw labels
            cc.RenderBlobs(labelView);

            // draw bonding boxes except background
            foreach (var blob in cc.Blobs.Skip(1))
            {
                rectView.Rectangle(blob.Rect, Scalar.Red);
            }

            // filter maximum blob
            var maxBlob = cc.GetLargestBlob();
            var filtered = new Mat();
            cc.FilterByBlob(src, filtered, maxBlob);

            using (new Window("src", src))
            using (new Window("binary", binary))
            using (new Window("labels", labelView))
            using (new Window("bonding boxes", rectView))
            using (new Window("maximum blob", filtered))
            {
                Cv2.WaitKey();
            }
        }
Example #2
1
        /// <summary>
        /// Submatrix operations
        /// </summary>
        private void SubMat()
        {
            Mat src = Cv2.ImRead(FilePath.Image.Lenna);

            // Assign small image to mat
            Mat small = new Mat();
            Cv2.Resize(src, small, new Size(100, 100));
            src[10, 110, 10, 110] = small;
            src[370, 470, 400, 500] = small.T();
            // ↑ This is same as the following:
            //small.T().CopyTo(src[370, 470, 400, 500]);

            // Get partial mat (similar to cvSetImageROI)
            Mat part = src[200, 400, 200, 360];
            // Invert partial pixel values
            Cv2.BitwiseNot(part, part);

            // Fill the region (50..100, 100..150) with color (128, 0, 0)
            part = src.SubMat(50, 100, 400, 450);
            part.SetTo(128);

            using (new Window("SubMat", src))
            {
                Cv2.WaitKey();
            }
        }
Example #3
0
        private static Mat[] SelectStitchingImages(int width, int height, int count)
        {
            Mat source = new Mat(@"Data\Image\lenna.png", ImreadModes.Color);
            Mat result = source.Clone();

            var rand = new Random();
            var mats = new List<Mat>();
            for (int i = 0; i < count; i++)
            {
                int x1 = rand.Next(source.Cols - width);
                int y1 = rand.Next(source.Rows - height);
                int x2 = x1 + width;
                int y2 = y1 + height;

                result.Line(new Point(x1, y1), new Point(x1, y2), new Scalar(0, 0, 255));
                result.Line(new Point(x1, y2), new Point(x2, y2), new Scalar(0, 0, 255));
                result.Line(new Point(x2, y2), new Point(x2, y1), new Scalar(0, 0, 255));
                result.Line(new Point(x2, y1), new Point(x1, y1), new Scalar(0, 0, 255));

                Mat m = source[new Rect(x1, y1, width, height)];
                mats.Add(m.Clone());
            }

            using (new Window(result))
            {
                Cv2.WaitKey();
            }

            return mats.ToArray();
        }
Example #4
0
        public void Run()
        {
            var gray = new Mat(FilePath.Image.Lenna, ImreadModes.GrayScale);
            var dst = new Mat(FilePath.Image.Lenna, ImreadModes.Color);

            BRISK brisk = BRISK.Create();
            KeyPoint[] keypoints = brisk.Detect(gray);

            if (keypoints != null)
            {
                var color = new Scalar(0, 255, 0);
                foreach (KeyPoint kpt in keypoints)
                {
                    float r = kpt.Size / 2;
                    Cv2.Circle(dst, kpt.Pt, (int)r, color);
                    Cv2.Line(dst, 
                        new Point2f(kpt.Pt.X + r, kpt.Pt.Y + r), 
                        new Point2f(kpt.Pt.X - r, kpt.Pt.Y - r), 
                        color);
                    Cv2.Line(dst, 
                        new Point2f(kpt.Pt.X - r, kpt.Pt.Y + r), 
                        new Point2f(kpt.Pt.X + r, kpt.Pt.Y - r), 
                        color);
                }
            }

            using (new Window("BRISK features", dst))
            {
                Cv2.WaitKey();
            }
        }
        public void Run()
        {
            var capture = new VideoCapture();
            capture.Set(CaptureProperty.FrameWidth, 640);
            capture.Set(CaptureProperty.FrameHeight, 480);
            capture.Open(-1);
            if (!capture.IsOpened())
                throw new Exception("capture initialization failed");

            var fs = FrameSource.CreateCameraSource(-1);
            var sr = SuperResolution.CreateBTVL1();
            sr.SetInput(fs);

            using (var normalWindow = new Window("normal"))
            using (var srWindow = new Window("super resolution"))
            {
                var normalFrame = new Mat();
                var srFrame = new Mat();
                while (true)
                {
                    capture.Read(normalFrame);
                    sr.NextFrame(srFrame);
                    if (normalFrame.Empty() || srFrame.Empty())
                        break;
                    normalWindow.ShowImage(normalFrame);
                    srWindow.ShowImage(srFrame);
                    Cv2.WaitKey(100);
                }
            }
        }
Example #6
0
        public void brightness(ref Mat img, double 目標)
        {
            //中心近くの9ピクセルから輝度調整

            int width = img.Width;
            int height = img.Height;
            int center_x = width / 5;
            int center_y = height / 5;

            double[] vals = new double[9];
            double average = 0;
            double diff = 0;
            var indexer = new MatOfByte3(img).GetIndexer();

            vals[0] = indexer[center_y - 10, center_x - 10].Item0; vals[3] = indexer[center_y - 10, center_x].Item0; vals[6] = indexer[center_y - 10, center_x + 10].Item0;
            vals[1] = indexer[center_y, center_x - 10].Item0; vals[4] = indexer[center_y, center_x].Item0; vals[7] = indexer[center_y, center_x + 10].Item0;
            vals[2] = indexer[center_y + 10, center_x - 10].Item0; vals[5] = indexer[center_y + 10, center_x].Item0; vals[8] = indexer[center_y + 10, center_x + 10].Item0;

            for (int num = 0; num < 9; num++) average += vals[num];
            average = average / 9.0;
            diff = 目標 - average;

            for (int x = 0; x < width; x++)
                for (int y = 0; y < height; y++)
                {
                    Vec3b color = indexer[y, x];
                    double val = color.Item0 + diff;
                    if (val > 255) color.Item0 = 255;
                    else if (val < 0) color.Item0 = 0;
                    else color.Item0 = (byte)val;
                    indexer[y, x] = color;
                }
            indexer = null;
        }
Example #7
0
 /// <summary>
 /// Adds descriptors to a training set.
 /// </summary>
 /// <param name="descriptors">descriptors Descriptors to add to a training set. Each row of the descriptors matrix is a descriptor.
 /// The training set is clustered using clustermethod to construct the vocabulary.</param>
 public void Add(Mat descriptors)
 {
     if (descriptors == null)
         throw new ArgumentNullException(nameof(descriptors));
     NativeMethods.features2d_BOWTrainer_add(ptr, descriptors.CvPtr);
     GC.KeepAlive(descriptors);
 }
        /// <summary>
        /// Filter a image with the specified label values. 
        /// </summary>
        /// <param name="src">Source image.</param>
        /// <param name="dst">Destination image.</param>
        /// <param name="labelValues">Label values.</param>
        /// <returns>Filtered image.</returns>
        public Mat FilterByLabels(Mat src, Mat dst, IEnumerable<int> labelValues)
        {
            if (src == null)
                throw new ArgumentNullException("src");
            if (dst == null)
                throw new ArgumentNullException("dst");
            if (labelValues == null)
                throw new ArgumentNullException("labelValues");
            int[] labelArray = EnumerableEx.ToArray(labelValues);
            if (labelArray.Length == 0)
                throw new ArgumentException("empty labelValues");

            foreach (int labelValue in labelArray)
            {
                if (labelValue < 0 || labelValue >= LabelCount)
                    throw new ArgumentException("0 <= x < LabelCount");
            }

            // マスク用Matを用意し、Andで切り抜く
            using (Mat mask = GetLabelMask(labelArray[0]))
            {
                for (int i = 1; i < labelArray.Length; i++)
                {
                    using (var maskI = GetLabelMask(labelArray[i]))
                    {
                        Cv2.BitwiseOr(mask, maskI, mask);
                    }
                }
                src.CopyTo(dst, mask);
                return dst;
            }
        }
Example #9
0
        private void DrawFeatures(string filename, IEnumerable<KeyPoint> keypoints)
        {
            using (var dst = new Mat(filename, ImreadModes.GrayScale))
            {
                int thickness = 2;
                foreach (KeyPoint kp in keypoints)
                {
                    float r = kp.Size/2;
                    Cv2.Circle(dst, kp.Pt, (int) r, Scalar.Red, thickness);
                    Cv2.Line(dst,
                        new Point2f(kp.Pt.X + r, kp.Pt.Y + r),
                        new Point2f(kp.Pt.X - r, kp.Pt.Y - r),
                        Scalar.Red, thickness);
                    Cv2.Line(dst,
                        new Point2f(kp.Pt.X - r, kp.Pt.Y - r),
                        new Point2f(kp.Pt.X + r, kp.Pt.Y + r),
                        Scalar.Red, thickness);
                }

                using (new Window("src w. keypoints", WindowMode.FreeRatio, dst))
                {
                    Cv2.WaitKey();
                }
            }
        }
Example #10
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="cascade"></param>
        /// <returns></returns>
        private Mat DetectFace(CascadeClassifier cascade)
        {
            Mat result;

            using (var src = new Mat(FilePath.Image.Yalta, ImreadModes.Color))
            using (var gray = new Mat())
            {
                result = src.Clone();
                Cv2.CvtColor(src, gray, ColorConversionCodes.BGR2GRAY);

                // Detect faces
                Rect[] faces = cascade.DetectMultiScale(
                    gray, 1.08, 2, HaarDetectionType.ScaleImage, new Size(30, 30));

                // Render all detected faces
                foreach (Rect face in faces)
                {
                    var center = new Point
                    {
                        X = (int)(face.X + face.Width * 0.5),
                        Y = (int)(face.Y + face.Height * 0.5)
                    };
                    var axes = new Size
                    {
                        Width = (int)(face.Width * 0.5),
                        Height = (int)(face.Height * 0.5)
                    };
                    Cv2.Ellipse(result, center, axes, 0, 0, 360, new Scalar(255, 0, 255), 4);
                }
            }
            return result;
        }
Example #11
0
        public void Run()
        {
            Mat src = new Mat(FilePath.Image.Girl, ImreadModes.Color);
            Mat dst = new Mat(FilePath.Image.Lenna, ImreadModes.Color);
            Mat src0 = src.Resize(dst.Size(), 0, 0, InterpolationFlags.Lanczos4);
            Mat mask = Mat.Zeros(src0.Size(), MatType.CV_8UC3);

            mask.Circle(200, 200, 100, Scalar.White, -1);

            Mat blend1 = new Mat();
            Mat blend2 = new Mat();
            Mat blend3 = new Mat();
            Cv2.SeamlessClone(
                src0, dst, mask, new Point(260, 270), blend1,
                SeamlessCloneMethods.NormalClone);
            Cv2.SeamlessClone(
                src0, dst, mask, new Point(260, 270), blend2,
                SeamlessCloneMethods.MonochromeTransfer);
                        Cv2.SeamlessClone(
                src0, dst, mask, new Point(260, 270), blend3,
                SeamlessCloneMethods.MixedClone);

            using (new Window("src", src0))
            using (new Window("dst", dst))
            using (new Window("mask", mask))
            using (new Window("blend NormalClone", blend1))
            using (new Window("blend MonochromeTransfer", blend2))
            using (new Window("blend MixedClone", blend3))
            {
                Cv2.WaitKey();
            }
        }
Example #12
0
        public void ToBitmapGrayScale()
        {
            Mat img = new Mat(FilePath.Image.Lenna511, ImreadModes.GrayScale); // width % 4 != 0

            Bitmap bitmap = BitmapConverter.ToBitmap(img);
            // Bitmap bitmap = img.ToBitmap();

            using (var form = new Form())
            using (var pb = new PictureBox())
            {
                pb.Image = bitmap;
                var size = new System.Drawing.Size(bitmap.Width, bitmap.Height);
                pb.ClientSize = size;
                form.ClientSize = size;
                form.Controls.Add(pb);
                form.KeyPreview = true;
                form.KeyDown += (sender, args) =>
                {
                    if (args.KeyCode.HasFlag(Keys.Enter))
                        ((Form)sender).Close();
                };
                form.Text = "Grayscale Mat to Bitmap Test";

                form.ShowDialog();
            }
        }
Example #13
0
        public void Run()
        {
            var gray = new Mat(FilePath.Image.Lenna, ImreadModes.GrayScale);
            var kaze = KAZE.Create();
            var akaze = AKAZE.Create();

            var kazeDescriptors = new Mat();
            var akazeDescriptors = new Mat();
            KeyPoint[] kazeKeyPoints = null, akazeKeyPoints = null;
            var kazeTime = MeasureTime(() =>
                kaze.DetectAndCompute(gray, null, out kazeKeyPoints, kazeDescriptors));
            var akazeTime = MeasureTime(() =>
                akaze.DetectAndCompute(gray, null, out akazeKeyPoints, akazeDescriptors));

            var dstKaze = new Mat();
            var dstAkaze = new Mat();
            Cv2.DrawKeypoints(gray, kazeKeyPoints, dstKaze);
            Cv2.DrawKeypoints(gray, akazeKeyPoints, dstAkaze);

            using (new Window(String.Format("KAZE [{0:F2}ms]", kazeTime.TotalMilliseconds), dstKaze))
            using (new Window(String.Format("AKAZE [{0:F2}ms]", akazeTime.TotalMilliseconds), dstAkaze))
            {
                Cv2.WaitKey();
            }
        }
Example #14
0
        public void Run()
        {
            Mat src = new Mat(FilePath.Image.Fruits, ImreadModes.Color);

            Mat normconv = new Mat(), recursFildered = new Mat();
            Cv2.EdgePreservingFilter(src, normconv, EdgePreservingMethods.NormconvFilter);
            Cv2.EdgePreservingFilter(src, recursFildered, EdgePreservingMethods.RecursFilter);

            Mat detailEnhance = new Mat();
            Cv2.DetailEnhance(src, detailEnhance);

            Mat pencil1 = new Mat(), pencil2 = new Mat();
            Cv2.PencilSketch(src, pencil1, pencil2);

            Mat stylized = new Mat();
            Cv2.Stylization(src, stylized);

            using (new Window("src", src))
            using (new Window("edgePreservingFilter - NormconvFilter", normconv))
            using (new Window("edgePreservingFilter - RecursFilter", recursFildered))
            using (new Window("detailEnhance", detailEnhance))
            using (new Window("pencilSketch grayscale", pencil1))
            using (new Window("pencilSketch color", pencil2))
            using (new Window("stylized", stylized))
            {
                Cv2.WaitKey();
            }
        }
Example #15
0
        private void MatchBySurf(Mat src1, Mat src2)
        {
            var gray1 = new Mat();
            var gray2 = new Mat();

            Cv2.CvtColor(src1, gray1, ColorConversionCodes.BGR2GRAY);
            Cv2.CvtColor(src2, gray2, ColorConversionCodes.BGR2GRAY);

            var surf = SURF.Create(500, 4, 2, true);

            // Detect the keypoints and generate their descriptors using SURF
            KeyPoint[] keypoints1, keypoints2;
            var descriptors1 = new MatOfFloat();
            var descriptors2 = new MatOfFloat();
            surf.Compute(gray1, null, out keypoints1, descriptors1);
            surf.Compute(gray2, null, out keypoints2, descriptors2);

            // Match descriptor vectors 
            var bfMatcher = new BFMatcher(NormTypes.L2, false);
            var flannMatcher = new FlannBasedMatcher();
            DMatch[] bfMatches = bfMatcher.Match(descriptors1, descriptors2);
            DMatch[] flannMatches = flannMatcher.Match(descriptors1, descriptors2);

            // Draw matches
            var bfView = new Mat();
            Cv2.DrawMatches(gray1, keypoints1, gray2, keypoints2, bfMatches, bfView);
            var flannView = new Mat();
            Cv2.DrawMatches(gray1, keypoints1, gray2, keypoints2, flannMatches, flannView);

            using (new Window("SURF matching (by BFMather)", WindowMode.AutoSize, bfView))
            using (new Window("SURF matching (by FlannBasedMatcher)", WindowMode.AutoSize, flannView))
            {
                Cv2.WaitKey();
            }
        }
Example #16
0
 /// <summary>
 /// 初期化
 /// </summary>
 /// <param name="image"></param>
 public MatProxy(Mat image)
 {
     using (var converted = new Mat())
     {
         Cv2.ConvertImage(image, converted);
         ImageData = converted.ToBytes(".png");
     }
 }
Example #17
0
        public void Run()
        {
            var src1 = new Mat(FilePath.Image.Match1, ImreadModes.Color);
            var src2 = new Mat(FilePath.Image.Match2, ImreadModes.Color);

            MatchBySift(src1, src2);
            MatchBySurf(src1, src2);
        }
Example #18
0
        /// <summary>
        /// カメラから画像を取得します
        /// </summary>
        /// <param name="cameraIndex"></param>
        /// <returns></returns>
        public static Mat GetCameraImage(int cameraIndex = 0)
        {
            var frame = new Mat();
            using (var capture = new VideoCapture(0))
                capture.Read(frame);

            return frame;
        }
 /// <summary>
 /// Sets a visual vocabulary.
 /// </summary>
 /// <param name="vocabulary">Vocabulary (can be trained using the inheritor of BOWTrainer ). 
 /// Each row of the vocabulary is a visual word(cluster center).</param>
 public void SetVocabulary(Mat vocabulary)
 {
     if (IsDisposed)
         throw new ObjectDisposedException(GetType().Name);
     if (vocabulary == null)
         throw new ArgumentNullException(nameof(vocabulary));
     NativeMethods.features2d_BOWImgDescriptorExtractor_setVocabulary(ptr, vocabulary.CvPtr);
     GC.KeepAlive(vocabulary);
 }
Example #20
0
        /*        public TargetDetector(string fileName)
                {
                    Cascade = new CascadeClassifier(fileName);

                    Scale = 1.04;
                    ScaleFactor = 1.3;
                    MinNeighbors = 2;
                }*/
        public TargetDetector(Mat mask)
        {
            Cascade = new CascadeClassifier(App.FaceCascadeName);
            EyeCascade = new CascadeClassifier(App.EyeCascadeName);
            SetMask(mask);

            Scale = 1.04;
            ScaleFactor = 1.3;
            MinNeighbors = 2;
        }
Example #21
0
        private IEnumerable<KeyPoint> FindFeatures_HarrisCornerDetector(string filename)
        {
            using (var src = new Mat(filename, ImreadModes.GrayScale))
            {
                // find ínteresting corners
                Point2f[] corners = src.GoodFeaturesToTrack(100, 0.01, 100, null, 15, true, 1);

                IEnumerable<KeyPoint> keypoints = corners.Select(s => new KeyPoint(s, 100));
                return keypoints;
            }
        }
Example #22
0
        /// <summary>
        /// Saves an image to a specified file.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="img">Image to be saved.</param>
        /// <param name="prms">Format-specific save parameters encoded as pairs</param>
        /// <returns></returns>
        public static bool ImWrite(string fileName, Mat img, int[] prms = null)
        {
            if (string.IsNullOrEmpty(fileName))
                throw new ArgumentNullException("fileName");
            if (img == null)
                throw new ArgumentNullException("img");
            if (prms == null)
                prms = new int[0];

            return NativeMethods.imgcodecs_imwrite(fileName, img.CvPtr, prms, prms.Length) != 0;
        }
Example #23
0
        /// <summary>
        /// Loads a multi-page image from a file. 
        /// </summary>
        /// <param name="filename">Name of file to be loaded.</param>
        /// <param name="mats">A vector of Mat objects holding each page, if more than one.</param>
        /// <param name="flags">Flag that can take values of @ref cv::ImreadModes, default with IMREAD_ANYCOLOR.</param>
        /// <returns></returns>
        public static bool ImReadMulti(string filename, out Mat[] mats, ImreadModes flags = ImreadModes.AnyColor)
        {
            if (filename == null) 
                throw new ArgumentNullException("filename");

            using (var matsVec = new VectorOfMat())
            {
                int ret = NativeMethods.imgcodecs_imreadmulti(filename, matsVec.CvPtr, (int) flags);
                mats = matsVec.ToArray();
                return ret != 0;
            }
        }
Example #24
0
        // grey scale comparison of translated image
        private void button2_Click(object sender, EventArgs e)
        {
            var src1 = new Mat(comboBox1.SelectedItem.ToString(), ImreadModes.GrayScale);
            var src2 = new Mat(comboBox2.SelectedItem.ToString(), ImreadModes.GrayScale);
            var output = new Mat();

            Cv2.Absdiff(src1, src2, output);

            using (new Window("output of abs diff", WindowMode.KeepRatio, output))
            {
                Cv2.WaitKey();
            }
        }
Example #25
0
 public static void Write(Mat image, WriteableBitmap bmp)
 {
     if (image.Rows != bmp.PixelHeight || image.Cols != bmp.PixelWidth)
     {
         Cv2.Resize(image, image, new OpenCvSharp.Size(bmp.PixelWidth, bmp.PixelHeight));
     }
     var pixels = GetPixels(image);
     var stride = image.Cols * image.ElemSize();
     bmp.WritePixels(
             new Int32Rect(0, 0, bmp.PixelWidth, bmp.PixelHeight),
             pixels,
             stride,
             0);
 }
Example #26
0
        public void Run()
        {
            // Split/Merge Test
            {
                Mat src = new Mat(FilePath.Image.Lenna, ImreadModes.Color);

                // Split each plane
                Mat[] planes;
                Cv2.Split(src, out planes);

                Cv2.ImShow("planes 0", planes[0]);
                Cv2.ImShow("planes 1", planes[1]);
                Cv2.ImShow("planes 2", planes[2]);
                Cv2.WaitKey();
                Cv2.DestroyAllWindows();

                // Invert G plane
                Cv2.BitwiseNot(planes[1], planes[1]);

                // Merge
                Mat merged = new Mat();
                Cv2.Merge(planes, merged);

                Cv2.ImShow("src", src);
                Cv2.ImShow("merged", merged);
                Cv2.WaitKey();
                Cv2.DestroyAllWindows();
            }

            // MixChannels Test
            {
                Mat rgba = new Mat(300, 300, MatType.CV_8UC4, new Scalar(50, 100, 150, 200));
                Mat bgr = new Mat(rgba.Rows, rgba.Cols, MatType.CV_8UC3);
                Mat alpha = new Mat(rgba.Rows, rgba.Cols, MatType.CV_8UC1);

                Mat[] input = { rgba };
                Mat[] output = { bgr, alpha };
                // rgba[0] -> bgr[2], rgba[1] -> bgr[1],
                // rgba[2] -> bgr[0], rgba[3] -> alpha[0]
                int[] fromTo = { 0, 2, 1, 1, 2, 0, 3, 3 };
                Cv2.MixChannels(input, output, fromTo);

                Cv2.ImShow("rgba", rgba);
                Cv2.ImShow("bgr", bgr);
                Cv2.ImShow("alpha", alpha);
                Cv2.WaitKey();
                Cv2.DestroyAllWindows();
            }
        }
Example #27
0
        /// <summary>
        /// Saves an image to a specified file.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="img">Image to be saved.</param>
        /// <param name="prms">Format-specific save parameters encoded as pairs</param>
        /// <returns></returns>
        public static bool ImWrite(string fileName, Mat img, params ImageEncodingParam[] prms)
        {
            if (prms != null)
            {
                List<int> p = new List<int>();
                foreach (ImageEncodingParam item in prms)
                {
                    p.Add((int) item.EncodingId);
                    p.Add(item.Value);
                }
                return ImWrite(fileName, img, p.ToArray());
            }

            return ImWrite(fileName, img, (int[]) null);
        }
Example #28
0
 /// <summary>
 /// Extracts MSER by C++-style code (cv::MSER)
 /// </summary>
 /// <param name="gray"></param>
 /// <param name="dst"></param>
 private void CppStyleMSER(Mat gray, Mat dst)
 {
     MSER mser = MSER.Create();
     Point[][] contours;
     Rect[] bboxes;
     mser.DetectRegions(gray, out contours, out bboxes); 
     foreach (Point[] pts in contours)
     {
         Scalar color = Scalar.RandomColor();
         foreach (Point p in pts)
         {
             dst.Circle(p, 1, color);
         }
     }
 }
Example #29
0
 /// <summary>
 /// Displays the image in the specified window
 /// </summary>
 /// <param name="winname">Name of the window.</param>
 /// <param name="mat">Image to be shown.</param>
 public static void ImShow(string winname, Mat mat)
 {
     if (string.IsNullOrEmpty(winname))
         throw new ArgumentNullException("winname");
     if (mat == null)
         throw new ArgumentNullException("mat");
     try
     {
         NativeMethods.highgui_imshow(winname, mat.CvPtr);
     }
     catch (BadImageFormatException ex)
     {
         throw PInvokeHelper.CreateException(ex);
     }
 }
Example #30
-1
        public void Run()
        {
            const string OutVideoFile = "out.avi";

            // Opens MP4 file (ffmpeg is probably needed)
            VideoCapture capture = new VideoCapture(FilePath.Movie.Bach);

            // Read movie frames and write them to VideoWriter 
            Size dsize = new Size(640, 480);
            using (VideoWriter writer = new VideoWriter(OutVideoFile, -1, capture.Fps, dsize))
            {
                Console.WriteLine("Converting each movie frames...");
                Mat frame = new Mat();
                while(true)
                {
                    // Read image
                    capture.Read(frame);
                    if(frame.Empty())
                        break;

                    Console.CursorLeft = 0;
                    Console.Write("{0} / {1}", capture.PosFrames, capture.FrameCount);

                    // grayscale -> canny -> resize
                    Mat gray = new Mat();
                    Mat canny = new Mat();
                    Mat dst = new Mat();
                    Cv2.CvtColor(frame, gray, ColorConversionCodes.BGR2GRAY);
                    Cv2.Canny(gray, canny, 100, 180);
                    Cv2.Resize(canny, dst, dsize, 0, 0, InterpolationFlags.Linear);
                    // Write mat to VideoWriter
                    writer.Write(dst);
                } 
                Console.WriteLine();
            }

            // Watch result movie
            using (VideoCapture capture2 = new VideoCapture(OutVideoFile))
            using (Window window = new Window("result"))
            {
                int sleepTime = (int)(1000 / capture.Fps);

                Mat frame = new Mat();
                while (true)
                {
                    capture2.Read(frame);
                    if(frame.Empty())
                        break;

                    window.ShowImage(frame);
                    Cv2.WaitKey(sleepTime);
                }
            }
        }