Beispiel #1
0
        static void Main(string[] args)
        {
            string name = DateTime.Now.ToString("yyyyMMddhhmmss");

            Console.WriteLine("开始生成...");

            using (VideoWriter videoWriter = new VideoWriter("c:\\test_" + name + ".avi"
                                                             , VideoWriter.FourCC('M', 'J', 'P', 'G')
                                                             , 1                          //每秒播放帧数
                                                             , new Size(800, 600), true)) //视频大小
            {
                string        filePath      = System.AppDomain.CurrentDomain.BaseDirectory;
                DirectoryInfo directoryInfo = new DirectoryInfo(filePath + "\\image");

                var filePathList = directoryInfo.GetFiles();

                foreach (var item in filePathList)
                {
                    Mat tempCCv = Cv2.ImRead(item.FullName);
                    Mat result  = new Mat();
                    Cv2.Resize(tempCCv, result, new Size(800, 600));//必须将图片的大小调整为视频的大小
                    //插入4帧相同的图片
                    videoWriter.Write(result);
                    videoWriter.Write(result);
                    videoWriter.Write(result);
                    videoWriter.Write(result);
                }
                videoWriter.Release();
                Cv2.DestroyAllWindows();
            }

            Console.Write("生成完成!路径c:\\test_" + name + ".avi,建议使用Windows Media Player播放");
            Console.Read();
        }
        public void WriteAndCapture()
        {
            using var image = Image("lenna.png");

            {
                using var writer = new VideoWriter("dummy1.avi", FourCCValues.MJPG, 10, image.Size());
                Assert.True(writer.IsOpened());
                writer.Write(image);
                writer.Write(image);
                writer.Write(image);
            }

            using var capture = new VideoCapture("dummy1.avi");
            Assert.True(capture.IsOpened());
            Assert.Equal("CV_MJPEG", capture.GetBackendName());
            Assert.Equal(3, capture.FrameCount);

            using var frame1 = new Mat();
            using var frame2 = new Mat();
            using var frame3 = new Mat();
            using var frame4 = new Mat();
            Assert.True(capture.Read(frame1));
            Assert.True(capture.Read(frame2));
            Assert.True(capture.Read(frame3));
            Assert.False(capture.Read(frame4));
            Assert.False(frame1.Empty());
            Assert.False(frame2.Empty());
            Assert.False(frame3.Empty());
            Assert.True(frame4.Empty());

            Assert.Equal(image.Size(), frame1.Size());
        }
Beispiel #3
0
        public void SaveVideo(int TimeLength)
        {
            List <Mat> frames = new List <Mat>();
            var        size   = new Size(640, 480);

            var start = DateTime.Now;

            while ((DateTime.Now - start).TotalMilliseconds < TimeLength / 2)
            {
                var mat = new Mat();
                if (capture.Read(mat))
                {
                    mat = mat.Resize(size);
                    frames.Add(mat);
                    System.Threading.Thread.Sleep(1);
                }
            }

            var frame_rate = frames.Count;
            var fmt        = VideoWriter.FourCC('m', 'p', '4', 'v');
            var writer     = new VideoWriter(VIDEOFILE_NAME, fmt, frame_rate, size);

            for (int i = 0; i < frames.Count; i++)
            {
                writer.Write(frames[i].Clone());
            }
            for (int i = frames.Count - 1; i >= 0; i--)
            {
                writer.Write(frames[i].Clone());
            }
            writer.Release();
        }
Beispiel #4
0
        /// <summary>
        /// Save a stream of image frames as an AVI video file.
        /// </summary>
        /// <param name="frames">Ordered list of frames at 30 fps.</param>
        /// <param name="width">Frame width.</param>
        /// <param name="height">Frame height.</param>
        /// <param name="file">Output filename.</param>
        public static void SaveAsAvi(List <Color[]> frames, int width, int height, string file)
        {
            if (frames.Count == 0)
            {
                return;
            }

            using (VideoWriter writer = new VideoWriter(file, new Size(width, height),
                                                        30, true, VideoCodec.FromName("MJPG"))) {
                writer.Open();

                foreach (Color[] frame in frames)
                {
                    Bgr <byte>[,] bitmap = new Bgr <byte> [height, width];

                    int h = 0;
                    for (int k = 0; k < height; k++)
                    {
                        for (int i = 0; i < width; i++)
                        {
                            bitmap[k, i] = new Bgr <byte>(frame[h].B, frame[h].G, frame[h].R);
                            h++;
                        }
                    }

                    writer.Write(bitmap.Lock());
                }

                writer.Close();
            }
        }
