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();
        
        }
Пример #2
0
        private void M_capture_ImageGrabbed(object sender, EventArgs e)
        {
            // Console.WriteLine("test: "  + startIndex.ToString());
            //  startIndex++;

            destin = SaveRecordingLocation_textbox.Text;

            if (fileChanged)
            {
                // destin = SaveRecordingLocation_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 + i + ".avi";
                videoWriter = new Emgu.CV.VideoWriter(destination, Emgu.CV.VideoWriter.Fourcc('I', 'Y', 'U', 'V'), fps, new System.Drawing.Size(frameWidth, frameHeight), true);
                fileChanged = false;
            }


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



            //throw new NotImplementedException();
        }
Пример #3
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);
                }
            }
        }
        // For cutting from a loaded video
        public WriteRallyVideoThread(double start, double end, String loadedvideopath, VideoWriter writer, long starttime)
        {
            this.start = Math.Floor(start);
            this.end = Math.Ceiling(end);
            this.loaded_videopath = loadedvideopath;
            this.videoWriter = writer;

            this.starttime = starttime; // to notify the main frame that we are done writing the rally with id starttime  so we can create a screenshot.
        }
Пример #5
0
 public VideoLogger(string videofile)
 {
     this.filename = videofile;
         bool isColor = true;
         int fps = 25;  // or 30
         int frameW = 640; // 744 for firewire cameras
         int frameH = 480; // 480 for firewire cameras
         writer = new VideoWriter(filename,
                              CvInvoke.CV_FOURCC('X','V','I','D'),
                              fps, frameW, frameH, isColor);
 }
Пример #6
0
 public Form1()
 {
     _imgCollection.GoTo(300);
     videoWriter = new VideoWriter("video.avi", 20, 640, 480, true);
     InitializeComponent();
     _playTimer = new DispatcherTimer(new TimeSpan(0, 0, 0, 0, 1), DispatcherPriority.Normal, StepRight_Click,
                                      Dispatcher.CurrentDispatcher);
     _playTimer.Stop();
     UpdateResearchInfo();
     UpdateImage();
     UpdateFrameCount();
     ImageBox.Focus();
 }
Пример #7
0
        public void Close()
        {
            if (writer != null)
            {
                writer.Dispose();
                writer = null;
            }

            if (frameIndexStream != null)
            {
                frameIndexStream.Close();
                frameIndexStream.Dispose();
                frameIndexStream = null;
            }
        }
Пример #8
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;
     }
 }
Пример #9
0
        public ImageStreamWriter(String fileName, int codec, int fps, int width, int height, bool isColour)
        {
            try
            {
                if (fps > 0 && width > 0 && height > 0)
                {
                    this.fileName = fileName;
                    this.isColour = isColour;

                    writer = new VideoWriter(fileName, codec, fps, width, height, isColour);

                    frameFileName = ImageStreamWriter.CreateMatchingSynchronisationFileName(fileName);
                    frameIndexStream = new System.IO.StreamWriter(frameFileName);
                }
            }
            catch (Exception e)
            {
                writer = null;
                frameIndexStream = null;
            }
        }
 private void CloseAllWriter()
 {
     if (colorWriter != null)
     {
         colorWriter.Dispose();
         colorWriter = null;
     }
     if (depthWriter != null)
     {
         depthWriter.Dispose();
         depthWriter = null;
     }
     if (skeWriter != null)
     {
         skeWriter.Dispose();
         skeWriter = null;
     }
 }
Пример #11
0
        private void button3_Click(object sender, EventArgs e)
        {
            saveFileDialog1.Filter = "AVI|*.avi";
            if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                path = saveFileDialog1.FileName;
                double fpsInitial = grabber.GetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_POS_FRAMES);

                int fps = (int)fpsInitial;
                VW = new VideoWriter(path, 4, 640, 480, true);
                //VW.WriteFrame(currentFrame);
                try {
                    //foreach (String h in hex)
                    //{
                    //    Image frame;
                    //    frame = library.ConvertByteToImage(library.DecodeHex(h));

                    //    Image<Gray, Byte> normalizedMasterImage = new Image<Gray, Byte>((Bitmap)frame);
                    //    VW.WriteFrame(normalizedMasterImage);

                    //}
                    //MessageBox.Show("Video Generated Successfully", "Success");
                    luuvideo = true;
                }catch(Exception ei)
                {
                    //VW.Dispose();
                    MessageBox.Show(ei.ToString());
                }
            }
        }
