public void write() {
            int codec = Emgu.CV.CvInvoke.CV_FOURCC('P', 'I', 'M', '1');

            int fps = 25;
            if (list_timestamps.Count > 0)
            {
                String tempvideopath = Program.getConfiguration().Mediafolderpath + @"\" + list_timestamps[0].ToString() + ".mpg";
                Capture tempcapture = new Capture(tempvideopath);
                fps = (int)tempcapture.GetCaptureProperty(CAP_PROP.CV_CAP_PROP_FPS);
                tempcapture.Dispose();
            }

            VideoWriter videowriter = new VideoWriter(videopath, codec, fps, 640, 480, true);
            

            for (int i = 0; i < list_timestamps.Count; i++)
            {
                videopath = Program.getConfiguration().Mediafolderpath + @"\" + list_timestamps[i].ToString() + ".mpg";
                try
                {
                    Capture joincapture = new Capture(videopath);
                    Image<Bgr, byte> frame = joincapture.QueryFrame();
                    for (int n = 1; n < 15; n++)
                        joincapture.QueryFrame();

                    while (frame != null)
                    {
                        videowriter.WriteFrame(frame);
                        frame = joincapture.QueryFrame();
                    }
                    joincapture.Dispose();

                    // Notify main frame to update its progressbar
                    ExportVideoProgressEventArgs e = new ExportVideoProgressEventArgs(i);
                    DoneAppendingRallyVideoEvent(this, e);
                }
                catch (NullReferenceException) { Console.WriteLine("unreadable video file"); }
            }
            videowriter.Dispose();
        
        }
Example #2
0
        private void run()
        {
            Image<Bgr, Byte> image = new Image<Bgr, byte>("lena.jpg"); //Read the files as an 8-bit Bgr image
            Capture vid = new Capture("kw.avi");
            vid.FlipVertical = true;
            int x = 0;
            TimeSpan time = TimeSpan.Zero;
            MCvFont font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_COMPLEX, 1.0, 1.0);
            using (VideoWriter vw = new VideoWriter("out3.avi", 15, 640, 480, true))
            {

                while (vid.Grab())
                {
                    //if (++x % 1 != 0) continue;

                    image = vid.RetrieveBgrFrame();

                    long detectionTime;
                    List<Rectangle> faces = new List<Rectangle>();
                    List<Rectangle> eyes = new List<Rectangle>();
                    DetectFace.Detect(image, "haarcascade_frontalface_default.xml", "supersmile.xml", faces, eyes, out detectionTime);
                    foreach (Rectangle face in faces)
                        image.Draw(face, new Bgr(Color.Red), 2);
                    foreach (Rectangle eye in eyes)
                        image.Draw(eye, new Bgr(Color.Blue), 2);
                    if (eyes.Count > 0) time = time.Add(new TimeSpan(0, 0, 0, 0, 66));
                    //display the image
                    image.Draw(String.Format("{0}:{1}", time.Seconds, time.Milliseconds), ref font, new Point(50, 50), new Bgr(0, 0, 255));
                    setimage(image);
                    vw.WriteFrame<Bgr, Byte>(image);
                }
            }
        }
Example #3
0
 public static bool SaveFrameInAVIFormat(VideoWriter output_writer, Image<Bgr, byte> frame)
 {
     try
     {
         using (frame)
         {
             output_writer.WriteFrame(frame);
             return true;
         }
     }
     catch (Exception e)
     {
         Debug.WriteLine(e.Message);
         return false;
     }
 }
        //Save video function called when t>trigger+T/2 OR from UI Test button, Saves ImageCollection buffer to video
        private void SaveVideo(bool fromTestButton)
        {

            string vEventfileName = fileHandler.getVideoFileName() + "event" + (fromTestButton?"test":"")+(counter).ToString() + ".avi"; //
            using (VideoWriter vw = new VideoWriter(vEventfileName, 0, 32 / frameAcceptance, 640, 480, true))
            {
                for (int i = 0; i < _videoArray.Count(); i++)
                {
                    vw.WriteFrame<Emgu.CV.Structure.Rgb, Byte>(_videoArray[i]);
                }
            }
        }
