private void StopActivity()
 {
     IsActive = false;
     InternalVideoWriter?.Release();
     InternalVideoWriter?.Dispose();
     InternalVideoWriter = null;
 }
Esempio n. 2
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();
        }
Esempio n. 3
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);
        }
Esempio n. 4
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();
        }
Esempio n. 5
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();
        }
Esempio n. 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);
     }
 }
Esempio n. 7
0
        static void Main(string[] args)
        {
            VideoCapture capture     = new VideoCapture("Star.mp4");
            Mat          frame       = new Mat(new Size(capture.FrameWidth, capture.FrameHeight), MatType.CV_8UC3);
            VideoWriter  videoWriter = new VideoWriter();
            bool         isWrite     = false;

            while (true)
            {
                if (capture.PosFrames == capture.FrameCount)
                {
                    capture.Open("Star.mp4");
                }

                capture.Read(frame);
                Cv2.ImShow("VideoFrame", frame);

                int key = Cv2.WaitKey(33);
                // Ctrl + D 또는 Alt + D
                // 운영체제 별로 다를 수 있습니다.
                if (key == 4)
                {
                    videoWriter.Open("Video.avi", FourCC.XVID, 30, frame.Size(), true);
                    isWrite = true;
                }
                // Ctrl + X 또는 Alt + X
                // 운영체제 별로 다를 수 있습니다.
                else if (key == 24)
                {
                    videoWriter.Release();
                    isWrite = false;
                }
                else if (key == 'q')
                {
                    break;
                }

                if (isWrite == true)
                {
                    videoWriter.Write(frame);
                }
            }

            videoWriter.Release();
            capture.Release();
            Cv2.DestroyAllWindows();
        }
Esempio n. 8
0
 public void stopCamera()
 {
     if (capture.IsOpened())
     {
         capture.Release();
         if (cameraThread != null && cameraThread.IsAlive)
         {
             cameraThread.Abort();
             cameraThread.Join();
         }
         writer.Release();
     }
     if (writer.IsOpened())
     {
         writer.Release();
     }
 }
Esempio n. 9
0
 private void btnClose_Click(object sender, EventArgs e)
 {
     backgroundWorker1.CancelAsync();
     capture?.Dispose();
     if (videoWriter is not null)
     {
         videoWriter.Release();
         videoWriter = null;
     }
 }
Esempio n. 10
0
 private void doWork_cap(object sender, DoWorkEventArgs e)
 {
     while (!bw_cap.CancellationPending)
     {
         if (this.live) //Live Mode
         {
             this.mat_cap = new Mat();
             this.vcap.Read(this.mat_cap);
             Cv2.PutText(this.mat_cap, "CAP:" + this.currentch.ToString(), new OpenCvSharp.Point(this.w - 60, 20),
                         HersheyFonts.HersheyPlain, 1, new Scalar(0, 255, 0),
                         1, LineTypes.AntiAlias);
             if (rec && this.fcount < FLEN && this.vw != null)
             {
                 vw.Write(this.mat_cap);
             }
             else if (rec && this.fcount == FLEN)
             {
                 rec = false;
                 vw.Release();
                 bw_cap.ReportProgress(2);
             }
         }
         else // Play mode
         {
             if (!live && this.fcount < FLEN)
             {
                 this.mat_cap = new Mat();
                 this.vcap.Set(VideoCaptureProperties.PosFrames, this.fcount);
                 this.vcap.Read(this.mat_cap);
             }
             else if (!live && this.fcount == FLEN)
             {
                 this.vcap.Release();
                 this.vcap = new VideoCapture(1);
                 this.live = true;
                 bw_cap.ReportProgress(3);
             }
         }
         if (!this.mat_cap.IsDisposed && this.mat_cap.Height > 0)
         {
             this.bmp = this.mat_cap.ToBitmap();
             this.mat_cap.Dispose();
             this.fcount++;
             if (this.FPS > 0)
             {
                 System.Threading.Thread.Sleep((int)(1000 / this.FPS));
             }
             bw_cap.ReportProgress(1);
         }
     }
 }
