Beispiel #1
0
 /// <summary>
 /// 基于OpenCv捕获视频流
 /// </summary>
 /// <param name="url"></param>
 /// <param name="action"></param>
 public void OpenCvCaptureVideoStream(string url, Action <OpenCvSharp.Mat> action)
 {
     using (OpenCvSharp.VideoCapture capture = new OpenCvSharp.VideoCapture(url))
     {
         //FourCC fourCC = FourCC.FromFourChars('m', 'p', '4', 'v');
         if (!capture.IsOpened())
         {
             return;
         }
         //double fps = capture.Get(VideoCaptureProperties.Fps);
         //double width = capture.Get(VideoCaptureProperties.FrameWidth);
         //double height = capture.Get(VideoCaptureProperties.FrameHeight);
         //OpenCvSharp.Size size = new OpenCvSharp.Size(width, height);
         using OpenCvSharp.Mat frame = new OpenCvSharp.Mat();
         while (_stopPlay == false)
         {
             if (capture.Read(frame))
             {
                 //win?.ShowImage(frame);
                 action?.Invoke(frame);
             }
         }
         frame.Dispose();
         capture.Dispose();
     }
 }
 public VideoMarkerDetector(OpenCvSharp.VideoCapture pack, int min_size)
 {
     marker_result    = new Dictionary <int, List <MarkerStructure> >();
     tracker_result   = new List <MarkerTrackerStructure>();
     min_tracker_size = min_size;
     m_data           = pack;
 }
Beispiel #3
0
        public MainWindow()
        {
            InitializeComponent();

            string filename;
            var    fileDlg = new OpenFileDialog();

            if (fileDlg.ShowDialog() == true)
            {
                filename = fileDlg.FileName;
            }
            else
            {
                MessageBox.Show("File is not selected!");
                return;
            }

            video = new OpenCvSharp.VideoCapture(filename);
            if (!video.IsOpened())
            {
                MessageBox.Show("Video is not valid!");
                return;
            }

            renderer = new EquirectToRect(new GLControl(), new System.Drawing.Size(1400, 900), 100 * (float)Math.PI / 180);
            renderer.Viewer.Paint += (sender, e) =>
            {
                renderer.Render(currentFrame);
                fps++;
            };
            renderer.Viewer.Dock = System.Windows.Forms.DockStyle.Fill;
            viewer.Child         = renderer.Viewer;

            DispatcherTimer renderingTimer = new DispatcherTimer();

            renderingTimer.Interval = TimeSpan.FromMilliseconds(/*1000 / video.Fps*/ 1);
            renderingTimer.Tick    += (sender, e) =>
            {
                if (DateTime.Now.Subtract(lastMeasureTime) > TimeSpan.FromSeconds(1))
                {
                    Title           = fps + " fps";
                    fps             = 0;
                    lastMeasureTime = DateTime.Now;
                }

                video.Read(currentFrame);
                if (currentFrame.Empty())
                {
                    return;
                }
                renderer.Viewer.Invalidate();
            };
            renderingTimer.Start();
        }
        public void AddVideoNode(OpenCvSharp.VideoCapture video, string video_name)
        {
            XmlNode      video_node      = _MetaData.CreateNode(XmlNodeType.Element, "video", null);
            XmlAttribute attribute_frame = _MetaData.CreateAttribute("frame");

            attribute_frame.Value = video.Fps.ToString();
            video_node.Attributes.Append(attribute_frame);
            XmlAttribute attribute_width = _MetaData.CreateAttribute("width");

            attribute_width.Value = video.FrameWidth.ToString();
            video_node.Attributes.Append(attribute_width);
            XmlAttribute attribute_height = _MetaData.CreateAttribute("height");

            attribute_height.Value = video.FrameHeight.ToString();
            video_node.Attributes.Append(attribute_height);
            video_node.InnerText = video_name;
            VideoNode.AppendChild(video_node);
        }