Пример #12
0
        void pipeClient_MessageReceived(string message)
        {
            if (message.Equals("start")) 
            {
                Invoke(new Action(()=>{
                if (resolution.SelectedIndex > -1)
                    fotis = new VideoWriter(vidPath + @"\temp.avi", CvInvoke.CV_FOURCC('D', 'I', 'V', 'X'), Int16.Parse(realfps.Text), selectedWidth, selectedHeight, true);
            }));
                start=true;
                Invoke((Action)(() =>{
                    this.Text = "Capturing...";
             Frame_lbl.Text = "Frame: ";
             webcam_frm_cnt = 0;
                }));
            }
            if (message.StartsWith("stop"))
            {
                start = false;
               this.Invoke(new Action(() => this.Text = "File saved"));
                string participant = message.Substring(4);
                this.Invoke(new Action(() => idtext.Text = participant));
                string path = vidPath;
                string path2 =vidPathFinal;
                string searchPattern = "t*";
                fotis.Dispose();
                DirectoryInfo di = new DirectoryInfo(path);
                FileInfo[] files = di.GetFiles(searchPattern, SearchOption.TopDirectoryOnly);

                foreach (FileInfo file in files)
                {
                    this.Invoke(new Action(() =>{
                    //if (File.Exists(path2))
                    //{
                    //    System.IO.File.Delete(path2);
                    //}
                    if (File.Exists(vidPathFinal + @"\Cam_" + modulenumber.SelectedItem.ToString() + "_ID_" + idtext.Text + ".avi"))
                    {
                        System.IO.File.Delete(vidPathFinal + @"\Cam_" + modulenumber.SelectedItem.ToString() + "_ID_" + idtext.Text + ".avi");
                    }
                    for (int i = 0; i < 3;i++ ) //try 3 times to move the video in case the writter still writes images
                        try
                        {
                            file.MoveTo(vidPathFinal + @"\Cam_" + modulenumber.SelectedItem.ToString() + "_ID_" + idtext.Text + ".avi");
                            break;
                        }
                        catch (Exception e)
                        { Thread.Sleep(1000); }
                    
                }));
                }
                 Invoke((Action)(() =>
                {
                    if (resolution.SelectedIndex >-1)
                        fotis = new VideoWriter(vidPath + @"\temp.avi", CvInvoke.CV_FOURCC('D', 'I', 'V', 'X'), Int16.Parse(realfps.Text), selectedWidth, selectedHeight, true);

                    Frame_lbl.Text = "Frame: ";
                    webcam_frm_cnt = 0;
                }));
            }
        }
Пример #13
0
        public override void Start()
        {
            _videoWriter = new VideoWriter("DataRenderer.avi", CvInvoke.CV_FOURCC('D', 'I', 'V', 'X'), 25, Width, Height, true);

            base.Start();
        }
Пример #14
0
        public override void Stop()
        {
            if (_videoWriter != null)
            {
                _videoWriter.Dispose();
                _videoWriter = null;
            }

            base.Stop();
        }