Beispiel #5
0
        private static void show_image_cv(Image p, string name)
        {
            int   x, y, k;
            Image copy = new Image(p);

            constrain_image(copy);
            if (p.C == 3)
            {
                rgbgr_image(copy);
            }

            string buff = name;

            using (Mat disp = copy.ToMat())
            {
                ImageViewer.Show(disp, buff);

                Size size = new Size(disp.Width, disp.Height);

                if (outputVideo == null)
                {
                    Console.WriteLine($"\n SRC output_video = {outputVideo} ");
                    string outputName = "test_dnn_out.avi";
                    outputVideo = new VideoWriter(outputName, 25, size, true);
                    Console.WriteLine($"\n cvCreateVideoWriter, DST output_video = {outputVideo} ");
                }

                outputVideo.Write(disp);
            }

            Console.WriteLine("\n cvWriteFrame \n");
        }
Beispiel #6
0
 private bool WaitCancel(bool frg)
 {
     Invoke((MethodInvoker) delegate
     {
         Mat VF = Fr.Clone();
         if (frg)
         {
             pictureBox1.Image = BitmapConverter.ToBitmap(Fr);
             if (RecFrg)
             {
                 VW.Write(VF);
             }
             else if (VW != null && VW.IsOpened())
             {
                 VW.Release();
             }
             pictureBox1.Refresh();
         }
     });
     if (frg)
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Beispiel #7
0
        public static void WriteVideo(string path)
        {
            var viewer = new ImageViewer();

            int counter = 0;

            const int fps = 24;

            Task.Run(() =>
            {
                using (var capture = new Capture())
                {
                    var frameWidth  = (int)capture.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameWidth);
                    var frameHeight = (int)capture.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameHeight);

                    using (var writer = new VideoWriter(path, -1, fps, new Size(frameWidth, frameHeight), true))
                    {
                        while (true)
                        {
                            var frame    = capture.QueryFrame();
                            viewer.Image = frame;
                            writer.Write(frame);

                            counter++;
                        }
                    }
                }
            });

            viewer.ShowDialog();
        }
Beispiel #8
0
        public void Combine(int origin1_start, int origin1_count)
        {
            if (mode != 2)
            {
                return;
            }
            cap1.SetCaptureProperty(CapProp.PosFrames, origin1_start);

            Mat mat = new Mat();

            writer = new VideoWriter(filename_dest, -1, (int)fps1, new Size(cap1.Width, cap1.Height), true);
            //第一个文件
            if (!writer.IsOpened)
            {
                return;
            }

            for (int i = 0; i < origin1_count; i++)
            {
                mat = cap1.QueryFrame();
                if (mat.IsEmpty)
                {
                    break;
                }
                writer.Write(mat);

                mat.Dispose();
            }


            writer.Dispose();
        }
Beispiel #9
0
        public void TrackRedVedio(String videoFile, String outputFile, String targetFile)
        {
            VideoCapture capture = new VideoCapture(videoFile);
            Mat          image   = new Mat();

            OpenCvSharp.CPlusPlus.Size dsize = new OpenCvSharp.CPlusPlus.Size(capture.FrameWidth, capture.FrameHeight);
            VideoWriter   writer             = new VideoWriter(outputFile, FourCC.MJPG, fps, dsize, true);
            int           k          = 0;
            List <string> targetList = new List <string>();

            while (capture.Read(image))
            {
                if (k % 1 == 0)
                {
                    double[] target;
                    Mat      res = TrackR(image, out target);
                    writer.Write(res);
                    targetList.Add(k + " " + target[0] + " " + target[1]);
                }

                k++;
                // if (k == 100)
                //   break;
            }
            ;
            writer.Release();
            Console.WriteLine(k);
            IOTools.WriteListToTxt(targetList, targetFile);
        }
        private void ProcessFrame(object sender, EventArgs e)
        {
            D_updateMsg MyUpdateLb    = new D_updateMsg(updateLabel);
            D_updateMsg MyUpdateTrack = new D_updateMsg(updateTrackBar);

            Mat frame = new Mat();


            cap.Retrieve(frame);
            currentPos = cap.GetCaptureProperty(CapProp.PosFrames);
            this.BeginInvoke(MyUpdateLb, currentPos);
            this.BeginInvoke(MyUpdateTrack, currentPos);
            // draw fps string
            if (rendering)
            {
                CvInvoke.PutText(frame, currentPos.ToString(), textLoc, FontFace.HersheySimplex, 1.5, textColor, 3);
                vw.Write(frame);
                imageBox1.Image = frame;
            }
            else
            {
                imageBox1.Image = frame;
            }

            //delay
            System.Threading.Thread.Sleep(frameDelay);
            Application.DoEvents();
            capNum += 1;
            if (capNum >= 4)
            {
                GC.Collect();
                capNum = 0;
            }
        }