Esempio n. 11
0
        public void DrawDLInVedio(String videoFile, String outputFile, String targetFile, String indexFile, int fileoffset, Scalar color)
        {
            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 = IOTools.ReadListFromTxt(targetFile);
            List <string> indexList  = IOTools.ReadListFromTxt(indexFile);
            int           t          = 0;
            String        status     = " ";

            while (capture.Read(image))
            {
                String[] ss = targetList[t + fileoffset].Split(' ');

                if (t < indexList.Count - 2 && k == int.Parse(indexList[t + 1]))
                {
                    t++;
                }
                Cv2.Circle(image, (int)double.Parse(ss[0]), (int)double.Parse(ss[1]), 10, color,
                           2
                           );
                // Cv2.PutText(image, status,
                //      new Point((int)double.Parse(ss[0]) - 5, (int)double.Parse(ss[1])), FontFace.Italic, 1, color, 3);
                if (t > 5)
                {
                    String[] ssPre = targetList[t + fileoffset - 5].Split(' ');
                    if (double.Parse(ss[1]) - double.Parse(ssPre[1]) < -25)
                    {
                        status = "Pick Up";
                    }

                    else if (double.Parse(ss[1]) - double.Parse(ssPre[1]) > 30)
                    {
                        status = "Put Down";
                    }
                    else if (Math.Abs(double.Parse(ss[1]) - double.Parse(targetList[fileoffset].Split(' ')[1])) < 10)
                    {
                        status = " ";
                    }
                }
                //if (double.Parse(ss[1]) < 420)

                writer.Write(image);
                k++;
            }
            ;
            writer.Release();
        }
Esempio n. 12
0
        private void DisposeCaptureResources()
        {
            if (capture != null)
            {
                capture.Release();
                capture.Dispose();
            }

            if (outputVideo != null)
            {
                outputVideo.Release();
                outputVideo.Dispose();
            }
        }
Esempio n. 13
0
 protected override void Dispose(bool disposing)
 {
     try
     {
         base.Dispose(disposing);
         if (videoWriter != null && !videoWriter.IsDisposed)
         {
             videoWriter.Release();
             videoWriter.Dispose();
         }
     }
     catch (Exception ex)
     {
         WriteLog(ex.Message);
     }
 }
Esempio n. 14
0
        public string Encode()
        {
            VideoWriter writer = new VideoWriter(Filename, "mp4v", Framerate, SceneSize);

            Console.WriteLine("[x] closing a new video file {0}", Filename);

            foreach (var frame in PreWrittenMats)
            {
                writer.Write(frame);
            }

            writer.Release();
            PreWrittenMats.Clear();

            return(Filename);
        }
Esempio n. 15
0
        public static void SoVüStricherln()
        {
            var r = new Random();

            var maxdim = 1024;

            var m = new Mat(maxdim, maxdim, MatType.CV_16SC4);

            var vw = new VideoWriter();

            vw.Open("video.avi", FourCC.Prompt, 29, m.Size(), true);

            Scalar color = new Scalar(10000d, 10000d, 0d, 0d);

            var colorchangeconst = 1000;

            Point p1 = new Point(0, 0);
            Point p2 = new Point(0, 0);

            for (int i = 0; i < 10000; i++)
            {
                var chan      = r.Next(0, 4);               // pick color channel
                var addremnum = r.Next(0, 2) == 0 ? -1 : 1; // add or remove value

                color[chan] = Math.Clamp(color[chan] + (colorchangeconst * addremnum), Int16.MinValue, Int16.MaxValue);

                p2.X = r.Next(0, maxdim);
                p2.Y = r.Next(0, maxdim);

                m.Line(p1, p2, color, 1);

                p1 = p2;

                if (i % 33 == 0)
                {
                    vw.Write(m);

                    Cv2.ImShow("sickname", m);
                    Cv2.WaitKey(10);
                }
            }

            vw.Release();

            //Cv2.ImShow("sickname", m);
            //Cv2.WaitKey();
        }
Esempio n. 16
0
        private void btnStop_Click(object sender, EventArgs e)
        ///<summary>
        /// stop button for stop running timer
        ///</summary>
        {
            btnStop.Enabled  = false;
            btnStart.Enabled = true;

            timer.Enabled = false;

            if (bSave)
            {
                saver.Release();
            }
            var liToCsv = new ListViewToCSV();

            liToCsv.listView_to_csv(listView2, "result.csv", false);
        }