Пример #15
0
        private void button_startmove_Click(object sender, EventArgs e)
        {
            long start_time;
     

            // initiating a new move along with a new timestamp as identifier
            if (!new_move)
            {
                live_video_click_count = 0;

                // Enable the Spielzug/Move property buttons
                button_kill.Enabled = true;
                button_smash.Enabled = true;
                button_drop.Enabled = true;
                button_bigPoint.Enabled = true;
                button_timeout.Enabled = true;

                radioButton_playerupright.Enabled = true;
                radioButton_playerupleft.Enabled = true;
                radioButton_playerdownleft.Enabled = true;
                radioButton_playerdownright.Enabled = true;

                radioButton_playerupright.Checked = false;
                radioButton_playerupleft.Checked = false;
                radioButton_playerdownleft.Checked = false;
                radioButton_playerdownright.Checked = false;
                

                start_time = getCurrentTime(); // get current time as identifier
                while (List_timestamps.Contains(start_time))
                    start_time = getCurrentTime();
                
                List_timestamps.Add(start_time); // add timestamp to the list we use for the screenshots

                // Create a new Rally 
                Game.Current_rally = 
                    new Rally(configuration.Teama.Player1.Current_position,
                              configuration.Teama.Player2.Current_position,
                              configuration.Teamb.Player1.Current_position,
                              configuration.Teamb.Player2.Current_position,
                              start_time, Game.Sets.Count);

                
   

                // Clear the BirdView
                pictureBox_birdview.Invalidate();

                rallyframes = new List<Image<Bgr, byte>>();

                
                String move_identifier = start_time.ToString();
                String videopath = Program.getConfiguration().Mediafolderpath + @"\" + move_identifier + ".mpg";

                if (capture_device_index != -1)
                    this.videoWriter = new VideoWriter(videopath, Emgu.CV.CvInvoke.CV_FOURCC('P', 'I', 'M', '1'), fps, 640, 480, true);


                // start a new video capture from video
                if (capture_device_index == -1)
                {
                    Capture tempcapture = new Capture(loaded_videopath);
                    int tempfps = (int)tempcapture.GetCaptureProperty(CAP_PROP.CV_CAP_PROP_FPS);
                    //this.videoWriter = new VideoWriter(videopath, Emgu.CV.CvInvoke.CV_FOURCC('P', 'I', 'M', '1'), tempfps, 640, 480, true);
                    startmilisecond = axWindowsMediaPlayer_live.Ctlcontrols.currentPosition;
                    axWindowsMediaPlayer_live.Ctlcontrols.play();
                    tempcapture.Dispose();
                }


                button_startmove.Text = "End of rally";
                button_startmove.ForeColor = System.Drawing.Color.Red;
                new_move = true;
            }
            else
            {
                live_video_click_count = 0;

                // Disable the Spielzug/Move property buttons
                button_kill.Enabled = false;
                button_smash.Enabled = false;
                button_drop.Enabled = false;
                button_bigPoint.Enabled = false;
                button_timeout.Enabled = false;

                radioButton_playerupright.Enabled = false;
                radioButton_playerupleft.Enabled = false;
                radioButton_playerdownleft.Enabled = false;
                radioButton_playerdownright.Enabled = false;

                radioButton_playerupright.Checked = false;
                radioButton_playerupleft.Checked = false;
                radioButton_playerdownleft.Checked = false;
                radioButton_playerdownright.Checked = false;

                // AUTO handling of score
                // Save into the list and add to xml output
                if (Game.Current_rally != null)
                {
                    Set current_set = Game.Sets[Game.Sets.Count - 1];
                    current_set.Rallies.Add(Game.Current_rally);
                    

                    // Set End Time
                    Game.Current_rally.EndRally_time = getCurrentTime();
                    Game.Current_rally.Duration_ticks = Game.Current_rally.EndRally_time - Game.Current_rally.Start_time;

                    // calculate the point for the successful team
                    Game.Current_rally.setNewScore(Game, configuration.TeamAup);
                    

                    xmlDoc.addRally(Game.Current_rally);


                    if (Game.Current_rally.Kill)
                        button_kill.Text = "KILL";
                    else
                        button_kill.Text = "NO KILL";

                    if (configuration.TeamAup)
                    {
                        textBox_scoreteamup.Text = current_set.TeamAScore.ToString();
                        textBox_scoreteamdown.Text = current_set.TeamBScore.ToString();
                    }
                    else
                    {
                        textBox_scoreteamup.Text = current_set.TeamBScore.ToString();
                        textBox_scoreteamdown.Text = current_set.TeamAScore.ToString();
                    }
                    // set color 
                    setScoreColor(current_set);
                    Team winner = current_set.getSetWinner(Game);

                    if (winner != null)
                    {
                        teamXhasWon();
                    }
                }


                

                // stop the capturing and write video
                if (capture_device_index != -1) // camera capture
                {
                    start_time = Game.Current_rally.Start_time;
                    WriteRallyVideoThread writevideoobject = new WriteRallyVideoThread(buffer, videoWriter, start_time);
                    writevideoobject.donewritingrallyvideo += new DoneWritingRallyVideoEventHandler(writevideothread_donewritingvideo);
                    writeRallyVideoFromBuffer(writevideoobject);
                }
                else // loaded video
                {
                    endmilisecond = axWindowsMediaPlayer_live.Ctlcontrols.currentPosition;
                    start_time = Game.Current_rally.Start_time;
                    WriteRallyVideoThread writevideoobject = new WriteRallyVideoThread(startmilisecond, endmilisecond, loaded_videopath, null, start_time);
                    writevideoobject.donewritingrallyvideo += new DoneWritingRallyVideoEventHandler(writevideothread_donewritingvideo);
                    writevideoobject.donewritingrallyframe += new DoneWritingRallyFrameEventHandler(writevideothread_donewritingframe);
                    writeRallyVideoFromLoaded(writevideoobject);
                    
                }


                button_startmove.Text = "Start of rally…"; // SAVE
                button_startmove.ForeColor = System.Drawing.Color.Black;
                new_move = false;

            }
        }