Beispiel #11
0
        static void Main()
        {
            //var reader = new CameraCapture(0); //capture from camera
            var reader = new FileCapture(Path.Combine(getResourceDir(), "Welcome.mp4"));

            reader.Open();

            var writer = new VideoWriter(@"output.avi", reader.FrameSize, /*reader.FrameRate does not work Cameras*/ 30); //TODO: bug: FPS does not work for cameras

            writer.Open();

            Bgr <byte>[,] frame = null;
            do
            {
                reader.ReadTo(ref frame);
                if (frame == null)
                {
                    break;
                }

                using (var uFrame = frame.Lock())
                { writer.Write(uFrame); }

                frame.Show(scaleForm: true);
            }while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape));

            reader.Dispose();
            writer.Dispose();

            UI.CloseAll();
        }
Beispiel #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="path"></param>
        /// <param name="angle"></param>
        /// <param name="outpath"></param>
        /// <param name="mode360"></param>
        public static void saveFisheyeMovie2equirectangular(string path, int angle, string outpath, bool mode360)
        {
            var video = new VideoCapture(path);
            var size  = new Size();
            var len   = video.FrameHeight > video.FrameWidth ? video.FrameHeight : video.FrameWidth;

            size.Height = len;
            size.Width  = mode360 ? len * 2 : len;
            var writer = new VideoWriter(outpath, FourCC.H264, video.Fps, size);
            var matrix = findCorrespondingFisheyePointMatrix(len, angle);

            while (video.IsOpened())
            {
                var frame = new Mat();
                if (video.Read(frame))
                {
                    //var f = fisheye2equirectangular(frame, angle, mode360);
                    var f = fisheye2equirectangular(frame, len, mode360, matrix);
                    // 変換して書き込み
                    writer.Write(frame);
                }
                else
                {
                    break;
                }
                frame.Dispose();
            }
            video.Dispose();
            writer.Dispose();
        }
        private void M_capture_ImageGrabbed(object sender, EventArgs e)
        {
            Console.WriteLine("test: " + startIndex.ToString());
            startIndex++;


            if (fileChanged)
            {
                nameofRecording = nameofrecord_textbox.Text;
                destin          = directorytosave_textbox.Text;

                totalFrames = m_capture.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameCount);
                fps         = m_capture.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.Fps);
                int    fourcc      = Convert.ToInt32(m_capture.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.FourCC));
                int    frameHeight = Convert.ToInt32(m_capture.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameHeight));
                int    frameWidth  = Convert.ToInt32(m_capture.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameWidth));
                string destination = destin + nameofRecording + ".avi";
                videoWriter = new VideoWriter(destination, VideoWriter.Fourcc('I', 'Y', 'U', 'V'), fps, new System.Drawing.Size(frameWidth, frameHeight), true);
                fileChanged = false;
            }


            Mat m = new Mat();

            m_capture.Retrieve(m);
            // pictureBox1.Image = m.ToImage<Bgr, byte>().Bitmap;
            videoWriter.Write(m);



            //throw new NotImplementedException();
        }
        private static async Task RecordVideo(string videoname, int seconds)
        {
            VideoWriter writer = null;

            try
            {
                await Task.Delay(seconds * 1000);

                writer = new VideoWriter(videoname, VideoWriter.FourCC('M', 'J', 'P', 'G'), _fps, new Size(CAPTUREWIDTH, CAPTUREHEIGHT), true);

                lock (frameLoker)
                {
                    LogUtil.Log($"start write buffer", LogLevel.Info);

                    foreach (var buffer in matBuffer)
                    {
                        writer.Write(buffer);
                    }
                }

                LogUtil.Log($"{videoname} Record {seconds} seconds finished", LogLevel.Info);
            }
            catch (Exception e)
            {
                LogUtil.LogException(e);
            }

            finally
            {
                if (writer != null)
                {
                    writer.Dispose();
                }
            }
        }