Esempio n. 17
0
        public void DrawParticlesInVedio(String videoFile, String outputFile, String particlefile, String resultFile)
        {
            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   = IOTools.ReadListFromTxt(resultFile);
            List <string> particleList = IOTools.ReadListFromTxt(particlefile);
            int           t            = 0;
            String        status       = " ";

            while (capture.Read(image))
            {
                if (t >= targetList.Count)
                {
                    break;
                }
                String[] ss = targetList[t].Split(' ');


                for (int i = 0; i < 100; i++)
                {
                    String[] pp = particleList[t * 100 + i].Split(' ');
                    Cv2.Circle(image, (int)double.Parse(pp[0]), (int)double.Parse(pp[1]), 1, new Scalar(255, 0, 0),
                               2
                               );
                }
                Cv2.Circle(image, (int)double.Parse(ss[0]), (int)double.Parse(ss[1]), 10, new Scalar(255, 255, 0),
                           2
                           );
                // Cv2.PutText(image, status,
                //      new Point((int)double.Parse(ss[0]) - 5, (int)double.Parse(ss[1])), FontFace.Italic, 1, color, 3);

                //if (double.Parse(ss[1]) < 420)

                writer.Write(image);
                t++;
            }
            ;
            writer.Release();
        }
Esempio n. 18
0
 private void button_video_Click(object sender, EventArgs e)
 {
     lock (flags)
     {
         if (flags.videomode == false)
         {
             vw = new VideoWriter("../../video/" + DateTime.Now.ToString("MMdd_HH_mm_ss") + ".avi",
                                  FourCC.XVID, 10.0, flags.showSize);
             flags.videomode       = true;
             ((Button)sender).Text = "停止录像";
         }
         else
         {
             vw.Release();
             vw = null;
             flags.videomode       = false;
             ((Button)sender).Text = "开始录像";
         }
     }
 }
Esempio n. 19
0
        public MotionData AnalizeAll(Parameters para)
        {
            string     targetDir = Settings.TargetDir(para.VideoFile);
            MotionData md        = new MotionData();

            Action <object, DoWorkEventArgs> ProgressDialogDoWork = (sender, e) => {
                using (VideoWriter writer = new VideoWriter(Settings.DetectVideoname(para.VideoFile),
                                                            FourCC.MPG4, 30, output3.Size())) {
                    var bw  = sender as BackgroundWorker;
                    int num = para.EndFrame - para.StartFrame + 1;
                    for (int t = para.StartFrame; t < para.EndFrame; t++)
                    {
                        PosFrames = t;
                        var contour = GetContour(para);
                        if (contour != null)
                        {
                            TXYW txyw = DrawToOutput(contour, para);
                            md.AddRawData(txyw);
                        }
                        writer.Write(output3);
                        if (bw.CancellationPending)
                        {
                            e.Cancel = true;
                            break;
                        }
                        string message = string.Format("{0}/{1}", t - para.StartFrame, num);
                        bw.ReportProgress((int)((t - para.StartFrame) * 100 / num), message);
                    }
                    if (!e.Cancel)
                    {
                        md.UpdatePlotData();
                    }
                    writer.Release();
                }
            };

            ProgressDialog pd     = new ProgressDialog($"解析中:{para.VideoFile}", new DoWorkEventHandler(ProgressDialogDoWork));
            DialogResult   result = pd.ShowDialog();

            return(result == DialogResult.OK ? md : null);
        }
Esempio n. 20
0
 private void buttonRecord_Click(object sender, EventArgs e)
 {
     if (_videoWriter == null)
     {
         _videoWriter = new VideoWriter();
         // https://www.atmarkit.co.jp/ait/articles/1610/18/news143_2.html
         if (!_videoWriter.Open(@"C:\Users\skeiya\caps\video.mp4", FourCC.MP4V, 20.0, new OpenCvSharp.Size(WIDTH, HEIGHT)))
         {
             MessageBox.Show("hoge");
             return;
         }
         buttonRecord.Text = "停止";
     }
     else
     {
         _videoWriter.Release();
         _videoWriter.Dispose();
         _videoWriter      = null;
         buttonRecord.Text = "録画";
     }
 }