Beispiel #5
0
        public MainWindow()
        {
            InitializeComponent();

            headset = new FVRHeadset(EFVR_ClientCapabilities.Gaze | EFVR_ClientCapabilities.Orientation);

            headset.IsHardwareConnected(out bool isConnected);
            Debug.Assert(isConnected, "Hardware is not connected!");

            headset.IsHardwareReady(out bool isReady);
            Debug.Assert(isReady, "Hardware capabilities are not ready!");

            OpenFileDialog dialog = new OpenFileDialog();

            if (dialog.ShowDialog() == true)
            {
                filename = dialog.FileName;
            }
            else
            {
                MessageBox.Show("File is not selected!");
                return;
            }

            video = new OpenCvSharp.VideoCapture(filename);
            if (!video.IsOpened())
            {
                MessageBox.Show("Video is not valid!");
                return;
            }

            video_width  = (int)video.Get(OpenCvSharp.CaptureProperty.FrameWidth);
            video_height = (int)video.Get(OpenCvSharp.CaptureProperty.FrameHeight);

            OpenCvSharp.Cv2.NamedWindow("coord", OpenCvSharp.WindowMode.Normal);
            OpenCvSharp.Cv2.ResizeWindow("coord", 1600, 900);

            renderer = new EquirectToRect(new GLControl(), new System.Drawing.Size(1400, 900), 100 * (float)Math.PI / 180);
            renderer.Viewer.Paint += (sender, e) =>
            {
                renderer.Render(currentFrame);
            };
            renderer.Viewer.Dock = System.Windows.Forms.DockStyle.Fill;
            viewer.Child         = renderer.Viewer;

            renderingTimer          = new DispatcherTimer();
            renderingTimer.Interval = TimeSpan.FromMilliseconds(1);
            renderingTimer.Tick    += (s, e) =>
            {
                video.Read(currentFrame);
                if (currentFrame.Empty())
                {
                    video.Set(OpenCvSharp.CaptureProperty.PosFrames, 0);
                    return;
                }

                headset.GetHMDPose(out SFVR_Pose pose);

                using (OpenCvSharp.Mat coordmap = currentFrame.Clone())
                {
                    SFVR_Vec3 direction = pose.orientation * SFVR_Vec3.Forward;
                    GetCoord(direction, video_width, video_height, out int x, out int y);
                    OpenCvSharp.Cv2.Circle(coordmap, new OpenCvSharp.Point(x, y), 50, new OpenCvSharp.Scalar(0, 0, 255), -1);

                    OpenCvSharp.Cv2.ImShow("coord", coordmap);
                    OpenCvSharp.Cv2.WaitKey(1);
                }

                SFVR_Vec3 eulerAngle = pose.orientation.EulerAngles;

                renderer.Pitch = -MathHelper.DegreesToRadians(eulerAngle.x);
                renderer.Yaw   = MathHelper.DegreesToRadians(eulerAngle.y);
                renderer.Roll  = MathHelper.DegreesToRadians(eulerAngle.z);

                renderer.Viewer.Invalidate();
            };
            renderingTimer.Start();
        }
Beispiel #6
0
        static int Main(string[] args)
        {
            // print usage
            Console.WriteLine("Usage: dotnet csharp_demo.dll [OPTIONS]");
            Console.WriteLine("Examples:");
            Console.WriteLine("    To specify license directory (for online license for example): dotnet csharp_demo.dll --license_dir license_dir");
            Console.WriteLine("");

            // parse arguments
            bool    error   = false;
            Options options = new Options();

            CommandLine.Parser.Default.ParseArguments <Options>(args)
            .WithParsed <Options>(opts => options  = opts)
            .WithNotParsed <Options>(errs => error = true);

            // exit if argument parsign error
            if (error)
            {
                return(1);
            }

            // print values of arguments
            Console.WriteLine("Arguments:");
            foreach (var opt in options.GetType().GetProperties())
            {
                Console.WriteLine("--{0} = {1}", opt.Name, opt.GetValue(options, null));
            }
            Console.WriteLine();

            try
            {
                OpenCvSharp.Window window = new OpenCvSharp.Window("demo");
                // create worker
                // (we are expecting run from bin folder)
                Worker worker = new Worker(
                    options.config_dir,
                    options.capturer_config,
                    options.license_dir);

                // here we trying camera open with opencv
                const int desiredFrameWidht  = 1280;
                const int desiredFrameHeight = 720;

                int camera_id = 0;

                // VideoCapture camera;
                OpenCvSharp.VideoCapture camera = new OpenCvSharp.VideoCapture();


                for (; camera_id < 10; ++camera_id)
                {
                    camera.Open(camera_id);
                    camera.Set(OpenCvSharp.CaptureProperty.FrameWidth, desiredFrameWidht);
                    camera.Set(OpenCvSharp.CaptureProperty.FrameHeight, desiredFrameHeight);
                    OpenCvSharp.Mat frame = new OpenCvSharp.Mat();
                    for (int i = 0; i < 10; i++)
                    {
                        frame = camera.RetrieveMat();
                    }

                    if (frame.Empty())
                    {
                        Console.WriteLine("webcam " + camera_id + " not opened");
                        camera.Release();
                    }
                    else
                    {
                        break;
                    }
                }

                for (;;)
                {
                    OpenCvSharp.Mat frame;

                    //camera.Grab();
                    frame = camera.RetrieveMat();

                    if (frame.Empty())
                    {
                        break;
                    }

                    // give a frame to the worker
                    worker.work(frame);

                    if (27 == (char)OpenCvSharp.Cv2.WaitKey(10))
                    {
                        camera.Release();
                        break;
                    }
                }

                // force free resources
                // otherwise licence error may occur
                // when create sdk object in next time
                worker.dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine("! exception catched: '" + e + "' ... exiting");
                return(1);
            }
            Console.WriteLine("close program");
            return(0);
        }