Пример #16
0
        private void CleanUp()
        {
            try
            {
                camera_capture.Dispose();
                video_writer.Dispose();
                timer.Stop();
                timer.Dispose();
                timer = null;
                frame_to_be_saved = null;
                camera_capture = null;
                video_writer = null;
            }
            catch (Exception)
            {

            }
        }
Пример #17
0
        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            foreach (var potentialSensor in KinectSensor.KinectSensors)
            {
                if (potentialSensor.Status == KinectStatus.Connected)
                {
                    this.sensor = potentialSensor;
                    break;
                }
            }

            if (null != this.sensor)
            {
                this.sensor.DepthStream.Enable(depthFormat);
                this.sensor.ColorStream.Enable(colorFormat);
                this.colorPixels = new byte[this.sensor.ColorStream.FramePixelDataLength];
                this.depthPixels = new DepthImagePixel[this.sensor.DepthStream.FramePixelDataLength];
                this.colorBitmap = new WriteableBitmap(this.sensor.ColorStream.FrameWidth, this.sensor.ColorStream.FrameHeight, 96.0, 96.0, PixelFormats.Bgr32, null);
                this.depthBitmap = new WriteableBitmap(this.sensor.DepthStream.FrameWidth, this.sensor.DepthStream.FrameHeight, 96.0, 96.0, PixelFormats.Bgr32, null);
                this.colorImg.Source = this.colorBitmap;
                this.mapper = new CoordinateMapper(sensor);
                this.skeletonPoints = new SkeletonPoint[307200];

                vw = new VideoWriter(recordLoc, 30, this.sensor.DepthStream.FrameWidth, this.sensor.DepthStream.FrameHeight, true);
                FileInfo newFile = new FileInfo(excelLoc);

                if (newFile.Exists)
                {
                    newFile.Delete();
                    newFile = new FileInfo(excelLoc);
                }

                pck = new ExcelPackage(newFile);
                wsheet = pck.Workbook.Worksheets.Add("Rat Data");

                wsheet.Cells[1, 1].Value = "Coord (m)";
                for (int i = 1; i <= 4; i++)
                {
                    wsheet.Cells[3 * i - 1, 1].Value = "Rat " + i + " X";
                    wsheet.Cells[3 * i, 1].Value = "Rat " + i + " Y";
                    wsheet.Cells[3 * i + 1, 1].Value = "Rat " + i + " Z";
                }

                this.sensor.AllFramesReady += this.sensor_AllFramesReady;

                try
                {
                    this.sensor.Start();
                }
                    catch (IOException)
                {
                    this.sensor = null;
                }

            }
            if (null == this.sensor)
            {
                this.outputViewbox.Visibility = System.Windows.Visibility.Collapsed;
                this.txtError.Visibility = System.Windows.Visibility.Visible;
                this.txtInfo.Text = "No Kinect Found";

            }
        }
Пример #18
0
 public void TestCaptureFromFile()
 {
    using (VideoCapture capture = new VideoCapture(EmguAssert.GetFile( "tree.avi")))
    using (VideoWriter writer = new VideoWriter("tree_invert.avi", 10, new Size(capture.Width, capture.Height), true))
    {
       int maxCount = 10;
       Mat img = new Mat();
       while (capture.Grab() && maxCount > 0)
       {
          capture.Retrieve(img);
          CvInvoke.BitwiseNot(img, img);
          writer.Write(img);
          maxCount--;
       }
    }
 }