Esempio n. 21
0
        //private void buttonChangeScore_Click(object sender, EventArgs e)
        //{
        //    int AScore = (int)numericUpDownScoreA.Value;
        //    int BScore = (int)numericUpDownScoreB.Value;
        //    numericUpDownScoreA.Value = 0;
        //    numericUpDownScoreB.Value = 0;
        //    lock (game)
        //    {
        //        game.CarA.Score += AScore;
        //        game.CarB.Score += BScore;
        //    }
        //}



        private void button_video_Click(object sender, EventArgs e)
        {
            lock (flags)
            {
                if (flags.videomode == false)
                {
                    string time = DateTime.Now.ToString("MMdd_HH_mm_ss");
                    vw = new VideoWriter("../../video/" + time + ".avi",
                                         FourCC.XVID, 10.0, flags.showSize);
                    flags.videomode       = true;
                    ((Button)sender).Text = "停止录像";
                    game.FoulTimeFS       = new FileStream("../../video/" + time + ".txt", FileMode.CreateNew);
                }
                else
                {
                    vw.Release();
                    vw = null;
                    flags.videomode       = false;
                    ((Button)sender).Text = "开始录像";
                    game.FoulTimeFS       = null;
                }
            }
        }
Esempio n. 22
0
        private void ConvertButton_Click(object sender, EventArgs e)
        {
            convertButton.Enabled = false;

            notification.Text = "click convert button\n";

            // target
            file.TargetPath   = targetPath;
            notification.Text = "target path\n";

            // output
            file.OutputPath   = outputPath;
            notification.Text = "output path\n";

            // filename
            String fileName = fileNameInput.Text;

            if (fileNameInput.Equals(null))
            {
                fileName = "image";
            }

            file.FileName     = fileName;
            notification.Text = "file name\n";

            // FPS
            float fPS;

            if (imageperFrameInput.Text.Equals(null))
            {
                fPS = 5;
            }
            else
            {
                fPS = float.Parse(imageperFrameInput.Text);
            }

            file.FPS          = fPS;
            notification.Text = "fps\n";


            // output format
            String format = formatDropdown.SelectedItem.ToString().Split('(')[0];

            file.OutputFormat = "." + format;
            notification.Text = "output format : " + file.OutputFormat + "\n";

            switch (currentMode)
            {
            case (int)MODE.videotoImage:
                var capture = new VideoCapture(file.TargetPath[0]);

                // max frame
                int maxFrame = (int)Math.Round(capture.Fps / file.FPS);
                notification.Text = "videoFrame : " + capture.Fps + "\nfileFPS : " + file.FPS + "\nmaxFrame : " + maxFrame;
                if (maxFrame < 1)
                {
                    maxFrame = 1;
                }

                // size
                System.Drawing.Size size = new System.Drawing.Size();

                if (!checkBox.Checked && !widthInput.Text.Equals(null))
                {
                    size.Width = Int32.Parse(widthInput.Text);
                }
                else
                {
                    size.Width = capture.FrameWidth;
                }
                notification.Text = "width\n";

                if (!checkBox.Checked && !heightInput.Text.Equals(null))
                {
                    size.Height = Int32.Parse(heightInput.Text);
                }
                else
                {
                    size.Height = capture.FrameHeight;
                }
                notification.Text = "height\n";

                file.Size = size;

                bool flag = false;
                using (Mat image = new Mat())
                {
                    while (!flag)
                    {
                        notification.Text = "capture . . . " + count.ToString("D5");

                        for (int i = 0; i < maxFrame; i++)
                        {
                            capture.Read(image);

                            Mat resizing            = new Mat();
                            OpenCvSharp.Size resize = new OpenCvSharp.Size(file.Size.Width, file.Size.Height);
                            //Cv2.Resize(image, resizing, resize);

                            if (image.Empty())
                            {
                                flag = true;
                                break;
                            }
                            else if (i == 0)
                            {
                                //Cv2.ImWrite(@outputPath + "\\" + fileName + (++count).ToString("D5") + file.OutputFormat, resizing);
                                Cv2.ImWrite(@outputPath + "\\" + (++count).ToString("D5") + file.OutputFormat, image);
                                //samplePictureBox.Image.Save(outputPath + "\\" + fileName + (++count).ToString("D5") + ".png" , System.Drawing.Imaging.ImageFormat.Png);
                                //bitmapImage.Save(@outputPath + "\\" + fileName + count.ToString("D5") + ".bmp");
                            }
                        }

                        if (image.Empty())
                        {
                            break;
                        }
                    }
                }
                notification.Text  = "success! \n";
                notification.Text += "videoFrame : " + capture.Fps + "\nfileFPS : " + file.FPS + "\nmaxFrame : " + maxFrame;
                break;

            case (int)MODE.imagetoVideo:
                notification.Text  = "length : " + file.TargetPath.Length;
                notification.Text += "\nlink : " + @outputPath + "\\" + fileName + file.OutputFormat;
                notification.Text += "\nlink : " + file.TargetPath[3];

                // size
                System.Drawing.Size size2     = new System.Drawing.Size();
                OpenCvSharp.Size    videoSize = new OpenCvSharp.Size();

                if (!checkBox.Checked && !widthInput.Text.Equals(null))
                {
                    videoSize.Width = Int32.Parse(widthInput.Text);
                }
                else
                {
                    videoSize.Width = Cv2.ImRead(file.TargetPath[0]).Width;
                }
                notification.Text = "width\n";

                if (!checkBox.Checked && !heightInput.Text.Equals(null))
                {
                    videoSize.Height = Int32.Parse(heightInput.Text);
                }
                else
                {
                    videoSize.Height = Cv2.ImRead(file.TargetPath[0]).Height;
                }
                notification.Text = "height\n";

                size2.Width  = videoSize.Width;
                size2.Height = videoSize.Height;

                file.Size = size2;

                notification.Text = "size : " + videoSize.Width + ", " + videoSize.Height;

                VideoWriter videoWriter = new VideoWriter(@outputPath + "\\" + fileName + ".avi", FourCC.Default, file.FPS, videoSize);
                {
                    if (!videoWriter.IsOpened())
                    {
                        notification.Text = "could not open the output video file for writer\n";
                        return;
                    }

                    //videoWriter.Open(@"F:\20190709\abc.avi", "DIVX", file.FPS, videoSize);

                    notification.Text = "make video . . . ";

                    for (int i = 0; i < file.TargetPath.Length; i++)
                    {
                        Mat mat = Cv2.ImRead(file.TargetPath[i]);
                        if (mat.Empty())
                        {
                            break;
                        }

                        Mat resizing = new Mat();
                        Cv2.Resize(mat, resizing, videoSize);

                        videoWriter.Write(resizing);
                        samplePictureBox.Image = MatToBitmap(resizing);
                    }
                    videoWriter.Release();
                }
                notification.Text += "\nsuccess! \n";
                break;
            }

            convertButton.Enabled = true;
        }