Example #5
0
        public void TestVideoWriter()
        {
            int numberOfFrames = 10;
             int width = 300;
             int height = 200;
             String fileName = GetTempFileName() + ".mpeg";

             Image<Bgr, Byte>[] images = new Image<Bgr, byte>[numberOfFrames];
             for (int i = 0; i < images.Length; i++)
             {
            images[i] = new Image<Bgr, byte>(width, height);
            images[i].SetRandUniform(new MCvScalar(), new MCvScalar(255, 255, 255));
             }

             using (VideoWriter writer = new VideoWriter(fileName, 5, width, height, true))
             {
            for (int i = 0; i < numberOfFrames; i++)
            {
               writer.WriteFrame(images[i]);
            }
             }

             FileInfo fi = new FileInfo(fileName);
             Assert.AreNotEqual(fi.Length, 0);

             using (Capture capture = new Capture(fileName))
             {
            Image<Bgr, Byte> img2 = capture.QueryFrame();
            int count = 0;
            while (img2 != null)
            {
               Assert.AreEqual(img2.Width, width);
               Assert.AreEqual(img2.Height, height);
               //Assert.IsTrue(img2.Equals( images[count]) );
               img2 = capture.QueryFrame();
               count++;
            }
            Assert.AreEqual(numberOfFrames, count);
             }
             File.Delete(fi.FullName);
        }
        private void previewBtn_Click(object sender, RoutedEventArgs e)
        {
            if (previewBtn.Content.ToString() == "Preview Stream")
            {
                if (kinect_sensor != null)
                {
                    // disable all other buttons
                    DeactivateReplay();
                    gestureCaptureBtn.IsEnabled = false;
                    gestureRecognitionBtn.IsEnabled = false;
                    gestureReplayBtn.IsEnabled = false;
                    previewBtn.Content = "Stop Stream";
                    isStreaming = true;
                    kinect_data_manager.ifShowJointStatus = true;

                    frame_rec_buffer.Clear();

                    kinect_sensor.Start();
                }
            }
            else
            {
                if(kinect_sensor != null)
                {
                    kinect_sensor.Stop();

                    gestureCaptureBtn.IsEnabled = true;
                    gestureReplayBtn.IsEnabled = true;
                    gestureRecognitionBtn.IsEnabled = true;

                    isStreaming = false;
                    kinect_data_manager.ifShowJointStatus = false;

                    // save recorded frame to disk
                    if (frame_rec_buffer != null && saveVideoCheckBox.IsChecked.Value)
                    {
                        // create video writer
                        int fwidth = (int)groupBox3.Width + 20;
                        int fheight = (int)groupBox3.Height + 20;

                        SaveFileDialog saveDialog = new SaveFileDialog();
                        saveDialog.Filter = "avi files (*.avi)|*.avi";
                        saveDialog.FilterIndex = 2;
                        saveDialog.RestoreDirectory = true;

                        if (saveDialog.ShowDialog().Value)
                        {
                            statusbarLabel.Content = "Saving video...";

                            string videofile = saveDialog.FileName.ToString();
                            VideoWriter videoWriter = new VideoWriter(videofile, CvInvoke.CV_FOURCC('M', 'J', 'P', 'G'), 15,
                                fwidth, fheight, true);

                            if (videoWriter == null)
                                MessageBox.Show("Fail to save video. Check if codec has been installed.");
                            else
                            {
                                for (int i = 0; i < frame_rec_buffer.Count; i++)
                                {
                                    // write to video file
                                    Emgu.CV.Image<Bgr, byte> cvImg =
                                        new Emgu.CV.Image<Bgr, byte>(frame_rec_buffer[i] as Bitmap);

                                    videoWriter.WriteFrame<Bgr, byte>(cvImg);
                                }

                                videoWriter.Dispose();

                                statusbarLabel.Content = "Video saved to " + videofile;
                            }
                        }

                    }

                    frame_rec_buffer.Clear();

                    previewBtn.Content = "Preview Stream";

                    // save tracked elbow speed
                    //FileStream file = File.Open("d:\\temp\\test.txt", FileMode.Create);
                    //StreamWriter writer = new StreamWriter(file);
                    //for (int i = 0; i < motion_assessor.jointStatusSeq.Count; i++)
                    //    writer.WriteLine(motion_assessor.jointStatusSeq[i][JointType.HandRight].abs_speed);
                    //writer.Close();
                }
            }
        }
        static void Main(string[] args)
        {
            /// Getting parameters
            ///
            inputValues iVal = ReadInput();
            PrintParams(iVal);

            string videoNameFile = iVal.videoIn;
            if (!File.Exists(videoNameFile))
            {
                Console.WriteLine("File {0} doesn't exist!", videoNameFile);
                Environment.Exit(1);
            }
            string workingDirectory = Path.GetDirectoryName(videoNameFile);
            //string outputFileName = string.Format("{0}_out1.avi", videoNameFile.Remove(videoNameFile.Length - 4));
            int windowLength = iVal.windowLength;
            int nParticles = iVal.nParticles;
            int blockDim = iVal.blockDim;
            double SIGMA = iVal.SIGMA;

            // in/out streams
            Capture cap = new Capture(Path.Combine(workingDirectory, videoNameFile));
            MCvFont font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_PLAIN, 1, 1);
            VideoWriter wr = new VideoWriter(iVal.videoOut, //Path.Combine(workingDirectory, outputFileName),
                   CvInvoke.CV_FOURCC('D', 'I', 'V', 'X'),
                   (int)cap.GetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FPS),
                   (int)cap.GetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_WIDTH),
                   (int)cap.GetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT),
                   true);

            // Print Results
            StreamWriter rw = new StreamWriter(Path.Combine(workingDirectory, iVal.videoOut.Remove(iVal.videoOut.Length - 4) + ".txt"));//videoNameFile.Remove(videoNameFile.Length - 4) + ".txt"));

            // LK params
            MCvTermCriteria termCrit = new MCvTermCriteria(10000, 0.0001);
            byte[] bs;
            float[] fs;
            PointF[] prevPoints = new PointF[nParticles];
            PointF[] newPoints = new PointF[nParticles];

            // Video frames
            currentFrame = cap.QueryFrame();
            Image<Bgr, byte> previousFrame = currentFrame.Clone();
            Image<Gray, byte> currentFrameGray = new Image<Gray, byte>(currentFrame.Bitmap);
            Image<Gray, byte> previousFrameGray = currentFrameGray.Clone();

            // Particle Initialization
            List<Particle> pList = GridGFTTinit(currentFrameGray, blockDim, nParticles, windowLength);
            prevPoints = ParticleToPointF(pList);
            newPoints = prevPoints;

            // State Matrix
            Matrix<float> stateMat = iVal.stateMat;  //ReadStateMatrix2x2();

            while (frameNumber < frameToProcess) {
                Console.WriteLine("------------Frame Number: {0} ---------", frameNumber);

                //if (currentFrame == null)
                //{
                //    currentFrame = cap.QueryFrame();
                //    frameNumber++;
                //}

                // Get Pointf[] from ParticleList
                List<Particle> pOld = new List<Particle>();
                foreach (Particle p in pList)
                {
                    Particle tmpParticle = new Particle(0, new Point(), 0);
                    p.CopyTo(tmpParticle);
                    pOld.Add(tmpParticle);
                }

                prevPoints = ParticleToPointF(pList);

                // Tracking old particles
                OpticalFlow.PyrLK(previousFrameGray, currentFrameGray, prevPoints, new System.Drawing.Size(15, 15), 3, termCrit, out newPoints, out bs, out fs);
                prevPoints = newPoints;
                for (int i = 0; i < newPoints.Length; i++ ) {
                    Point p = new Point(Convert.ToInt32(newPoints[i].X), Convert.ToInt32(newPoints[i].Y));
                    pList[i].Update(p, frameNumber);
                }
                // Particle Thickening
                pList = GridGFTTUpdate(currentFrameGray, pList, blockDim, nParticles, 3, windowLength);
                Console.WriteLine("Particle Number: {0}.", pList.Count);

                //debug line
                if (pList.Count == 0)
                    pList.Add(new Particle(-1, new Point(), frameNumber, windowLength));

                // Particle classification and mitigation EUSIPCO INFLUENCE
                Matrix<float> InfluenceMatrix = CalcMatrixRdynamic(pList, SIGMA);
                //Matrix<float> InfluenceMatrix = CalcMatrixRhybrid(pList, SIGMA);

                Console.WriteLine("Matrix R Computed.");
                //MarkovChain(ref pList, InfluenceMatrix, stateMat);
                ForwardAlgorithm(ref pList, InfluenceMatrix, stateMat, iVal.condMat, iVal.hmmLength);
                Console.WriteLine("Influence model completed.");

                // to write trajectories
                List<int> pExpList = ExpiredParticles(pList, pOld);
                foreach (int i in pExpList)
                {
                    Particle part = pList.First<Particle>(p => p.GetID() == i);
                    rw.Write("{0}\t", part.wholePosList.Count);
                    for (int pt = 0; pt < part.wholePosList.Count; pt++)
                    {
                        rw.Write("({0},{1},{2})", part.wholePosList[pt].X, part.wholePosList[pt].Y, part.wholeFnList[pt]);
                    }
                    rw.WriteLine("");
                    part.ClearPosList();
                }
                rw.Flush();

                ////////// Draw & display points
                List<Particle> finalParticles = new List<Particle>();
                int count = 0;

                foreach (Particle p in pList) {
                    if (p.state == 1) {
                        currentFrame.Draw(new CircleF(p.Position(), 1), new Bgr(Color.Blue), lineStroke);
                        finalParticles.Add(p);
                    } else if (p.state == 2) {
                        //Point posText = p.Position();
                        //posText.Y += 10;
                        //currentFrame.Draw(new CircleF(p.Position(), 1), new Bgr(Color.Yellow), lineStroke);
                        //currentFrame.Draw(string.Format("{0}", p.GetID()), ref font, posText, new Bgr(Color.Yellow));
                        Point prevpo = p.posList[p.posList.Count - 1];

                        bool jumpcheck = false;
                        for (int j = 1; j < iVal.hmmLength - 1; j++)
                        {
                            Point actpo = p.posList[p.posList.Count - 1 - j];
                            if (PointDistance(actpo, prevpo) > 50)
                                jumpcheck = true;
                        }

                        if (jumpcheck)
                            continue;

                        prevpo = p.posList[p.posList.Count - 1];
                        //currentFrame.Draw(p.GetID().ToString(), ref font, p.Position(), new Bgr( Color.Beige));
                        for (int j = 1; j < iVal.hmmLength - 1; j++)
                        {
                            Point actpo = p.posList[p.posList.Count - 1 - j];

                            currentFrame.Draw(new LineSegment2D(actpo, prevpo), new Bgr(Color.Yellow), lineStroke);
                            prevpo = actpo;
                        }
                        finalParticles.Add(p);
                        //rw.WriteLine("{0}\t{1}\t{2}\t{3}", frameNumber, p.Position().X, p.Position().Y, p.groupLabel);
                    }
                    else if (p.state == 0)
                    {
                        Console.WriteLine(string.Format("Particle {0} killed", count));
                    }
                    else if (p.state == 3)
                    {
                        finalParticles.Add(p);
                    }
                    count++;
                }

                pList = finalParticles;

                currentFrame.Draw(string.Format("Frame: {0}", frameNumber), ref font, new Point(50, 50), new Bgr(Color.Yellow));
                wr.WriteFrame<Bgr, byte>(currentFrame);
                previousFrame = currentFrame.Clone();
                double ratio = 1;
                if (cap.Width > cap.Height) {
                    ratio = 1000 / (double)cap.Width;
                } else {
                    ratio = 1000 / (double)cap.Height;
                }
                CvInvoke.cvShowImage("Video", previousFrame.Resize(ratio, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC).Ptr);
                CvInvoke.cvWaitKey(10);
                if (frameNumber > windowLength - 3 ) {
                    //currentFrame.Resize(ratio, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC).Save(string.Format(@"frames/debug_{0}.jpg", frameNumber));
                }

                // Update frame (current, gray and previous)
                try {
                    currentFrame = cap.QueryFrame();
                    frameNumber++;
                    //cap.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_POS_FRAMES, frameNumber);
                    //currentFrame = cap.QueryFrame();
                    previousFrameGray = currentFrameGray.Clone();
                    currentFrameGray = new Image<Gray, byte>(currentFrame.Bitmap);
                } catch (NullReferenceException) {
                    break;
                }
            }
            //rw.Flush();
            rw.Close();
            //List<string> emailText = new List<string>();
            //emailText.Add(string.Format("Finito con file {0}, PARAMS:\nProcessed Frames: {1}", videoNameFile, frameToProcess));
            //emailText.Add(string.Format("BlockDim: {0}", blockDim));
            //emailText.Add(string.Format("N. particles per block: {0}", nParticles));
            //emailText.Add(string.Format("Window Length: {0}", windowLength));
            //emailText.Add(string.Format("SIGMA: {0}", SIGMA));
            //emailText.Add(string.Format("State Matrix:\n{0} {1}\n{2} {3}", stateMat[0,0], stateMat[0,1], stateMat[1,0], stateMat[1,1]));
            //SendEmailAlert(emailText.ToArray());
        }
Example #8
0
        private void generarVideo()
        {
            Emgu.CV.VideoWriter escritor = new Emgu.CV.VideoWriter(rutaAlmacenamiento+"\\Out.avi", 30,
                ancho, alto, true);
            //Recuperamos los nombres de los archivos JPG
            string[] listaImagenes = Directory.GetFiles(rutaAlmacenamiento, "*.jpg");
            barraProgresoGeneracion.Maximum = listaImagenes.Length;
            int posFrame = 0;
            int total=listaImagenes.Length;

            foreach (string imagen in listaImagenes)
            {

                barraProgresoGeneracion.Value = posFrame;

                Image<Bgr, Byte> imagenCargada = new Image<Bgr, byte>(imagen);
                escritor.WriteFrame<Bgr, byte>(imagenCargada);
                //imagenCargada.Dispose();
                posFrame=posFrame+1;
            }

            Thread.Sleep(5000);
            escritor.Dispose();
            GC.Collect();

            MessageBox.Show("Video generado");
        }