Beispiel #7
0
        static void Main(string[] args)
        {
            var wb = OpenCvSharp.XPhoto.SimpleWB.Create();

            wb.P         = 0.2f;
            wb.OutputMin = 8.0f;

            var decodedFramesBlock = new TransformBlock <OpenCvSharp.Mat, OpenCvSharp.Mat>(
                mat =>
            {
                return(Task.Run(() => { wb.BalanceWhite(mat, mat); return mat; }));
            },
                new ExecutionDataflowBlockOptions
            {
                BoundedCapacity        = 10,
                MaxDegreeOfParallelism = 10,
                EnsureOrdered          = true,
            }
                );

            // var inputVideo = new OpenCvSharp.VideoCapture("2017_0928_105336_023.MOV");
            var inputVideo  = new OpenCvSharp.VideoCapture("YI004801.mp4");
            var outputVideo = new OpenCvSharp.VideoWriter("out_lina.mp4", "avc1", inputVideo.Fps, new OpenCvSharp.Size(inputVideo.FrameWidth, inputVideo.FrameHeight));

            ConcurrentQueue <OpenCvSharp.Mat> decodedFramesQueue = new ConcurrentQueue <OpenCvSharp.Mat>();

            // decoder
            Task decodeTask = Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    var mat = inputVideo.RetrieveMat();
                    if (mat.Height == 0)
                    {
                        Console.WriteLine("DECODED");
                        decodedFramesBlock.Complete();
                        break;
                    }
                    decodedFramesBlock.SendAsync(mat).Wait();
                }
            });

            Task writeTask = Task.Factory.StartNew(() =>
            {
                int c = 0;
                OpenCvSharp.Mat mat;
                while (!decodedFramesBlock.Completion.IsCompleted)
                {
                    ++c;
                    mat = decodedFramesBlock.Receive();
                    outputVideo.Write(mat);
                    mat.Dispose();
                    Console.WriteLine("Frame " + c + " of " + inputVideo.FrameCount);
                }
            });

            decodeTask.Wait();
            writeTask.Wait();

            Console.WriteLine("ready!");
            outputVideo.Release();

            /*
             * var channels = img.Split();
             * channels = channels.Select(c => c.EqualizeHist()).ToArray();
             * foreach(var channel in channels)
             * {
             *  channel.ConvertTo(channel, channel.Type(), 0.9, 0);
             * }
             * OpenCvSharp.Cv2.Merge(channels, img);
             */
        }
Beispiel #8
0
        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult res = openFileDialog1.ShowDialog();

            if (res == DialogResult.OK)
            {
                string ext = System.IO.Path.GetExtension(openFileDialog1.FileName);

                if (ext.ToLower() == ".bmp" || ext.ToLower() == ".jpg" || ext.ToLower() == ".jpeg" || ext.ToLower() == ".png")
                {
                    pictureBox1.Image = CreateImage(openFileDialog1.FileName);
                }
                if (ext.ToLower() == ".avi" || ext.ToLower() == ".mp4")
                {
                    System.IO.Directory.SetCurrentDirectory(apppath);
                    System.IO.DirectoryInfo target = new System.IO.DirectoryInfo(@"main\LR\calendar");
                    foreach (System.IO.FileInfo file in target.GetFiles())
                    {
                        file.Delete();
                    }
                    int image_num = 1;
                    video = true;
                    OpenCvSharp.VideoCapture vcap = new OpenCvSharp.VideoCapture(openFileDialog1.FileName);
                    while (vcap.IsOpened())
                    {
                        if (stopping)
                        {
                            break;
                        }

                        OpenCvSharp.Mat mat = new OpenCvSharp.Mat();

                        if (vcap.Read(mat))
                        {
                            if (pictureBox1.Image != null)
                            {
                                pictureBox1.Image.Dispose();//Memory release
                            }

                            if (mat.IsContinuous())
                            {
                                pictureBox1.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);

                                //OpenCvSharp.Cv2.Resize(mat, mat, OpenCvSharp.Size(), 0, 0);
                                string filename = string.Format(@"main\LR\calendar\{0:D4}.png", image_num);
                                //pictureBox1.Image.Save(filename, System.Drawing.Imaging.ImageFormat.Png);

                                OpenCvSharp.Cv2.ImWrite(filename, mat, (int[])null);
                                image_num++;
                                //if (image_num > 10) break;
                            }
                            else
                            {
                                break;
                            }
                            Application.DoEvents(); // 非推奨
                        }
                        else
                        {
                            break;
                        }
                        System.Threading.Thread.Sleep((int)(1000 / vcap.Fps));

                        mat.Dispose();//Memory release
                    }
                    Fps = vcap.Fps;
                    vcap.Dispose();//Memory release
                    stopping = false;

                    pictureBox1.Image = CreateImage(@"main\LR\calendar\0001.png");
                }
            }
        }