Esempio n. 23
0
        private void playVideowithSaving()
        {
            Mat        save = new Mat();
            FileDialog ofd  = new SaveFileDialog();

            string imagePath;

            OpenCvSharp.FourCC codec = OpenCvSharp.FourCC.Default;
            OpenCvSharp.CvSize size;
            size.Height = input1bitmap.Height;
            size.Width  = input1bitmap.Width;


            FlowArray opticalFlow = new FlowArray();

            opticalFlow.Height   = input1bitmap.Height;
            opticalFlow.Width    = input1bitmap.Width;
            opticalFlow.Array    = new float[2][];
            opticalFlow.Array[0] = new float[opticalFlow.Width * opticalFlow.Height];
            opticalFlow.Array[1] = new float[opticalFlow.Width * opticalFlow.Height];
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                imagePath = ofd.FileName;



                videofilename = String.Format("{0}.avi", imagePath);
            }


            VideoWriter savevid = new VideoWriter();

            savevid.Open(videofilename, codec, 24, size, true);

            if (videoSelected)
            {
                while (!(image.Empty()))
                {
                    input1bitmap = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(image);
                    sw.Start();
                    for (int i = 0; i < 1; i++)
                    {
                        opticalFlow = HornSchunck.calculateOpticalFlow(input1bitmap, input2bitmap, out int k, opticalFlow);
                    }


                    OutputVideo = _CLProcessor.decorateFlowColor(input1bitmap, opticalFlow, HornSchunck.flowInterval, HornSchunck.threshold);
                    save        = OpenCvSharp.Extensions.BitmapConverter.ToMat(OutputVideo.Bitmap);

                    savevid.Write(save);
                    pictureBox4.Image.Dispose();
                    pictureBox5.Image.Dispose();

                    pictureBox4.Image = OutputVideo.Bitmap;
                    pictureBox5.Image = input1bitmap;

                    Application.DoEvents();
                    pictureBox4.Refresh();
                    pictureBox5.Refresh();
                    sw.Stop();
                    runTime        = 1 / (float)sw.Elapsed.TotalSeconds;
                    label9.Text    = String.Format("Frame rate: {0} [fps]", Convert.ToString(runTime));
                    label9.Visible = true;
                    sw.Reset();
                    input2bitmap = input1bitmap;
                    capture.Read(image);
                }
            }
            videoSelected = false;
            capture.Dispose();
            image.Dispose();
            savevid.Release();
            //savevid.Dispose();
            pictureBox4.Image.Dispose();
            pictureBox5.Image.Dispose();
        }