Пример #19
0
        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());
        }
        private void frame_threading()
        {
            int i = 0;
            States current_states = new States();
            current_states = States.start;
            fileName = Directory.GetFiles(@"" + folder_selected, "*.xed");
            Console.WriteLine("Successful to get all file name");
            if (fileName.Length < 1)
            {
                Console.WriteLine("No xed file in this folder");
                return;
            }
            colorizer = new Colorizer(AaronRotateTan, CurrentKinectSensor.DepthStream.MaxDepth, CurrentKinectSensor.DepthStream.MinDepth);

            while (Is_running)
            {
                switch (current_states)
                {
                    case States.start:
                        Console.WriteLine("Start state .. .. .. ");
                        single_file_name = System.IO.Path.GetFileNameWithoutExtension(fileName[i]);
                        if (!Directory.Exists(folder_selected + "\\" + single_file_name))
                            Directory.CreateDirectory(folder_selected + "\\" + single_file_name);
                        colorWriter = new VideoWriter(folder_selected + "\\" + single_file_name + "\\" + single_file_name + "_c.avi", 30, 640, 480, true);
                        depthWriter = new VideoWriter(folder_selected + "\\" + single_file_name + "\\" + single_file_name + "_d.avi", 30, 640, 480, true);
                        FileStream file_name = File.Open(@folder_selected + "\\" + single_file_name + "\\" + single_file_name + ".csv", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                        skeWriter = new StreamWriter(file_name);

                        // !!!!  Detecting signer by the filename
                        if (single_file_name.Contains("Michael"))
                            colorizer.Angle = MichaelRotateTan;
                        else if (single_file_name.Contains("Anita"))
                            colorizer.Angle = AnitaRotateTan;
                        else if (single_file_name.Contains("Aaron"))
                            colorizer.Angle = AaronRotateTan;
                        controler.Open_File(fileName[i]);
                        System.Threading.Thread.Sleep(1000);

                        old_frame_number_for_stop = 0;
                        old_skeleton_frame_number_for_stop = 0;
                        current_frame_number_for_stop = 0;
                        current_skeleton_frame_number_for_stop = 0;

                        PreColorFrameNumber = -1;
                        PreDepthFrameNumber = -1;
                        first_skeleton_frame_number = 0;
                        FirstTimeStamp = long.MaxValue;
                        current_states = States.running_start;
                        break;
                    case States.running_start:
                        file_IsReady = true;
                        timer.Start();
                        controler.Run_by_clik();
                        //controler.Run();
                        
                        current_states = States.Isrunning;
                        break;
                    case States.Isrunning:
                        Console.WriteLine("Isrunning states...");
                        System.Threading.Thread.Sleep(2000);
                        if ((current_frame_number_for_stop == old_frame_number_for_stop) &&
                            (current_skeleton_frame_number_for_stop == old_skeleton_frame_number_for_stop))
                        {
                            current_states = States.ending;
                            timer.Stop();
                            waiting = 0;
                        }
                        old_frame_number_for_stop = current_frame_number_for_stop;
                        old_skeleton_frame_number_for_stop = current_skeleton_frame_number_for_stop;
                        break;
                    case States.ending:
                        Console.WriteLine("Is ending state......");
                        i++;
                        CloseAllWriter();
                        System.Threading.Thread.Sleep(400);
                        if (i >= fileName.Length)
                            current_states = States.finished;
                        else
                            current_states = States.start;
                        break;
                    case States.finished:
                        Console.WriteLine("Happy finished all file in this folder");
                        all_finished = true;
                        break;
                    default:
                        break;
                }
                if (all_finished)
                    break;
            }
        }
Пример #21
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);
        }
Пример #22
0
        private void recordVideoToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            //set up filter
            SF.Filter = "Video Files|*.avi;*.mp4;*.mpg";
            //Get information about the video file save location
            if (SF.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //check to see if capture exists if it does dispose of it
                if (_Capture != null)
                {
                    if (_Capture.GrabProcessState == System.Threading.ThreadState.Running) _Capture.Stop(); //Stop urrent capture if running
                    _Capture.Dispose();//dispose of current capture
                }
                try
                {
                    //record the save location
                    this.Text = "Saving Video: " + SF.FileName; //display the save method and location

                    //set the current video state
                    CurrentState = VideoMethod.Recording;

                    //set up new capture
                    _Capture = new Capture(); //Use the default device
                    _Capture.ImageGrabbed += ProcessFrame; //attach event call to process frames

                    //get/set the capture video information

                    Frame_width = (int)_Capture.GetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_WIDTH);
                    Frame_Height = (int)_Capture.GetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT);

                    FrameRate = 15; //Set the framerate manually as a camera would retun 0 if we use GetCaptureProperty()

                    //Set up a video writer component
                    /*                                        ---USE----
                    /* VideoWriter(string fileName, int compressionCode, int fps, int width, int height, bool isColor)
                     *
                     * Compression code.
                     *      Usually computed using CvInvoke.CV_FOURCC. On windows use -1 to open a codec selection dialog.
                     *      On Linux, use CvInvoke.CV_FOURCC('I', 'Y', 'U', 'V') for default codec for the specific file name.
                     *
                     * Compression code.
                     *      -1: allows the user to choose the codec from a dialog at runtime
                     *       0: creates an uncompressed AVI file (the filename must have a .avi extension)
                     *
                     * isColor.
                     *      true if this is a color video, false otherwise
                     */
                    VW = new VideoWriter(@SF.FileName, -1, (int)FrameRate, Frame_width, Frame_Height, true);

                    //set up the trackerbar
                    UpdateVideo_CNTRL(false);//disable the trackbar

                    //set up the button and images
                    play_pause_BTN1.BackgroundImage = VideoCapture.Properties.Resources.Record;
                    recordstate = false;

                    //Start aquring from the webcam
                    _Capture.Start();

                }
                catch (NullReferenceException excpt)
                {
                    MessageBox.Show(excpt.Message);
                }
            }
        }