Beispiel #15
0
        public void Write(Mat frame)
        {
            string      path    = "C:\\Users\\Public\\Desktop\\1.avi";
            VideoWriter _Wvideo = new VideoWriter(path, VideoWriter.Fourcc('M', 'J', 'P', 'G'), 25, frame.Size, true);

            _Wvideo.Write(frame);
        }
Beispiel #16
0
        void generateVideo(string path, string filename)
        {
            int i   = -1;
            var fcc = VideoWriter.Fourcc('m', 'p', '4', 'v');

            Stopwatch watch = new Stopwatch();

            watch.Start();
            using (var video = new VideoCapture(path))
                using (var writer = new VideoWriter(@$ "{filename}.mp4", fcc, video.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.Fps) / FRAMES,
                                                    new Size((int)video.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameWidth), (int)video.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameHeight)), true))
                    using (var img = new Mat()) {
                        while (video.Grab())
                        {
                            if (++i % FRAMES == 0)
                            {
                                video.Read(img);
                                Bitmap            bmp   = new Bitmap(convertIntoAscii(img.ToBitmap()), (int)video.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameWidth), (int)video.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameHeight));
                                Image <Bgr, byte> frame = bmp.ToImage <Bgr, byte>();
                                writer.Write(frame.Mat);
                            }
                        }
                    }
            watch.Stop();
            Console.WriteLine($"\u001b[36mTime: {watch.ElapsedMilliseconds/60} sec.\u001b[0m");
        }
        private void writeVideoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (capture == null)
            {
                return;
            }
            int               fourcc          = Convert.ToInt32(capture.GetCaptureProperty(CapProp.FourCC));
            int               weidht          = Convert.ToInt32(capture.GetCaptureProperty(CapProp.FrameWidth));
            int               height          = Convert.ToInt32(capture.GetCaptureProperty(CapProp.FrameHeight));
            string            destinationPath = @"C:\Video\out.mp4";
            VideoWriter       writer          = new VideoWriter(destinationPath, fourcc, fps, new Size(weidht, height), true);
            Image <Bgr, byte> logo            = new Image <Bgr, byte>("C:\\Pictures\\3.jpg");
            Mat               m = new Mat();

            while (frameN < 500)
            {
                capture.Read(m);
                //add logo part
                Image <Bgr, byte> img = m.ToImage <Bgr, byte>();
                img.ROI = new Rectangle(0, 0, logo.Width, logo.Height);
                logo.CopyTo(img);
                img.ROI = Rectangle.Empty;
                //
                writer.Write(img.Mat);
                frameN++;
            }
            if (writer.IsOpened)
            {
                writer.Dispose();
            }
            MessageBox.Show("Complited.");
        }
Beispiel #18
0
        private void CaptureCameraCallback()
        {
            frame = new Mat();
            if (string.IsNullOrEmpty(_videoFile))
            {
                capture = new VideoCapture();
                capture.Open(_camera);
            }
            else
            {
                capture = new VideoCapture(_videoFile);
            }
            videoWriter = new VideoWriter(_outputVideoFile, FourCC.XVID, 5 /*capture.Fps*/, new OpenCvSharp.Size(capture.FrameWidth, capture.FrameHeight));

            while (isCameraRunning == true)
            {
                bool result = capture.Read(frame);
                if (result)
                {
                    aiMetrics.Start();
                    detector.Analyze(frame);
                    aiMetrics.Finish();
                    AIMetrics = aiMetrics.LastDurationMS.ToString();
                    videoWriter.Write(frame);
                    image            = BitmapConverter.ToBitmap(frame);
                    videoImage.Image = image;
                    image            = null;
                }
            }
            videoWriter.Release();
            capture.Release();
            AIMetrics = aiMetrics.AverageDurationMS.ToString();
        }
Beispiel #19
0
        public void Process(string outputFilePath, double reductionCoefficient, FrameAction frameAction)
        {
            // TODO: Multithreaded option

            var resultingSize = new Size((int)(FrameSize.Width * reductionCoefficient), (int)(FrameSize.Height * reductionCoefficient));

            var frameNumber   = 0;
            var tempFramePath = Path.Combine(Path.GetTempPath(), "tempframe.png");

            using (var videoWriter = new VideoWriter(outputFilePath, -1, (int)Fps, resultingSize, true))
            {
                var continueWorking = true;
                while (continueWorking)
                {
                    frameNumber++;

                    var frame = new Mat();
                    VideoSource.Read(frame);

                    if (frame.IsEmpty)
                    {
                        break;
                    }

                    var scaledFrame = ApplyLiquidRescale(frame, resultingSize, tempFramePath);
                    frame.Dispose();

                    continueWorking = frameAction(scaledFrame.Bitmap, frameNumber);

                    videoWriter.Write(scaledFrame);
                    scaledFrame.Dispose();
                }
            }
        }