Esempio n. 24
0
        public static void ImmerDerNaseNach()
        {
            var lenab          = 1524;
            var strokeLen      = 5;
            var brushSize      = 20;
            var rotationfactor = 15; // neue maximale rotation in Anteilen von Kreis
            var rotation       = 1d / rotationfactor;

            var lens = Lib.SplitGolden(lenab);
            var m    = new Mat((int)lens.Y, (int)lens.X, MatType.CV_16SC4);

            var vw = new VideoWriter();

            vw.Open("video.avi", FourCC.Prompt, 29, m.Size(), true);

            Scalar color            = new Scalar(30000d, 30000d, 0, 0);
            var    colorchangeconst = 1500;

            Point p1 = new Point(lens.X / 2, lens.Y / 2);

            var r = new Random();

            // this is the direction in the circle ranging from 0 to less than 1;
            var direction = r.NextDouble();

            for (int i = 0; i < 30000; i++)
            {
                // COLOR CHANGE
                var chan      = r.Next(0, 4);               // pick color channel
                var addremnum = r.Next(0, 2) == 0 ? -1 : 1; // add or remove value
                color[chan] = Math.Clamp(color[chan] + (colorchangeconst * addremnum), Int16.MinValue, Int16.MaxValue);

                var circle = Lib.PlotCircle(p1.X, p1.Y, strokeLen);

                var newStep = circle[(int)(circle.Count * direction)];
                newStep = Lib.ContinuePointInRect((int)lens.X, (int)lens.Y, (int)newStep.X, (int)newStep.Y);

                // anmalen
                m.Circle(newStep, brushSize, color, thickness: -1);

                // weiter drehen
                var posnegativemultiplier = r.Next(0, 2) == 0 ? -1 : 1;
                direction = Lib.ContinuePointInRange(1, direction + (rotation * posnegativemultiplier));

                p1 = newStep;

                if (i % 5 == 0)
                {
                    posnegativemultiplier = r.Next(0, 2) == 0 ? -1 : 1;
                    brushSize             = Math.Clamp(brushSize + posnegativemultiplier, 5, 30);
                }

                if (i % 66 == 0)
                {
                    vw.Write(m);

                    //Cv2.ImShow("sickname2", m);
                    //Cv2.WaitKey(10);
                }
            }

            vw.Release();

            //Cv2.ImShow("sickname", m);
            //Cv2.WaitKey();
        }