Пример #23
0
        private void writeRallyVideoFromLoaded(double s, double e, VideoWriter writer, String loadedvideopath)
        {
            double start = Math.Floor(s);
            double end = Math.Ceiling(e);
            double startmsec = start * 1000;
            double endmsec = end * 1000;


            Capture tempcapture = new Capture(loaded_videopath);

            Image<Bgr, Byte> frame;
            if (tempcapture != null)
            {
                //tempcapture.SetCaptureProperty(CAP_PROP.CV_CAP_PROP_POS_MSEC, start);

                double fps2 = tempcapture.GetCaptureProperty(CAP_PROP.CV_CAP_PROP_FPS);
                //tempcapture.SetCaptureProperty(CAP_PROP.CV_CAP_PROP_POS_MSEC, 100);

                for (int i = 0; i < (start * fps2); i++)
                    (tempcapture).QueryFrame();

                int durationframes = (int)((end - start) * fps2); // since c# sucks i have to do it manually just like any other crap

                int count = 0;
                while (count < durationframes)
                {
                    frame = (tempcapture).QueryFrame();
                    videoWriter.WriteFrame(frame);
                    count++;
                }
            }


            tempcapture.Dispose();
            videoWriter.Dispose();
        }
 // for writing from a given buffer
 public WriteRallyVideoThread(List<Image<Bgr, Byte>> buffer, VideoWriter writer, long starttime)
 {
     this.videoWriter = writer;
     this.buffer = buffer;
     this.starttime = starttime;
 }
Пример #25
0
 //INITIALIZES THE VIDEO WRITER
 public void InitilaizeWriter()
 {
     video_writer = new VideoWriter(
                                     PATH_TO_SAVED_FILES,
                                     (int)camera_capture.GetCaptureProperty(CAP_PROP.CV_CAP_PROP_FOURCC),
                                     (int)5,
                                     Singleton.MAIN_WINDOW.GetControl(MainWindow.MainWindowControls.live_stream_image_box1).Width,
                                     Singleton.MAIN_WINDOW.GetControl(MainWindow.MainWindowControls.live_stream_image_box1).Height,
                                     true
                                   );
 }