Beispiel #20
0
 protected override void WriteFrame(object sender, ElapsedEventArgs e)
 {
     isBusy = true;
     try
     {
         //WriteLog("WriteFrame");
         Mat image = Read();
         if (image != null)
         {
             //WriteLog("  image");
             //if (lastFrame != null) { lastFrame.Dispose(); }
             //lastFrame = image;
             videoWriter.Write(image);
             image.Dispose();
         }
         else
         {
             WriteLog("VideoOutputStream#WriteFrame: Skip");
         }
     }
     catch (Exception ex)
     {
         WriteLog(ex.Message);
     }
     finally
     {
         isBusy = false;
     }
 }
        public void ProcessFrame(object sender, EventArgs arg)
        {
            try
            {
                if (_capture != null)
                {
                    _capture.Retrieve(frame, 0);//1检索frame
                    captureImageBox.Image = frame;
                }
                this.Invoke(new Action(() =>
                {
                    textBox1.Text = frame.Size.Height.ToString();
                    textBox2.Text = frame.Size.Width.ToString();
                    //textBox3.Text = frame.GetType().ToString();
                }));

                if (recordflag)
                {
                    vw.Write(frame);
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }
        }
Beispiel #22
0
        private static String GetVideoIOInfo()
        {
            String outText = String.Empty;
            int    width   = 640;
            int    height  = 480;

            using (VideoWriter writer = new VideoWriter("out.avi", VideoWriter.Fourcc('M', 'J', 'P', 'G'), 5, new Size(width, height), true))
            {
                for (int i = 0; i < 10; i++)
                {
                    using (Mat m = new Mat(width, height, DepthType.Cv8U, 3))
                    {
                        writer.Write(m);
                    }
                }
                outText += "Video written to out.avi" + Environment.NewLine;
            }
            using (VideoCapture capture = new VideoCapture("out.avi"))
            {
                Mat img2  = capture.QueryFrame();
                int count = 0;
                while (img2 != null && !img2.IsEmpty)
                {
                    img2.Dispose();
                    img2 = capture.QueryFrame();
                    count++;
                }
                outText += "Video read from out.avi" + Environment.NewLine;
            }

            return(outText);
        }
Beispiel #23
0
        private void ProcessFrame(object sender, EventArgs arg)
        {
            if (_capture0 != null && _capture0.Ptr != IntPtr.Zero)
            {
                _capture0.Retrieve(_frame0, 0);

                CvInvoke.CvtColor(_frame0, _grayFrame, ColorConversion.Bgr2Gray);

                CvInvoke.PyrDown(_grayFrame, _smallGrayFrame);

                CvInvoke.PyrUp(_smallGrayFrame, _smoothedGrayFrame);

                CvInvoke.Canny(_smoothedGrayFrame, _cannyFrame, 100, 60);

                captureImageBox.Image = _frame0;
                //grayscaleImageBox.Image = _grayFrame;
                smoothedGrayscaleImageBox.Image = _smoothedGrayFrame;
                cannyImageBox.Image             = _cannyFrame;

                ILog log = log4net.LogManager.GetLogger("visClient.Logging");
                log.Info(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "frame0 captured");

                if (flag)
                {
                    vw.Write(_frame0);
                    log.Info(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "video writing...");
                }
            }
        }
Beispiel #24
0
        static void Main()
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            Environment.SetEnvironmentVariable("PATH", Environment.GetEnvironmentVariable("PATH") + ";runtimes/win10-x64/"); //only needed if projects are directly referenced

            //var reader = new CameraCapture(0); //capture from camera
            var reader = new FileCapture(Path.Combine(getResourceDir(), "Welcome.mp4"));

            reader.Open();

            var writer = new VideoWriter(@"output.avi", reader.FrameSize, /*reader.FrameRate does not work Cameras*/ 30); //TODO: bug: FPS does not work for cameras

            writer.Open();

            Bgr <byte>[,] frame = null;
            do
            {
                reader.ReadTo(ref frame);
                if (frame == null)
                {
                    break;
                }

                using (var uFrame = frame.Lock())
                { writer.Write(uFrame); }

                frame.Show(autoSize: true);
            }while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape));

            reader.Dispose();
            writer.Dispose();

            ImageUI.CloseAll();
        }