Beispiel #9
0
        private void button1_Click(object sender, EventArgs e)
        {
            folder = "";
            DialogResult res = openFileDialog1.ShowDialog();

            if (res == DialogResult.OK)
            {
                label1.Text = "Image is loading";
                label1.Refresh();
                string ext = System.IO.Path.GetExtension(openFileDialog1.FileName);

                if (ext.ToLower() == ".bmp" || ext.ToLower() == ".jpg" || ext.ToLower() == ".jpeg" || ext.ToLower() == ".png")
                {
                    pictureBox1.Image = CreateImage(openFileDialog1.FileName);
                }
                if (ext.ToLower() == ".avi" || ext.ToLower() == ".mp4")
                {
                    System.IO.Directory.SetCurrentDirectory(apppath);
                    System.IO.DirectoryInfo target = new System.IO.DirectoryInfo(@"main\tecoGAN\LR\calendar");
                    foreach (System.IO.FileInfo file in target.GetFiles())
                    {
                        file.Delete();
                    }
                    int image_num = 1;
                    video = true;
                    OpenCvSharp.VideoCapture vcap = new OpenCvSharp.VideoCapture(openFileDialog1.FileName);
                    while (vcap.IsOpened())
                    {
                        if (stopping)
                        {
                            break;
                        }

                        OpenCvSharp.Mat mat = new OpenCvSharp.Mat();
                        if (image_num % 9 == 0)
                        {
                            label1.Text = "";
                            label1.Refresh();
                        }
                        else
                        {
                            label1.Text = "Image is loading";
                            label1.Refresh();
                        }
                        if (vcap.Read(mat))
                        {
                            if (pictureBox1.Image != null)
                            {
                                pictureBox1.Image.Dispose();//Memory release
                            }

                            if (mat.IsContinuous())
                            {
                                pictureBox1.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);
                                {
                                    //pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;

                                    Bitmap bmp = new Bitmap(
                                        pictureBox1.Image,
                                        pictureBox1.Image.Width * 4,
                                        pictureBox1.Image.Height * 4);

                                    pictureBox1.Image = bmp;
                                }

                                if (!checkBox1.Checked)
                                {
                                    OpenCvSharp.Cv2.Resize(mat, mat, new OpenCvSharp.Size((int)((float)mat.Width * (float)numericUpDown1.Value), (int)((float)mat.Height * (float)numericUpDown1.Value)), 0, 0);
                                }
                                else
                                {
                                    OpenCvSharp.Cv2.Resize(mat, mat, new OpenCvSharp.Size((int)(0.5f + (float)mat.Width / (float)numericUpDown1.Value), (int)(0.5f + (float)mat.Height / (float)numericUpDown1.Value)), 0, 0);
                                }

                                string filename = string.Format(@"main\tecoGAN\LR\calendar\{0:D4}.png", image_num);
                                //pictureBox1.Image.Save(filename, System.Drawing.Imaging.ImageFormat.Png);

                                OpenCvSharp.Cv2.ImWrite(filename, mat, (int[])null);
                                image_num++;
                                //if (image_num > 10) break;
                            }
                            else
                            {
                                break;
                            }
                            Application.DoEvents(); // 非推奨
                        }
                        else
                        {
                            break;
                        }
                        System.Threading.Thread.Sleep((int)(1000 / vcap.Fps));

                        mat.Dispose();//Memory release
                    }
                    Fps = vcap.Fps;
                    vcap.Dispose();//Memory release
                    stopping = false;

                    pictureBox1.Image = CreateImage(@"main\tecoGAN\LR\calendar\0001.png");
                }
                label1.Text = "";
                label1.Refresh();
                MessageBox.Show("finished");
            }
        }