Пример #26
0
        void FrameGrabber(object sender, EventArgs e)
        {
            try
            {
                //Get the current frame form capture device
                currentFrame = grabber.QueryFrame().Resize(520, 340, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
            }
            catch (NullReferenceException e1)
            {
                _motionHistory = new MotionHistory(2.0, 0.05, 0.5);
                _forgroundDetector = null;
                motionQueue.Clear(); helpQueue.Clear();
                grabber = new Capture(vidlist[excnt]);
                excnt++;
                if (excnt == 5) { excnt = 0; }
                currentFrame = grabber.QueryFrame().Resize(520, 340, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
                green1 = false; green2 = false; green3 = false; green4 = false;
                red1 = false; red2 = false; red3 = false; red4 = false;
            }

            //Convert it to Grayscale
            gray = currentFrame.Convert<Gray, Byte>();

            //Face Detector
            MCvAvgComp[][] facesDetected = gray.DetectHaarCascade(
              face,
              1.2,
              10,
              Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,
              new Size(20, 20));

            //Action for each element detected
            foreach (MCvAvgComp f in facesDetected[0])
            {

                t = t + 1;
                result = currentFrame.Copy(f.rect).Convert<Gray, byte>().Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);

                //MessageBox.Show("wiidth " + f.rect.Width + " height " + f.rect.Height + " area " + f.rect.Width * f.rect.Height);
                if (f.rect.Width > 80) continue;

                //draw the face detected in the 0th (gray) channel with blue color
                if (showHand)
                    currentFrame.Draw(f.rect, new Bgr(Color.LightGreen), 2);

                int nearespos = nearestPosition(f.rect.X, f.rect.Y);

                if (helpQueue.ToArray().ToList().IndexOf(nearespos) == -1)
                {
                    //lbAlerts.Items.Add("Help request at #" + nearespos.ToString());

                    dgAlerts.Rows.Add("Help Request", nearespos.ToString());
                    DB_Connect.InsertQuery("INSERT INTO alert_tab(exam_id,position_id,alert_type,alert_time) VALUES(" + examid + "," + nearespos.ToString() + ",'H','" + DateTime.Now + "')");
                    dgAlerts.FirstDisplayedScrollingRowIndex = dgAlerts.RowCount - 1;

                    //GCM - help
                    //AndroidGCMPushNotification apnGCM = new AndroidGCMPushNotification();
                    //string strResponse = apnGCM.SendNotification(regID, nearespos.ToString() + " "+ DateTime.Now, "H");

                    if (nearespos == 1) green1 = true;
                    else if (nearespos == 2) green2 = true;
                    else if (nearespos == 3) green3 = true;
                    else if (nearespos == 4) green4 = true;

                    if (helpQueue.Count == 10)
                    {
                        helpQueue.Dequeue();
                        helpQueue.Enqueue(nearespos);
                    }
                    else
                    {
                        helpQueue.Enqueue(nearespos);
                    }
                }
            }

            //Show the faces procesed and recognized
            imageBoxFrameGrabber.Image = ProcessFrame(currentFrame);

            if (captureOutput == null && xdoc.Descendants("RecordVideo").First().Value == "1")
            {
                MessageBox.Show("reording start");
                captureOutput = new VideoWriter(@"video" + examid + ".avi", (int)grabber.GetCaptureProperty(CAP_PROP.CV_CAP_PROP_FOURCC), 15, 520, 340, true);
            }

            if (currentFrame != null && xdoc.Descendants("RecordVideo").First().Value == "1")
            {
                captureOutput.WriteFrame<Bgr, Byte>(currentFrame);
            }
        }
        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();
                }
            }
        }
        //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]);
                }
            }
        }
Пример #29
0
        /// <summary>
        /// Execute the filter.
        /// </summary>
        /// <param name="b">Bundle of information</param>
        public void Execute(Dictionary<string, object> b)
        {
            if (_vw == null) {
            _vw = new VideoWriter(_path, _fps, _frame_width, _frame_height, true);
              }

              Image<Bgr, byte> i = b.GetImage(_bag_name);
              Size s = i.Size;
              if (s.Width != _frame_width || s.Height != _frame_height) {
            i = i.Resize(_frame_width, _frame_height, Emgu.CV.CvEnum.INTER.CV_INTER_LINEAR);
              }

              _vw.WriteFrame(i);
        }
Пример #30
0
 private void PlayStop_Click(object sender, EventArgs e)
 {
     if (_playing)
     {
         PlayStop.Text = "Play";
         videoWriter.Dispose();
         _playTimer.Stop();
     }
     else
     {
         PlayStop.Text = "Stop";
         videoWriter = new VideoWriter("video.avi", 20, 640, 480, true);
         _playTimer.Start();
     }
     _playing = !_playing;
 }
Пример #31
0
        private void button3_Click(object sender, EventArgs e)
        {
            Button b = sender as Button;

            if (b.Text == "REC")
            {
                string filename = String.Format("C:/video/rec_{0}_{1}_{2}.avi", DateTime.Now.ToShortDateString(),
                DateTime.Now.ToShortTimeString().ToString().Replace(':', '_'), DateTime.Now.Millisecond.ToString());

                videoWriter = new VideoWriter(filename, 25, CamModel.Width, CamModel.Height, true);

                b.Text = "STOP";

                System.Console.Out.WriteLine("NAGRYWANIE");
                System.Console.Out.WriteLine(filename);
            }
            else
            {
                videoWriter.Dispose();
                videoWriter = null;
                b.Text = "REC";

                System.Console.Out.WriteLine("KONIEC NAGRYWANIA");
            }
            
        }