Beispiel #25
0
        /// <summary>
        /// 获取图像
        /// </summary>
        public void Cap_Run(object o)
        {
            VideoCapture cap       = new VideoCapture(Path);
            VideoWriter  output    = new VideoWriter();
            int          videoW    = (int)cap.Get(CaptureProperty.FrameHeight);
            int          videoH    = (int)cap.Get(CaptureProperty.FrameHeight);
            int          fps       = (int)cap.Get(CaptureProperty.Fps);
            Size         videosize = new Size(videoW, videoH);

            output.Open("demo.avi", FourCC.MJPG, fps, videosize);

            while (true)
            {
                cap.Read(Source);
                output.Write(Source);
                //Source.ImWrite("D:\\Show me your Code\\GitHub仓库\\My-ROV-Project\\temp.jpg");
                if (Isopen == 0)
                {
                    break;
                }
                try
                {
                    (this.Owner as MainForm).PicBox_Video.Image = BitmapConverter.ToBitmap(Source);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
            if (Isopen == 0)
            {
                this.th.Abort();
            }
        }
Beispiel #26
0
 private void AddFrameToVideo(object sender, EventArgs e)
 {
     if (videoWriter.IsOpened && !debugMode)
     {
         videoWriter.Write(frame);
     }
 }
        public static void WriteVideo()
        {
            Size dsize = new Size(640, 480);

            // Opens a camera device
            using (VideoCapture capture = new VideoCapture(0))
                // Read movie frames and write them to VideoWriter
                using (VideoWriter writer = new VideoWriter("out.avi", -1, capture.Fps, dsize))
                    using (Mat frame = new Mat())
                        using (Mat gray = new Mat())
                            using (Mat canny = new Mat())
                                using (Mat dst = new Mat())
                                {
                                    Console.WriteLine("Converting each movie frames...");
                                    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
                                        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);
                                    }
                                }
        }
Beispiel #28
0
 private void ProcessVideo(VideoWriter vw, Mat frame)
 {
     if (videoInProgress)
     {
         vw.Write(frame);
     }
 }
Beispiel #29
0
        private void ProcessFrame(object sender, EventArgs arg)
        {
            if (_capture0 != null && _capture0.Ptr != IntPtr.Zero)
            {
                _capture0.Retrieve(_frame0, 0);

                CvInvoke.CvtColor(_frame0, _grayFrame, ColorConversion.Bgr2Gray);

                CvInvoke.PyrDown(_grayFrame, _smallGrayFrame);

                CvInvoke.PyrUp(_smallGrayFrame, _smoothedGrayFrame);

                CvInvoke.Canny(_smoothedGrayFrame, _cannyFrame, 100, 60);

                captureImageBox.Image = _frame0;
                //grayscaleImageBox.Image = _grayFrame;
                smoothedGrayscaleImageBox.Image = _smoothedGrayFrame;
                cannyImageBox.Image             = _cannyFrame;

                if (flag)
                {
                    vw.Write(_frame0);
                }
            }
        }
Beispiel #30
0
        public static bool ConvertJpegToAviWithOpenCV(List <string> fileLists, string filename)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            try
            {
                if (fileLists.Count == 0)
                {
                    throw new ArgumentOutOfRangeException();
                }

                (var imageWidth, var imageHeight) = GetImageSize(fileLists.First());
                using (VideoWriter cvw = new VideoWriter(filename, FourCC.MJPG, 30, new OpenCvSharp.Size(imageWidth, imageHeight)))
                {
                    foreach (var f in fileLists)
                    {
                        if (File.Exists(f))
                        {
                            using (Mat m = new Mat(f))
                            {
                                cvw.Write(m);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.ToString());
                return(false);
            }
            System.Diagnostics.Debug.WriteLine($"time: {sw.Elapsed}");
            return(true);
        }
        public void Run()
        {
            const string OutVideoFile = "out.avi";

            // Opens MP4 file (ffmpeg is probably needed)
            VideoCapture capture = new VideoCapture(FilePath.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, ColorConversion.BgrToGray);
                    Cv2.Canny(gray, canny, 100, 180);
                    Cv2.Resize(canny, dst, dsize, 0, 0, Interpolation.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);
                }
            }
        }