Esempio n. 25
0
        internal static void SuperSchnit()
        {
            var cryzyform = 2; // 0.5,1,2,3,4

            var lp   = new ElPalletto();
            var rand = new Random();

            var brushSizeNP = new NumerPlayer(np =>
            {
                var fac = rand.Next(0, 2) == 0 ? -1 : 1;
                np.N    = Math.Clamp(np.N + (fac * rand.Next(0, 4)), 2, 37);
            });

            brushSizeNP.N = 11;

            var radiusInitNp = new NumerPlayer(np =>
            {
                var fac = rand.Next(0, 2) == 0 ? -1 : 1;
                np.N    = (int)Math.Clamp(1 + np.N + (fac * np.N * 0.1), 20d, 4000d);
            });

            radiusInitNp.N = 300;

            var r    = radiusInitNp.N;
            var quad = 0; //quadrant 0,1,2,3

            var lenab = 2000;
            var lens  = Lib.SplitGolden(lenab);
            var m     = new Mat((int)lens.Y, (int)lens.X, MatType.CV_16SC4);

            var vw = new VideoWriter();

            vw.Open("video.avi", FourCC.Prompt, 29, m.Size(), true);

            var p1 = new Point((int)lens.X / 2, (int)lens.Y / 2);

            lp._Color  = new Scalar(-20000d, 30000d, -29990d, 30000d);
            lp._Color2 = new Scalar(-20000d, 30000d, -29990d, 30000d);

            for (int i = 0; i < 1000000; i++)
            {
                if (r <= brushSizeNP.N / cryzyform)
                {
                    r         = radiusInitNp.N;
                    lp._Color = lp._Color2;

                    radiusInitNp.Kick();
                    brushSizeNP.Kick();

                    if (i % 4 == 0)
                    {
                        p1 = new Point2d(rand.Next((int)lens.X), rand.Next((int)lens.Y));
                        lp.RandomizeColorWithAlpha();
                        lp._Color2 = lp._Color;
                    }
                }

                var circle           = Lib.PlotCircle(p1.X, p1.Y, r);
                var circpixcountquad = (int)((decimal)circle.Count / 4);

                var segment = circle.GetRange(circpixcountquad * quad, circpixcountquad);

                int j = 0;
                foreach (var p in segment)
                {
                    m.Circle(p, 1, lp._Color, thickness: brushSizeNP.N);
                    lp.CCChanDir();

                    j++;
                    if (j % 150 == 0)
                    {
                        vw.Write(m);
                    }
                }

                //lp.Darken(0.1);
                var rcut = Lib.SplitGolden(r);
                r = (int)rcut.X;

                p1 = segment.LastOrDefault();

                if (quad == 0)
                {
                    p1.Y = p1.Y - r;
                }
                if (quad == 1)
                {
                    p1.X = p1.X + r;
                }
                if (quad == 2)
                {
                    p1.Y = p1.Y + r;
                }
                if (quad == 3)
                {
                    p1.X = p1.X - r;
                }

                quad = (quad + 1) % 4;

                Cv2.ImShow("supafenster", m);
                Cv2.WaitKey(1);
            }
            vw.Release();
        }
