// Function to get one image from the file (if null returned it failed)
 public Bitmap getPreview()
 {
     Bitmap preview = null;
     VideoFileReader Temp = new VideoFileReader();
     try
     {
         Temp.Open(file);
     }
     catch
     {
         return preview;
     }
     // try if possible to extract a frame (use this one, to return for drawing)
     try
     {
         int frametotake = (int)Temp.FrameCount;
         for (int i = 0; i < (frametotake - 1) && i < 10; i++)
         {
             Temp.ReadVideoFrame();
         }
         preview = Temp.ReadVideoFrame();
     }
     catch
     {
         return preview;
     }
     return preview;
 }
Example #2
0
        public void ReadFromVideo(string path)
        {
            pathToFile = new Uri(AnaglyphParameters.VideoPath.LocalPath);
            AnaglyphParameters.PathToRead  = pathToFile.LocalPath;
            AnaglyphParameters.PathToWrite = path.Split('.')[0] + "1.mp4";
            reader.Open(pathToFile.LocalPath);

            SetWriter(reader, writer);


            for (int i = 0; i < reader.FrameCount; i++)
            {
                OnOnFrameDone(i, (int)reader.FrameCount);
                try
                {
                    using (Bitmap videoFrame = reader.ReadVideoFrame(i))
                    {
                        using (Bitmap videoFrameChanged = new Fitler().Calc(videoFrame))
                        {
                            writer.WriteVideoFrame(videoFrameChanged, (uint)i);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.StackTrace);
                }
            }
            reader.Close();
            writer.Close();

            VideoToFrames.AddAudioToVideo(path);
            OnOnProcessDone();
        }
        // Function to get one image from the file (if null returned it failed)
        public Bitmap getPreview()
        {
            Bitmap          preview = null;
            VideoFileReader Temp    = new VideoFileReader();

            try
            {
                Temp.Open(file);
            }
            catch
            {
                return(preview);
            }
            // try if possible to extract a frame (use this one, to return for drawing)
            try
            {
                int frametotake = (int)Temp.FrameCount;
                for (int i = 0; i < (frametotake - 1) && i < 10; i++)
                {
                    Temp.ReadVideoFrame();
                }
                preview = Temp.ReadVideoFrame();
            }
            catch
            {
                return(preview);
            }
            return(preview);
        }
Example #4
0
        public static void Generate()
        {
            var reader = new VideoFileReader();

            reader.Open(VideoPath + VideoName);
            var    writer         = new VideoFileWriter();
            var    numberOfFrames = (int)reader.FrameCount;
            Bitmap probeBitmap    = reader.ReadVideoFrame(0);

            if (numberOfFrames > probeBitmap.Width)        //if user want -> fit to original width
            {
                numberOfFrames = probeBitmap.Width;
            }
            writer.Open(VideoPath + "out.mp4", numberOfFrames, probeBitmap.Height, OutputFps, VideoCodec.H265);
            for (var x = 0; x < probeBitmap.Width; x++)
            {
                var convertedBitmap = new Bitmap(numberOfFrames, probeBitmap.Height);
                reader.Open(VideoPath + VideoName);
                for (var f = 0; f < numberOfFrames; f++)
                {
                    var currentBitmap = reader.ReadVideoFrame();
                    for (var y = 0; y < probeBitmap.Height; y++)
                    {
                        convertedBitmap.SetPixel(f, y, currentBitmap.GetPixel(x, y));
                    }
                    currentBitmap.Dispose();
                }
                writer.WriteVideoFrame(convertedBitmap);
                convertedBitmap.Dispose();
            }
            reader.Dispose();
            writer.Close();
        }
Example #5
0
        private void processMovie()
        {
            if (videoReader.IsOpen)
            {
                Bitmap videoFrame;

                processor.Background = videoReader.ReadVideoFrame();

                int i = 0;

                while ((videoFrame = videoReader.ReadVideoFrame()) != null)
                {
                    Bitmap preprocess = processor.preprocessImage(videoFrame);
                    this.Dispatcher.Invoke(new Action(() => frameCountLabel.Content  = Properties.Resources.FPS_LABEL_BEGIN + (int)(++i / videoReader.FrameRate) + "s"));
                    this.Dispatcher.Invoke(new Action(() => preprocessedImage.Source = VideoProcessor.convertBitmap(preprocess)));

                    Bitmap diff = processor.findDifference(preprocess);
                    preprocess.Dispose();

                    this.Dispatcher.Invoke(new Action(() => differenceImage.Source = VideoProcessor.convertBitmap(diff)));

                    Bitmap final = processor.showMotion(videoFrame, diff);
                    diff.Dispose();

                    this.Dispatcher.Invoke(new Action(() => finalImage.Source = VideoProcessor.convertBitmap(final)));
                    final.Dispose();
                    videoFrame.Dispose();
                }
                i = 0;
                videoReader.Dispose();
                videoReader.Close();
                restart();
            }
        }
Example #6
0
 private void pictureBox10_Click(object sender, EventArgs e)
 {
     if (textBox2.Text != "" && textBox3.Text != "" && textBox4.Text != "" && textBox5.Text != "")
     {
         Array.Clear(vbm, 0, vbm.Length);
         // create instance of video reader
         reader = new VideoFileReader();
         // open video file
         OpenFileDialog open = new OpenFileDialog();
         if (open.ShowDialog() == DialogResult.OK)
         {
             path = open.FileName;
             reader.Open(path);
             sir1  = textBox5.Text;
             vecu1 = sir1.Split(':');
             dur   = dur + Convert.ToInt32(vecu1[0]) * 60;
             dur   = dur + Convert.ToInt32(vecu1[1]);
             sec   = reader.FrameCount / dur;
             sir2  = textBox2.Text;
             vecu1 = sir2.Split(':');
             frm   = frm + Convert.ToInt32(vecu1[0]) * 60;
             frm   = frm + Convert.ToInt32(vecu1[1]);
             sir3  = textBox4.Text;
             vecu1 = sir3.Split(':');
             frm2  = frm2 + Convert.ToInt32(vecu1[0]) * 60;
             frm2  = frm2 + Convert.ToInt32(vecu1[1]);
             st    = frm * sec;
             stop  = frm2 * sec;
             // read 100 video frames out of it
             Image cont;
             for (int i = 0; i < reader.FrameCount; i++)
             {
                 if (i > stop)
                 {
                     break;
                 }
                 if (i >= st && i <= stop)
                 {
                     t3++;
                     vbm[t3] = reader.ReadVideoFrame();
                 }
                 if (i < st)
                 {
                     cont = reader.ReadVideoFrame();
                     cont.Dispose();
                 }
             }
             reader.Close();
         }
     }
     else
     {
         MessageBox.Show("Inainte de a incarca video-ul e nevoie sa completati specificatiile!");
     }
 }
Example #7
0
        private void timerPlayer_Tick(object sender, EventArgs e)
        {
            try
            {
                if (reader != null && reader.IsOpen)
                {
                    var frame = reader.ReadVideoFrame();

                    if (frame != null)
                    {
                        pictureBoxPlayer.Image = (Bitmap)frame;
                        frameIndex++;
                    }
                    else
                    {
                        timerPlayer.Stop();
                    }

                    trackBar1.Value = frameIndex;
                    ObtenerPresentarTiempo();
                    // frame.Dispose();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message);
            }
        }
Example #8
0
 public Task SkipFrame(int count = 1)
 {
     return(Task.Run(() =>
     {
         for (int i = 0; i < count; i++)
         {
             _reader.ReadVideoFrame().Dispose();
             CurrentFrame++;
         }
     }));
 }
Example #9
0
 private void MoveToNextFrame()
 {
     var bmp = _reader.ReadVideoFrame();
     if (bmp == null)
     {
         _reader.Close();
         _reader.Open(VideoPath);
         bmp = _reader.ReadVideoFrame();
     }
     _currentBitMap = bmp;
     _msSpentInCurrentFrame = 0;
 }
Example #10
0
        public async void StartAsync()
        {
            await Task.Run(() =>
            {
                double frameToSkip = 1;    //the number of frames to skip, setting to 1 never skips a frame
                double nextFrame   = 0;    //the next frame to analyze, we always analyze the first frame

                if (DesiredFramerate < reader.FrameRate)
                {
                    frameToSkip = (double)reader.FrameRate / DesiredFramerate;
                }

                BlackAndWhiteDoubleArray firstFrame;
                var secondFrame = new BlackAndWhiteDoubleArray(reader.ReadVideoFrame()); //load the first frame outside of the loop as prep

                output = new StreamWriter(resultsPath);

                //for some reason ~4-5 frames from the end I was getting out of index errors so I just said f**k it and quit 10 frames early
                for (CompletedFrames = 1; CompletedFrames < reader.FrameCount - 10; CompletedFrames++)
                {
                    //if (CompletedFrames % 200 == 0) Console.WriteLine($"OPTS: {CompletedFrames}");  //write progress to console, not required, but nice for debug

                    if ((int)nextFrame <= CompletedFrames)                                          //we do <= to catch any potential double fuckery
                    {
                        nextFrame += frameToSkip;
                        try
                        {
                            firstFrame  = secondFrame;
                            secondFrame = new BlackAndWhiteDoubleArray(reader.ReadVideoFrame());
                            var fs      = new FrameSet(firstFrame, secondFrame, output, BoxSize);
                            VideoToBitmap.framesToAnalyse.Add(fs);
                        }
                        catch (NullReferenceException) //writes to the debug log the frame that caused problems but still throws the exception, I may want to catch this elsewhere
                        {
                            Console.WriteLine(CompletedFrames);
                            throw;
                        }
                        if (nextFrame > reader.FrameCount - 10)
                        {
                            break;                                     //if the next frame to analyse is outside of the
                        }
                    }
                    else
                    {
                        reader.ReadVideoFrame().Dispose(); //reading and disposing of frames like this feels inefficient, but is more performant that putting the desired frame as a parameter
                    }
                }
                Console.WriteLine("Completed: " + videoPath);
            });
        }
Example #11
0
        public IEnumerator <Bitmap> GetEnumerator()
        {
            while (reader.IsOpen)
            {
                yield return(reader.ReadVideoFrame());

                for (int i = Step; i > 1; i--)
                {
                    reader.ReadVideoFrame();
                }
            }

            //Restart();
        }
Example #12
0
        private Bitmap GetBitmap(VideoFileReader reader, ref long currentFrame, int timeInSeconds)
        {
            long framesToSkip = reader.FrameRate * timeInSeconds - currentFrame;

            for (int i = 0; i < framesToSkip; ++i)
            {
                var bitmap = reader.ReadVideoFrame();
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }
            }
            currentFrame += framesToSkip;
            return(reader.ReadVideoFrame());
        }
Example #13
0
        /// <summary>
        /// 截取视频缩略图
        /// </summary>
        /// <param name="videoPath">视频路径</param>
        /// <param name="thumbImagePath">缩略图文件路径</param>
        /// <param name="thubWidth">缩略图指定的边长(正方形)</param>
        /// <param name="thubQuality">缩略图质量</param>
        public static void VideoSnapshots(string videoPath, string thumbImagePath, int thubWidth, int thubQuality)
        {
            VideoFileReader reader = new VideoFileReader();

            try
            {
                lock (lockData)
                {
                    reader.Open(videoPath);
                }
                Bitmap bitMap = reader.ReadVideoFrame();
                //创建目录
                string dirPath = Path.GetDirectoryName(thumbImagePath);
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                ImageHelper.CutForSquare(bitMap, thumbImagePath, thubWidth, thubQuality);
            }
            finally
            {
                reader.Dispose();
                reader.Close();
            }
        }
        static void PlayVideoAForgeFFMPEG(IStreamDeck deck, string videoPath)
        {
            using (VideoFileReader reader = new VideoFileReader())
            {
                reader.Open(videoPath);
                var fr          = reader.FrameRate;
                int frameLength = (int)Math.Round(1000.0 / fr);

                while (true)
                {
                    var sw = Stopwatch.StartNew();
                    using (var frame = reader.ReadVideoFrame())
                    {
                        if (frame == null)
                        {
                            return;
                        }
                        deck.DrawFullScreenBitmap(frame);
                        var wait = frameLength - (int)sw.ElapsedMilliseconds;
                        sw.Restart();
                        if (wait > 0)
                        {
                            Thread.Sleep(wait);
                        }
                    }
                }
            }
        }
        public int readStream(String name)
        {
            //Console.WriteLine("begin: {0} \ntotalFrameNum: {1}\ncurrentFrame: {2}\n fps: {3}\n", name, totalFrameNum, currentFrame, fps);
            //Console.ReadKey();
            writer = new VideoFileWriter();
            writer.Open(name, width, height, fps);
            int    reachEnd = 0;
            Bitmap temp;

            for (int i = currentFrame; i < currentFrame + fps && i < totalFrameNum; i++)
            {
                temp = reader.ReadVideoFrame();
                writer.WriteVideoFrame(temp);
                temp.Dispose();
                if (totalFrameNum == i + 1)
                {
                    reachEnd     = 1;
                    currentFrame = i;
                    writer.Close();
                    return(reachEnd);
                }
            }
            currentFrame = currentFrame + fps;
            writer.Close();
            //Console.WriteLine("after: {0} \ntotalFrameNum: {1}\ncurrentFrame: {2}\n", name, totalFrameNum, currentFrame);
            //Console.ReadKey();
            return(reachEnd);
        }
Example #16
0
        public static Vector3[,] Medium(string path, int steps = 100)
        {
            VideoFileReader reader = new VideoFileReader();

            reader.Open(path);

            Vector3[,] data = new Vector3[reader.Width, reader.Height];

            var temp = new Image <Rgb, float>(reader.Width, reader.Height);


            for (int i = 0; i < steps; i++)
            {
                using (Bitmap img = reader.ReadVideoFrame(i * (int)reader.FrameCount / steps))
                {
                    var arr = new Image <Rgb, float>(img);
                    temp.Accumulate(arr);
                    //temp.WriteRGB(img);
                    //data.ForEach(temp, (m, v) => m.Add(v));
                }
            }

            for (int x = 0; x < reader.Width; x++)
            {
                for (int y = 0; y < reader.Height; y++)
                {
                    Rgb rgb = temp[y, x];
                    data[x, y] = new Vector3((float)rgb.Red / steps / 255, (float)rgb.Green / steps / 255, (float)rgb.Blue / steps / 255);
                }
            }

            reader.Close();

            return(data);
        }
Example #17
0
        /* ---------------------------------------------------------------------
         * readVideo
         * ---------------------------------------------------------------------
         * Reads the video, saving all its frames and creating the intensity
         * matrix for each one.
         * Preconditions:
         *  -video of specified name exists
         */
        private void readVideo()
        {
            String VideoPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;

            VideoPath = VideoPath + "\\Resources\\20020924_juve_dk_02a.avi";
            bool intensityExists = readIntensityFile();

            using (var vFReader = new VideoFileReader())
            {
                vFReader.Open(VideoPath);

                // get video info to remake video when done
                this.vWidth     = vFReader.Width;
                this.vHeight    = vFReader.Height;
                this.vFramerate = vFReader.FrameRate;

                // store each image and intensities into the arrays
                for (int i = 1000; i < 5000; i++)
                {
                    System.Drawing.Bitmap bmpBaseOriginal = vFReader.ReadVideoFrame();
                    FrameMatrix[i] = bmpBaseOriginal;
                }
                vFReader.Close();

                if (!intensityExists)
                {
                    getIntensity();
                    writeIntensityFile();
                }
            }
        }
Example #18
0
        public void PlayAvi(string path, bool saveScreen = false)
        {
            var i = 0;

            try
            {
                var s      = new VideoFileSource(path);
                var reader = new VideoFileReader();
                var uri    = new Uri(path);
                reader.Open(uri.AbsolutePath);
                int framesToSkip = reader.FrameRate * 3600;

                var seconds = reader.FrameCount / reader.FrameRate;

                for (i = 0; i < reader.FrameCount; i++)
                {
                    try
                    {
                        var screen = reader.ReadVideoFrame();
                        Console.WriteLine(i);
                        if (i % 25 == 0)
                        {
                            screen.Save(@"screen_" + i.ToString() + ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
                        }
                    } catch { }
                }
            }
            catch (Exception e)
            {
            }
            finally
            {
            }
        }
Example #19
0
        //public void ToBinContours()
        //{
        //    newWorld::Emgu.CV.Image<newWorld::Emgu.CV.Structure.Gray, byte> _contour;
        //    Bitmap _tempToSave;//контур контуров
        //    Bitmap _frameInContour; //= mainFrameImage.ToImage<newWorld::Emgu.CV.Structure.Gray, byte>();
        //    //tessnet2.Tesseract tessocr = new tessnet2.Tesseract();
        //    //tessocr.SetVariable("tessedit_char_whitelist", "0123456789");
        //    //tessocr.Init(null, "eng", false);
        //    for (int i = 0; i < allContours.Count; i++)
        //    {
        //        //if ((allContours[i].Height  < 150) && (allContours[i].Height > 30) && (allContours[i].Width < 200) && (allContours[i].Width > 22))
        //        //{
        //            _frameInContour = currentMainFrameBitmap.Clone(allContours[i], currentMainFrameBitmap.PixelFormat);
        //            _contour = new newWorld::Emgu.CV.Image<newWorld::Emgu.CV.Structure.Gray, byte>(_frameInContour);
        //       // newWorld::Emgu.CV.CvInvoke.Threshold(_contour, _contour, 100, 250, newWorld::Emgu.CV.CvEnum.ThresholdType.Binary);

        //       // processorNumbersContours = new ImageProcessor();
        //       // processorNumbersContours.ProcessImage(_contour.Bitmap);
        //        string path = @"Бинаризированные приведенные контуры\" + i.ToString() + ".png";
        //        _contour.Save(path);

        //        //for (int j = 0; j < processorNumbersContours.contours.Count; j++)
        //        //{
        //        //    if ((processorNumbersContours.contours[j].BoundingRectangle.Width < 20) && (processorNumbersContours.contours[j].BoundingRectangle.Width > 10) && (processorNumbersContours.contours[j].BoundingRectangle.Height > 10) && (processorNumbersContours.contours[j].BoundingRectangle.Height < 20))
        //        //    {
        //        //        _tempToSave = _contour.Bitmap.Clone(processorNumbersContours.contours[j].BoundingRectangle, _contour.Bitmap.PixelFormat);
        //        //        //_tempToSave.Save(@"Бинаризированные приведенные контуры\" + i.ToString() + "_" + j.ToString() + ".png");
        //        //        // var text = tessocr.DoOCR(_tempToSave, Rectangle.Empty);
        //        //        _tempToSave.Dispose();
        //        //    }
        //        //    //}
        //        //    //    //newWorld::Emgu.CV.CvInvoke.Resize(_contour, _contour, new Size(50, 50), 0, 0, newWorld::Emgu.CV.CvEnum.Inter.Linear);
        //        //}
        //        _frameInContour.Dispose();
        //    }
        //}
        public void ReadVideo()
        {
            Regex regex = new Regex(@"Тестовые видеофайлы\\.+$");
            Match match = regex.Match(path);

            //nameLabel.Text = match.Value.Remove(0,6);
            reader.Open(path);
            frameCount             = reader.FrameCount;
            durationLabel.Text     = frameCount.ToString();
            label5.Text            = reader.Height.ToString() + "x" + reader.Width.ToString();
            currentMainFrameBitmap = reader.ReadVideoFrame(); // берем первый кадр и делаем на нем распознаванием
            frameForDrawing        = currentMainFrameBitmap.Clone(new Rectangle(0, 0, currentMainFrameBitmap.Width, currentMainFrameBitmap.Height), currentMainFrameBitmap.PixelFormat);

            RecognizePeopleDefault();// дефолтное распознавание
            //MyPeopleRecognize(); //Мое распознавание
        }
Example #20
0
        }//void

        public void parcala()
        {
            VideoFileReader reader = new VideoFileReader();
            IWMPMedia       saniye = axWindowsMediaPlayer1.newMedia(ofdVideoYukle.FileName);

            videoFrameList.Clear();

            reader.Open(ofdVideoYukle.FileName);
            this._TotalFrameCount = (int)saniye.duration * reader.FrameRate;
            this._VideoFPS        = reader.FrameRate;
            progressBar1.Maximum  = this._TotalFrameCount;
            FrameSayisi           = _TotalFrameCount;
            for (int i = 0; i < this._TotalFrameCount; i++)
            {
                Bitmap videoFrame = reader.ReadVideoFrame();
                string yol        = "C://Users//BegovicTeam//Desktop//video sıkıştırma//frameparcalanmis//" + "image" + i + ".mpeg";
                convertMpeg(videoFrame, yol);
                progressBar1.Value += 1;
            }
            reader.Close();
            reader.Dispose();

            birlestir();

            frameParcala.Abort();
        }
Example #21
0
        public List <byte> GetFileBytes(int start, int end, int increment, int boxSize)
        {
            VideoFileReader reader = new VideoFileReader();

            reader.Open(_filename);

            List <byte> fileBytes = new List <byte>();

            _progressCount = 0;

            for (int i = start; i < end; i++)
            {
                Console.WriteLine("i: " + i + " < " + end);
                using (Bitmap fileImage = reader.ReadVideoFrame(i)) {
                    if (i % increment == 0)
                    {
                        GetVideoFrameBytes(fileBytes, fileImage, boxSize);

                        _progressCount++;

                        ReportProgress(increment);
                    }
                }
            }

            return(fileBytes);
        }
Example #22
0
        //Méthode permettant de de créer un apercu d'une image à partir d'une vidéo et la situe à l'endroit de la vidéo
        public static string createPreviewFromVideo(string pathVideo, string cameraName)
        {
            //Path de l'image qui sera créé par la suite
            string pathImage = "";

            if (!String.IsNullOrEmpty(pathVideo))
            {
                VideoFileReader reader = new VideoFileReader();
                //Ouvre la video
                reader.Open(pathVideo);
                //Lit la première image
                Bitmap videoFrame = reader.ReadVideoFrame();
                if (String.IsNullOrEmpty(cameraName))
                {
                    pathImage = Path.GetDirectoryName(pathVideo) + @"\" + Path.GetFileNameWithoutExtension(pathVideo) + "image.png";
                }
                else
                {
                    pathImage = Path.GetDirectoryName(pathVideo) + @"\" + cameraName + "image.png";
                }
                //Ecrase l'image si le nom est déjà pris
                if (File.Exists(pathImage))
                {
                    File.Delete(pathImage);
                }

                videoFrame.Save(pathImage);
                //On libère les ressources
                videoFrame.Dispose();
                reader.Close();
            }

            return(pathImage);
        }
Example #23
0
        //Call following function only once...
        public void ReadVideoFile()
        {
            VideoFileReader reader       = new VideoFileReader();
            List <Bitmap>   frameCapture = new List <Bitmap>();

            reader.Open(Environment.CurrentDirectory + @"\20020924_juve_dk_02a_1.avi");
            // check some of its attributes
            Console.WriteLine("width:  " + reader.Width);
            Console.WriteLine("height: " + reader.Height);
            Console.WriteLine("fps:    " + reader.FrameRate);
            Console.WriteLine("codec:  " + reader.CodecName);
            // read 100 video frames out of it
            for (int i = 0; i < 5000; i++)
            {
                Bitmap videoFrame = reader.ReadVideoFrame();
                if (i < 1000)
                {
                    continue;
                }
                videoFrame.Save(Environment.CurrentDirectory + @"/images/VideoFrameImageDetails" + i + ".bmp");
                videoFrame.Dispose();
            }

            reader.Close();
        }
Example #24
0
        private void convert()
        {
            try
            {
                VideoFileReader reader = new VideoFileReader();
                reader.Open(m_mp4File);
                Bitmap videoFrame  = null;
                int    frame       = 0;
                int    scratchfile = 0;
                while ((videoFrame = reader.ReadVideoFrame()) != null)
                {
                    if (frame % reader.FrameRate == 0)
                    {
                        Console.WriteLine("Frame: " + frame);

                        byte[] buffer = imageToByteArray(videoFrame);
                        m_dictionary.Add(scratchfile, getMd5Hash(buffer));
                        videoFrame.Save("C:/temp/" + scratchfile.ToString() + ".png", ImageFormat.Png);
                        videoFrame.Dispose();
                        videoFrame = null;
                        ++scratchfile;
                    }
                    ++frame;
                }
                reader.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Example #25
0
        public async Task Transfer(VideoHeader header, Stream source)
        {
            Guard.NotNull(() => header, header);
            Guard.NotNull(() => source, source);

            var temp = Path.GetTempFileName();

            using (StreamWriter write = new StreamWriter(temp))
            {
                await source.CopyToAsync(write.BaseStream).ConfigureAwait(false);
            }

            try
            {
                using (VideoFileReader reader = new VideoFileReader())
                {
                    reader.Open(temp);
                    using (Bitmap videoFrame = reader.ReadVideoFrame())
                    {
                        videoFrame.Save(ResolveName(header), ImageFormat.Png);
                    }
                }
            }
            finally
            {
                File.Delete(temp);
            }
        }
        private static void Main()
        {
            var reader = new VideoFileReader();

            reader.Open(@"your video here");

            // video attributes
            Console.WriteLine("width:  " + reader.Width);
            Console.WriteLine("height: " + reader.Height);
            Console.WriteLine("fps:    " + reader.FrameRate);
            Console.WriteLine("codec:  " + reader.CodecName);

            // read video frames
            while (true)
            {
                using (var videoFrame = reader.ReadVideoFrame())
                {
                    if (videoFrame == null)
                    {
                        break;
                    }

                    // process the frame here
                }
            }

            reader.Close();
        }
Example #27
0
        public BitmapStream loadBitmapStream_wmv()
        {
            BitmapStream stream_tmp = new BitmapStream();

            for (int i = 0; i < bmpPerStream; i++)
            {
                //现在不会判断它停。。。
                if (video_wmv.IsOpen == false)
                {
                    return(stream_tmp);
                }
                Bitmap bitmap_tmp = video_wmv.ReadVideoFrame();
                if (bitmap_tmp != null)
                {
                    stream_tmp.addFrame(bitmap_tmp);
                }
                else
                {
                    finish = 1;
                    video_wmv.Close();
                    streamCount++;
                    return(stream_tmp);
                }
            }
            streamCount++;
            return(stream_tmp);
        }
Example #28
0
        static void Main(string[] args)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            VideoFileReader reader = new VideoFileReader();

            reader.Open(fileName);
            for (int i = 0; i < reader.FrameCount; i++)
            {
                read.Add(reader.ReadVideoFrame());
                write.Add(NegativGeneralas(read[i]));
            }

            VideoFileWriter writer = new VideoFileWriter();

            writer.Open("eredmeny_" + fileName, reader.Width, reader.Height, reader.FrameRate, VideoCodec.MPEG4, reader.BitRate);
            for (int i = 0; i < write.Count; i++)
            {
                writer.WriteVideoFrame(write[i]);
            }
            reader.Close();
            writer.Close();
            stopwatch.Stop();
            Console.WriteLine(stopwatch.Elapsed);
            Console.ReadLine();
        }
Example #29
0
        private static void VideoProcessing(string videoPath, string outputFolder)
        {
            VideoFileReader videoFileReader = new VideoFileReader();

            videoFileReader.Open(videoPath);
            Console.WriteLine("Video loaded (" + videoFileReader.FrameCount + " frames)");

            Size scaledSize = new Size((int)Math.Round(videoFileReader.Width * scalingFactor), (int)Math.Round(videoFileReader.Height * scalingFactor));

            Console.WriteLine("Analyzing frames");

            for (int i = 0; i < videoFileReader.FrameCount; i++)
            {
                DrawTextProgressBar(i + 1, (int)videoFileReader.FrameCount);
                using (Bitmap frame = videoFileReader.ReadVideoFrame())
                {
                    using (Bitmap scaled = new Bitmap(frame, scaledSize))
                    {
                        float brightness = scaled.BrightnessOfBrightestPixels(0.02);
                        if (brightness > 0.09f)
                        {
                            frame.Save(outputFolder + @"\" + i.ToString().PadLeft(5, '0') + ".bmp");
                        }
                    }
                }
            }
            videoFileReader.Close();

            Console.WriteLine("Done");
        }
Example #30
0
        //protected override bool StartCaptureCore()
        //{
        //        BitmapPool.Instance.Create(InterestRegion.Width, InterestRegion.Height, PixelFormat);

        //        return playLooper.Start();
        //}

        //protected override bool StopCaptureCore()
        //{
        //        return playLooper.Stop();
        //}

        protected override sealed ValueResult <Bitmap> CaptureCore()
        {
            if (ConnectState != ConnectState.Connected ||
                DispatchState != DispatchState.Established)
            {
                return(ValueResult <Bitmap> .Failed);
            }

            var bitmap = Pool.WriteLock();

            var frame = reader.ReadVideoFrame();

            BitmapConverter.ConvertTo(frame, bitmap);

            Pool.WriteUnlock(bitmap);

            //BitmapStorager.Save(bitmap, DateTime.Now.ToChineseLongFileName() + ".bmp");

            bitmap.TimeStamps["CaptureTime"] = DateTime.Now;

            var result = new ValueResult <Bitmap>(bitmap);

            OnCaptureSuccessed(new ValueEventArgs <Bitmap>(bitmap));

            return(result);
        }
 private static Bitmap GetFrameBitmap(int frame)
 {
     if (videoReader != null)
     {
         return(videoReader.ReadVideoFrame(frame));
     }
     return(null);
 }
Example #32
0
 public void VideoFileReaderTest()
 {
     var fileName = @"C:\Datos Lab\videos\480x360Videos\subject01.avi";
     var videoFile = new VideoFileReader();
     videoFile.Open(fileName);
     var bitmap = videoFile.ReadVideoFrame();
     var height = bitmap.Height;
     var width = bitmap.Width;
     videoFile.Close();
     Assert.IsTrue(height > 0 && width > 0);
 }
Example #33
0
        private void button2_Click(object sender, EventArgs e)
        {
            FileStream dosyamiz;
            StreamReader okuma;
            string yol = "C:\\manual_Jogging1.txt";

            dosyamiz = new FileStream(yol, FileMode.Open, FileAccess.Read);
            okuma = new StreamReader(dosyamiz);

            int n, a, b, c, d;
            int x1, x2, x3, x4;
            double xgec;

            System.Drawing.Graphics graphicsObj;

            graphicsObj = this.CreateGraphics();

            Pen myPen = new Pen(System.Drawing.Color.Red, 1);

            VideoFileReader reader = new VideoFileReader();
            IWMPMedia saniye = axWindowsMediaPlayer1.newMedia(ofVideoYukle.FileName);

            if (fbdFramePath.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show("Klasör seçilmedi");
            }

            string str_FramePath = fbdFramePath.SelectedPath + @"\";
            reader.Open(ofVideoYukle.FileName);
            this.TotalFrame = (int)saniye.duration * reader.FrameRate;
            this.Videofps = reader.FrameRate;
            for (int i = 0; i < 307; i++)
            {

                textBox1.Text = okuma.ReadLine();
                textBox2.Text = textBox1.Text.Replace("		", "");

                n = Convert.ToInt32(textBox2.Text.Substring(0, 1));
                a = Convert.ToInt32(textBox2.Text.Substring(1, 3));
                b = Convert.ToInt32(textBox2.Text.Substring(4, 3));
                c = Convert.ToInt32(textBox2.Text.Substring(7, 2));
                d = Convert.ToInt32(textBox2.Text.Substring(9, 2));

                if (i > 9)
                {
                    if (i == 48 || i == 49 || i == 50 || i == 51 || i == 52 || i == 53 || i == 54 || i == 55)
                    {
                        n = Convert.ToInt32(textBox2.Text.Substring(0, 2));
                        a = Convert.ToInt32(textBox2.Text.Substring(2, 2));
                        b = Convert.ToInt32(textBox2.Text.Substring(4, 3));
                        c = Convert.ToInt32(textBox2.Text.Substring(7, 2));
                        d = Convert.ToInt32(textBox2.Text.Substring(9, 2));
                    }

                    else
                    {
                        n = Convert.ToInt32(textBox2.Text.Substring(0, 2));
                        a = Convert.ToInt32(textBox2.Text.Substring(2, 3));
                        b = Convert.ToInt32(textBox2.Text.Substring(5, 3));
                        c = Convert.ToInt32(textBox2.Text.Substring(8, 2));
                        d = Convert.ToInt32(textBox2.Text.Substring(10, 2));
                    }

                }

                if (i > 99)
                {
                    n = Convert.ToInt32(textBox2.Text.Substring(0, 3));
                    a = Convert.ToInt32(textBox2.Text.Substring(3, 3));
                    b = Convert.ToInt32(textBox2.Text.Substring(6, 3));
                    c = Convert.ToInt32(textBox2.Text.Substring(9, 2));
                    d = Convert.ToInt32(textBox2.Text.Substring(11, 2));

                }

                x1 = a - c;
                x2 = b - ((3 * d) / 2);
                x3 = 2 * c;
                xgec = (Math.Sqrt(Math.Pow(c, 2) + Math.Pow(d, 2))) * 3;
                x4 = Convert.ToInt32(xgec);

                Rectangle myRectangle = new Rectangle(x1, x2, x3, x4);
                Bitmap videoFrame = reader.ReadVideoFrame();

                using (Graphics grafik = Graphics.FromImage(videoFrame as Image))
                {

                    grafik.DrawEllipse(myPen, myRectangle);

                }

                videoFrame.Save(str_FramePath + "Image" + i + ".jpg");
                videoFrame.Dispose();
            }

            reader.Close();
            reader.Dispose();
            MessageBox.Show("Video Frame lere ayrildi");
            button4.Enabled = true;
        }
Example #34
0
        private void btn_encode_Click(object sender, EventArgs e)
        {
            if (oform != null && File.Exists(oform.FileName)) { //has a filestream been opened?
                hScrollBar1.Enabled = false;
                checkBox1.Enabled = false;
                btn_encode.Enabled = false;
                // create instance of video reader
                VideoFileReader reader = new VideoFileReader();
                VideoFileWriter writer = new VideoFileWriter();
                reader.Open(oform.FileName);
                if (checkBox1.Checked) { //Is the user requesting a AVI?
                    writer.Open(apath + "output.wmv", 320, 200, reader.FrameRate, VideoCodec.WMV2);
                }
                // print some of its attributes
                logbox.Text += "Width: " + reader.Width + "px" + Environment.NewLine;
                logbox.Text += ("Height: " + reader.Height + "px" + Environment.NewLine);
                logbox.Text += ("Fps: " + reader.FrameRate + "fps"+ Environment.NewLine);
                logbox.Text += ("Codec: " + reader.CodecName + Environment.NewLine);
                logbox.Text += ("Frames: " + reader.FrameCount + Environment.NewLine);
                //start encoding classes
                TMVVideo tvid = new TMVVideo();
                TMVEncoder tmv = new TMVEncoder();
                //tmvframe.Threshold = hScrollBar1.Value;
                Bitmap videoFrame = new Bitmap(320,200);
                logbox.Text += "Conversion started @ " + DateTime.Now.ToString();
                string logtxt = logbox.Text;
                logbox.Text += "Current Frame: 0";
                TMVFont renderfont = new TMVFont(apath + "font.bin");
                TMVFrame tframe;
                for (int i = 0; i < reader.FrameCount; i++) {
                    videoFrame = resize_image(reader.ReadVideoFrame());
                    tframe = tmv.encode(videoFrame);
                    tvid.addFrame(tframe);
                    obox.Image = tframe.renderFrame(renderfont);
                    pbar.Value = (int)((i * 100) / (reader.FrameCount-1));
                    logbox.Text = logtxt + Environment.NewLine + "Current Frame: " + i + "/" + (reader.FrameCount-1);
                    if (checkBox1.Checked) { //Is the user requesting a AVI?
                        writer.WriteVideoFrame((Bitmap)obox.Image);
                    }
                    if (closing)
                    {
                        return;
                    }
                    fbox.Image = videoFrame;
                    Application.DoEvents();
                }
                logbox.Text += Environment.NewLine + "All frames converted, attempting to interleave audio.";
                if (File.Exists(apath + "temp.wav")) { //remove any previous streams
                    File.Delete(apath + "temp.wav");
                }
                AviManager aviManager = new AviManager(oform.FileName, true);
                try { //try to read the stream
                    AudioStream waveStream = aviManager.GetWaveStream();
                    logbox.Text += Environment.NewLine + "Audio stream found:";
                    logbox.Text += Environment.NewLine + "Sample Rate: " + waveStream.CountSamplesPerSecond.ToString();
                    logbox.Text += Environment.NewLine + "Bits:" + waveStream.CountBitsPerSample.ToString();
                    logbox.Text += Environment.NewLine + "Number of Channels: " + waveStream.CountChannels.ToString();
                    File.Delete(apath + "temp.wav");
                    waveStream.ExportStream(apath+"temp.wav");
                    waveStream.Close();
                    aviManager.Close();

                    byte[] audio_data = readWav(apath + "temp.wav");

                    if (reader.FrameRate > 99) { //sometimes frame rate is stored fixed point CRUDE
                        tvid.setFPS((decimal)(reader.FrameRate / 10.0));
                        tvid.loadAudio(audio_data);
                        tvid.save();
                    }
                    else {
                        tvid.setFPS(reader.FrameRate);
                        tvid.loadAudio(audio_data);
                        tvid.save();
                    }
                }
                catch { //error somewhere here, continue silent.
                    logbox.Text += Environment.NewLine+"Error, source video does not have WAV audio, video will be silent.";

                    if (reader.FrameRate > 99) { //sometimes frame rate is stored fixed point CRUDE
                        tvid.setFPS((decimal)(reader.FrameRate / 10.0));
                        tvid.loadAudio(new Byte[reader.FrameCount]);
                        tvid.save();
                    }
                    else {
                        tvid.setFPS(reader.FrameRate);
                        tvid.loadAudio(new Byte[reader.FrameCount]);
                        tvid.save();
                    }
                }

                logbox.Text += Environment.NewLine + "Conversion finished @ " + DateTime.Now.ToString();
                writer.Close();
                reader.Close();
                hScrollBar1.Enabled = true;
                checkBox1.Enabled = true;
                btn_encode.Enabled = true;

            }
            else {
                logbox.Text += Environment.NewLine + "Error: Select a file (Using File -> Open) before attempting to encode.";
            }
        }
Example #35
0
        private void keyFrame()
        {
            VideoFileReader readerShort= new VideoFileReader();
            readerShort.Open(name);

            // set many frame
            int Fcon = int.Parse(readerShort.FrameCount.ToString());
            // set frame/2
            int Fcount = Fcon / 2;

            for (int i = 0; i < readerShort.FrameCount; i++)
            {
                Bitmap videoFrame = readerShort.ReadVideoFrame();
                if (i == Fcount)
                {
                    hisVec(videoFrame);
                    keyF = ("..\\..\\..\\Keyframe\\" + Url2 + "_" + i + ".jpeg");
                    videoFrame.Save(keyF, ImageFormat.Jpeg);
                    break;
                }
                videoFrame.Dispose();
            }
            // close short video
            readerShort.Close();
        }
Example #36
0
        private void saveshot()
        {
            string str = Url;
            string[] sAry = str.Split('.');
            Url2 = sAry[0];

            VideoFileReader reader = new VideoFileReader();
            reader.Open(textBox1.Text);
            int co = 0;
            int end = int.Parse(reader.FrameCount.ToString());

            int countFrameCut = 0;
            VideoFileWriter writerShort = new VideoFileWriter();
            name = "..\\..\\..\\VideoName\\" + Url2 + "_" + Convert.ToString(countFrameCut) + ".avi";
            videoname = Url2 + "_" + countFrameCut + ".avi";
            writerShort.Open(name, reader.Width, reader.Height, reader.FrameRate, VideoCodec.MPEG4, 1000000);
            for (int i = 0; i < end; i++)
            {
                Bitmap videoFrame = reader.ReadVideoFrame();
                writerShort.WriteVideoFrame(videoFrame);
                videoFrame.Dispose();
                if (i == Savei[countFrameCut]) {
                    // cut short
                    writerShort.Close();

                    keyFrame();

                    if (countCutFrame != countFrameCut)
                    {
                        name = "..\\..\\..\\VideoName\\" + Url2 + "_" + Convert.ToString(countFrameCut) + ".avi";
                        videoname = Url2 + "_" + countFrameCut + ".avi";
                        writerShort.Open(name, reader.Width, reader.Height, reader.FrameRate, VideoCodec.MPEG4, 1000000);
                    }
                    countFrameCut++;
                }
            }
            writerShort.Close();
            reader.Close();

            /*
            for (int i = 0; i < Savei.Length; i++)
            {

                if (Savei[i] == 0)
                {
                    if (co == 0)
                    {
                        Savei[i] = end;
                        co = 1;
                    }
                    else
                    {

                        break;
                    }
                }

                VideoFileWriter writer = new VideoFileWriter();

                try
                {

                    name = "..\\..\\..\\VideoName\\" + Url2 + "_" + Convert.ToString(i) + ".avi";
                    videoname = Url2 + "_" + i + ".avi";
                    writer.Open(name, reader.Width, reader.Height, reader.FrameRate, VideoCodec.MPEG4, 1000000);

                    for (int j = 0; j < end; j++)
                    {
                        if (Savei[i] == j)
                        {
                            writer.Close();
                            break;
                        }
                        Bitmap videoFrame = reader.ReadVideoFrame();

                        writer.WriteVideoFrame(videoFrame);
                        videoFrame.Dispose();
                    }

                }
                catch (Exception exception)
                {
                    writer.Close();
                }

                if (i == 0)
                {
                    end = end - Savei[i];
                }
                else
                {
                    end = end - Math.Abs(Savei[i] - Savei[i - 1]);
                }

                keyFrame();

                //string constr = ConfigurationManager.ConnectionStrings["Db"].ConnectionString;
                //SqlConnection con = new SqlConnection(constr);
                //con.Open();

                //SqlCommand cmd = new SqlCommand("INSERT into CollectionShot (No,VideoName,PathVideoName,KeyFrame,HistrogrameVecter) " +
                //       " VALUES ( (Select count(*) from CollectionShot ),'" + videoname + "','" + name + "' , '" + keyF + "','" + Vechist + "')", con);
                //cmd.ExecuteNonQuery();
                //con.Close();

            }
            reader.Close();
            */
        }
Example #37
0
        private void keyFrame()
        {
            VideoFileReader reader = new VideoFileReader();
            reader.Open(textBox1.Text);
            int Fcon = int.Parse(reader.FrameCount.ToString());
            int Fcount = Fcon / 2;
            for (int i = 0; i < reader.FrameCount; i++)
            {
                Bitmap videoFrame = reader.ReadVideoFrame();
                if (i == Fcount)
                {
                    hisVec(videoFrame);
                    break;
                }

            }

            reader.Close();
        }
Example #38
0
        /// <summary>
        /// Method for reading the next frame from the video input stream. Can skip frames to speed up the resulting video
        /// </summary>
        /// <param name="reader">VideoFileReader object (the video input stream)</param>
        /// <param name="skipFrames">Frames to skip</param>
        /// <param name="currentFrame">Refference to the number of already processed frames from the input video.</param>
        /// <returns>A frame from the input video stream</returns>
        private static Bitmap GetFrame(VideoFileReader reader, long skipFrames, ref long currentFrame)
        {
            // skip frames
            for (int i = 0; (i < skipFrames - 1 || currentFrame < videoStart) && currentFrame < videoEnd; i++)
            {
                reader.ReadVideoFrame().Dispose();
                currentFrame++;
            }

            return reader.ReadVideoFrame();
        }
        /// <summary>
        /// Reason : To read video and read frames from it
        /// </summary>
        public void VideoProcessing()
        {
            VideoFileReader reader = new VideoFileReader();
            string path = @"C:\Users\Cuelogic\Desktop\sample images\videos\drop.avi";
            reader.Open(path);

            for (int i = 0; i < 100; i++)
            {
                Bitmap videoFrame = reader.ReadVideoFrame();
                videoFrame.Dispose();
            }
            reader.Close();
        }
Example #40
0
        private void Run_Click(object sender, EventArgs e)
        {
            VideoFileReader reader = new VideoFileReader();
            // open video file
            reader.Open(textBox1.Text);
            // check some of its attributes
            //Console.WriteLine("width:  " + reader.Width);
            //Console.WriteLine("height: " + reader.Height);
            //Console.WriteLine("fps:    " + reader.FrameRate);
            //Console.WriteLine("codec:  " + reader.CodecName);
            int[][] frameRGB = new int[reader.FrameCount][];
            // read 100 video frames out of it
            for (int i = 0; i < reader.FrameCount; i++)
            {
                //int disRed = 0;
                //int disGreen = 0;
                //int disBlue = 0;
                Bitmap videoFrame = reader.ReadVideoFrame();
                // process the frame somehow
                ImageStatistics rgbStatistics = new ImageStatistics(videoFrame);
                int[] redValues = rgbStatistics.Red.Values;
                int[] greenValues = rgbStatistics.Green.Values;
                int[] blueValues = rgbStatistics.Blue.Values;

                int[] his = new int[256];
                for (int j = 0; j < 256; j++)
                {
                    his[j] = (redValues[j] + greenValues[j] + blueValues[j]) / 3;

                }
                frameRGB[i] = his;

                //Bitmap videoFrame2 = reader.ReadVideoFrame();
                //// process the frame somehow
                //ImageStatistics rgbStatistics2 = new ImageStatistics(videoFrame2);
                //int[] redValues2 = rgbStatistics2.Red.Values;
                //int[] greenValues2 = rgbStatistics2.Green.Values;
                //int[] blueValues2 = rgbStatistics2.Blue.Values;

                //for (int j = 0; j < 256; j++)
                //{
                //    disRed = disRed + Math.Abs(redValues[j] - redValues2[j]);
                //    disGreen = disGreen + Math.Abs(greenValues[j] - greenValues2[j]);
                //    disBlue = disBlue + Math.Abs(blueValues[j] - blueValues2[j]);

                //}
                //int sumdis = disRed + disGreen + disBlue;
                //สร้างตัวแปรเก็บr+G+B เอาไว้หาค่าthredshold;กำหนดเอง
                // dispose the frame when it is no longer required
                videoFrame.Dispose();
            }

            reader.Close();
            Sdis = new int[frameRGB.Length - 1];
            for (int g = 0; g < frameRGB.Length - 1; g++)
            {
                int dis = 0;
                for (int k = 0; k < 256; k++)
                {

                    dis += Math.Abs(frameRGB[g][k] - frameRGB[g + 1][k]);
                }
                Sdis[g] = dis;
            }

            this.chart1.Titles.Add("Distance");
            Series series = this.chart1.Series.Add("Distance");
            for (int ss = 0; ss < frameRGB.Length - 1; ss++)
            {

                series.Points.AddXY(ss, Sdis[ss]);
            }
        }
Example #41
0
        public void test_read()
        {
            // create instance of video reader
            VideoFileReader reader = new VideoFileReader();
            // open video file
            reader.Open("test.avi");
            // check some of its attributes
            Console.WriteLine("width:  " + reader.Width);
            Console.WriteLine("height: " + reader.Height);
            Console.WriteLine("fps:    " + reader.FrameRate);
            Console.WriteLine("codec:  " + reader.CodecName);
            // read 100 video frames out of it
            for (int i = 0; i < 100; i++)
            {
                Bitmap videoFrame = reader.ReadVideoFrame();
                // process the frame somehow
                // ...

                // dispose the frame when it is no longer required
                videoFrame.Dispose();
            }
            reader.Close();
        }