Esempio n. 26
0
        private async void BtnFile_ClickAsync(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog {
                Multiselect = false,
                Title       = "Please choose a video file:",
                Filter      = "Video File (*.mp4)|*.mp4"
            };

            if (fileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            BtnFile.Enabled = false;
            string file        = fileDialog.FileName;
            string path        = Path.GetDirectoryName(file);
            string temppath    = Path.GetTempPath();
            string filename    = Path.GetFileName(file);
            string audio       = Path.Combine(temppath, "output.mp3");
            string opencv_out  = Path.Combine(temppath, "output.mp4");
            string file_output = Path.Combine(path, "[superresolution]" + filename);
            string ffmpegPath  = ConfigurationManager.AppSettings["ffmpeg"];

            int index = 1;

            var video_in = VideoCapture.FromFile(file);

            var ffmpeg_extract = new Process();

            ffmpeg_extract.StartInfo.UseShellExecute        = false;
            ffmpeg_extract.StartInfo.RedirectStandardInput  = true;
            ffmpeg_extract.StartInfo.RedirectStandardOutput = true;
            ffmpeg_extract.StartInfo.RedirectStandardError  = true;
            ffmpeg_extract.StartInfo.CreateNoWindow         = true;
            ffmpeg_extract.StartInfo.FileName  = ffmpegPath;
            ffmpeg_extract.StartInfo.Arguments = " -i " + file + " -vn -f mp3 " + audio + " -y";
            ffmpeg_extract.Start();
            ffmpeg_extract.WaitForExit();
            if (!ffmpeg_extract.HasExited)
            {
                ffmpeg_extract.Kill();
            }

            FourCC      fourCC    = FourCC.DIVX;
            double      fps       = video_in.Fps;
            Size        dsize     = new Size(video_in.FrameWidth * 2, video_in.FrameHeight * 2);
            VideoWriter video_out = new VideoWriter(opencv_out, fourCC, fps, dsize, true);
            var         max       = video_in.FrameCount;

            progressBar1.Value   = 0;
            progressBar1.Maximum = max;

            TimeSpan interval_start = new TimeSpan(System.DateTime.Now.Ticks);

            while (video_in.IsOpened())
            {
                Mat frame_in = new Mat();
                var status   = video_in.Read(frame_in);
                if (!status)
                {
                    break;
                }
                var frame_out = await Task.Run(() => ExtractFrame(frame_in));

                video_out.Write(frame_out);
                MemoryStream ms_in    = new MemoryStream(frame_in.ToBytes());
                var          image_in = Image.FromStream(ms_in);
                PicVidIn.Image = image_in;
                MemoryStream ms_out    = new MemoryStream(frame_out.ToBytes());
                Image        image_out = Image.FromStream(ms_out);
                PicVidOut.Image = image_out;

                var percentage = Math.Round((float)index / max * 100, 2);

                TimeSpan interval_now = new TimeSpan(System.DateTime.Now.Ticks);
                TimeSpan countTime    = interval_start.Subtract(interval_now).Duration();
                int      second       = (int)(countTime.TotalSeconds / ((float)index / max));
                int      hour         = second / 3600;
                second %= 3600;
                int minute = second / 60;
                second     %= 60;
                label2.Text = index + "/" + max + " Frames  -  " + percentage + "%    Approximately " + hour + "H" + minute + "M" + second + "S Left";
                progressBar1.Value++;
                index++;
            }
            video_in.Release();
            video_out.Release();

            var ffmpeg_add = new Process();

            ffmpeg_add.StartInfo.UseShellExecute        = false;
            ffmpeg_add.StartInfo.RedirectStandardInput  = true;
            ffmpeg_add.StartInfo.RedirectStandardOutput = true;
            ffmpeg_add.StartInfo.RedirectStandardError  = true;
            ffmpeg_add.StartInfo.CreateNoWindow         = true;
            ffmpeg_add.StartInfo.FileName  = ffmpegPath;
            ffmpeg_add.StartInfo.Arguments = " -i " + opencv_out + " -i " + audio + " -c copy " + file_output;
            ffmpeg_add.Start();
            ffmpeg_add.WaitForExit();
            if (!ffmpeg_add.HasExited)
            {
                ffmpeg_add.Kill();
            }

            File.Delete(opencv_out);
            File.Delete(audio);

            MessageBox.Show("Video file \"output_" + filename + "\" saved.", "Task Finished");
            BtnFile.Enabled = true;
        }
Esempio n. 27
0
        public void recordCamera()
        {
            isRecordingCamera = true;
            int k = 0;

            Thread.Sleep(100);

            new Thread(() =>
            {
                IplImage img;
                // recordFrames.TryPeek(out img);



                OpenCvSharp.CPlusPlus.Size dsize = new OpenCvSharp.CPlusPlus.Size(cap.FrameWidth, cap.FrameHeight);
                VideoWriter writer = new VideoWriter(Conf.filepath + "1.avi", FourCC.MJPG, fps, dsize, true);
                StreamWriter sw    = new StreamWriter(Conf.filepath + "t.txt");
                while (true)
                {
                    Mat gray  = new Mat();
                    Mat canny = new Mat();
                    Mat dst   = new Mat();
                    try
                    {
                        bool suc = recordFrames.TryDequeue(out img);
                        if (suc)
                        {
                            Mat frame = new Mat(img, true);
                            string time;
                            recordTimes.TryDequeue(out time);
                            // Console.WriteLine(DateTime.Now.ToString("==yyyy-MM-dd-HH-mm-ss-fffffff"));
                            //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((frame));
                            sw.WriteLine(time);
                            k++;
                        }
                        else
                        {
                            Console.WriteLine("ffff");
                            if (isRecordingCamera == false)
                            {
                                break;
                            }
                        }


                        //stop = true;
                        Thread.Sleep(1000 / fps - 10);
                    }
                    catch (Exception e)
                    {
                        label.Content = e.ToString();
                    }
                }
                Console.WriteLine(k);
                writer.Release();
                sw.Close();
                return;
                //  writer.Dispose();
                // cap.Dispose();
            }).Start();
        }