C# OpenCvSharp Tracker 目标追踪

时间:2024-02-24 17:59:09

目录

效果

项目

代码

下载


C# OpenCvSharp Tracker 目标追踪

效果

项目

代码

using OpenCvSharp;
using OpenCvSharp.Extensions;
using OpenCvSharp.Tracking;
using System;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;

namespace C__OpenCvSharp_Tracker_目标追踪
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string filename = "";
        bool play = false;
        Tracker tracker;

        VideoCapture capture;
        bool m_mouseDown = false;
        bool m_mouseMove = false;

        System.Drawing.Point startPoint = new System.Drawing.Point();
        System.Drawing.Point endPoint = new System.Drawing.Point();

        Mat currentFrame = new Mat();
        Rect roi = new Rect();

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.SelectedIndex = 0;
            toolStripStatusLabel1.Text = "请打开视频文件";
            label2.Text = "";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Video files (*.avi)|*.avi|MP4 files (*.mp4)|*.mp4";
            ofd.RestoreDirectory = true;
            ofd.CheckFileExists = true;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                filename = ofd.FileName;
                toolStripStatusLabel1.Text = filename;
                capture = new VideoCapture(filename);
                if (!capture.IsOpened())
                {
                    toolStripStatusLabel1.Text = " 打开视频文件失败";
                    return;
                }
                capture.Read(currentFrame);
                if (!currentFrame.Empty())
                {
                    pictureBox1.Image = BitmapConverter.ToBitmap(currentFrame);
                    timer1.Interval = (int)(1000.0 / capture.Fps);
                    timer1.Enabled = true;

                    m_mouseMove = false;
                    m_mouseDown = false;
                    pictureBox2.Image = null;
                }

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            play = true;
            if (pictureBox2.Image != null)
            {
                switch (comboBox1.SelectedIndex)
                {
                    case 0:
                    default:
                        tracker = TrackerCSRT.Create();
                        break;
                    case 1:
                        tracker = TrackerGOTURN.Create();
                        break;
                    case 2:
                        tracker = TrackerKCF.Create();
                        break;
                    case 3:
                        tracker = TrackerMIL.Create();
                        break;
                }
                tracker.Init(currentFrame, roi);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            play = false;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (play)
            {
                capture.Read(currentFrame);
                if (currentFrame.Empty())
                {
                    play = false;
                    pictureBox1.Image = null;
                    pictureBox2.Image = null;

                    timer1.Enabled = false;
                    return;
                }
                if (pictureBox2.Image != null && tracker != null)
                {
                    tracker.Update(currentFrame, ref roi);
                    Cv2.Rectangle(currentFrame, roi, Scalar.Red);
                    label2.Text = String.Format("ROI:({0},{1})-({2},{3})", roi.X, roi.Y, roi.X + roi.Width, roi.Y + roi.Height);
                }
                pictureBox1.Image = BitmapConverter.ToBitmap(currentFrame);
            }
        }

        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            if (!m_mouseDown || !m_mouseMove)
                return;
            Graphics g = e.Graphics;
            Pen p = new Pen(Color.Blue, 2);
            Rectangle rect = new Rectangle(startPoint.X, startPoint.Y, (endPoint.X - startPoint.X), (endPoint.Y - startPoint.Y));
            g.DrawRectangle(p, rect);
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (pictureBox1.Image == null)
                return;
            if (!m_mouseDown) return;

            m_mouseMove = true;
            endPoint = e.Location;

            pictureBox1.Invalidate();
        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            if (!m_mouseDown || !m_mouseMove)
                return;
            m_mouseDown = false;
            m_mouseMove = false;

            System.Drawing.Point image_startPoint = ConvertCooridinate(startPoint);
            System.Drawing.Point image_endPoint = ConvertCooridinate(endPoint);
            if (image_startPoint.X < 0)
                image_startPoint.X = 0;
            if (image_startPoint.Y < 0)
                image_startPoint.Y = 0;
            if (image_endPoint.X < 0)
                image_endPoint.X = 0;
            if (image_endPoint.Y < 0)
                image_endPoint.Y = 0;
            if (image_startPoint.X > currentFrame.Cols)
                image_startPoint.X = currentFrame.Cols;
            if (image_startPoint.Y > currentFrame.Rows)
                image_startPoint.Y = currentFrame.Rows;
            if (image_endPoint.X > currentFrame.Cols)
                image_endPoint.X = currentFrame.Cols;
            if (image_endPoint.Y > currentFrame.Rows)
                image_endPoint.Y = currentFrame.Rows;

            label2.Text = String.Format("ROI:({0},{1})-({2},{3})", image_startPoint.X, image_startPoint.Y, image_endPoint.X, image_endPoint.Y);
            int w = (image_endPoint.X - image_startPoint.X);
            int h = (image_endPoint.Y - image_startPoint.Y);
            if (w > 10 && h > 10)
            {
                roi = new Rect(image_startPoint.X, image_startPoint.Y, w, h);

                Mat roi_mat = currentFrame[roi];
                pictureBox2.Image = BitmapConverter.ToBitmap(roi_mat);
            }
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (pictureBox1.Image == null)
                return;
            play = false;
            m_mouseDown = true;

            startPoint = e.Location;
        }

        private System.Drawing.Point ConvertCooridinate(System.Drawing.Point point)
        {
            System.Reflection.PropertyInfo rectangleProperty = this.pictureBox1.GetType().GetProperty("ImageRectangle", BindingFlags.Instance | BindingFlags.NonPublic);
            Rectangle pictureBox = (Rectangle)rectangleProperty.GetValue(this.pictureBox1, null);

            int zoomedWidth = pictureBox.Width;
            int zoomedHeight = pictureBox.Height;

            int imageWidth = pictureBox1.Image.Width;
            int imageHeight = pictureBox1.Image.Height;

            double zoomRatex = (double)(zoomedWidth) / (double)(imageWidth);
            double zoomRatey = (double)(zoomedHeight) / (double)(imageHeight);
            int black_left_width = (zoomedWidth == this.pictureBox1.Width) ? 0 : (this.pictureBox1.Width - zoomedWidth) / 2;
            int black_top_height = (zoomedHeight == this.pictureBox1.Height) ? 0 : (this.pictureBox1.Height - zoomedHeight) / 2;

            int zoomedX = point.X - black_left_width;
            int zoomedY = point.Y - black_top_height;

            System.Drawing.Point outPoint = new System.Drawing.Point();
            outPoint.X = (int)((double)zoomedX / zoomRatex);
            outPoint.Y = (int)((double)zoomedY / zoomRatey);

            return outPoint;
        }

    }
}

using OpenCvSharp;
using OpenCvSharp.Extensions;
using OpenCvSharp.Tracking;
using System;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;

namespace C__OpenCvSharp_Tracker_目标追踪
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string filename = "";
        bool play = false;
        Tracker tracker;

        VideoCapture capture;
        bool m_mouseDown = false;
        bool m_mouseMove = false;

        System.Drawing.Point startPoint = new System.Drawing.Point();
        System.Drawing.Point endPoint = new System.Drawing.Point();

        Mat currentFrame = new Mat();
        Rect roi = new Rect();

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.SelectedIndex = 0;
            toolStripStatusLabel1.Text = "请打开视频文件";
            label2.Text = "";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Video files (*.avi)|*.avi|MP4 files (*.mp4)|*.mp4";
            ofd.RestoreDirectory = true;
            ofd.CheckFileExists = true;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                filename = ofd.FileName;
                toolStripStatusLabel1.Text = filename;
                capture = new VideoCapture(filename);
                if (!capture.IsOpened())
                {
                    toolStripStatusLabel1.Text = " 打开视频文件失败";
                    return;
                }
                capture.Read(currentFrame);
                if (!currentFrame.Empty())
                {
                    pictureBox1.Image = BitmapConverter.ToBitmap(currentFrame);
                    timer1.Interval = (int)(1000.0 / capture.Fps);
                    timer1.Enabled = true;

                    m_mouseMove = false;
                    m_mouseDown = false;
                    pictureBox2.Image = null;
                }

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            play = true;
            if (pictureBox2.Image != null)
            {
                switch (comboBox1.SelectedIndex)
                {
                    case 0:
                    default:
                        tracker = TrackerCSRT.Create();
                        break;
                    case 1:
                        tracker = TrackerGOTURN.Create();
                        break;
                    case 2:
                        tracker = TrackerKCF.Create();
                        break;
                    case 3:
                        tracker = TrackerMIL.Create();
                        break;
                }
                tracker.Init(currentFrame, roi);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            play = false;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (play)
            {
                capture.Read(currentFrame);
                if (currentFrame.Empty())
                {
                    play = false;
                    pictureBox1.Image = null;
                    pictureBox2.Image = null;

                    timer1.Enabled = false;
                    return;
                }
                if (pictureBox2.Image != null && tracker != null)
                {
                    tracker.Update(currentFrame, ref roi);
                    Cv2.Rectangle(currentFrame, roi, Scalar.Red);
                    label2.Text = String.Format("ROI:({0},{1})-({2},{3})", roi.X, roi.Y, roi.X + roi.Width, roi.Y + roi.Height);
                }
                pictureBox1.Image = BitmapConverter.ToBitmap(currentFrame);
            }
        }

        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            if (!m_mouseDown || !m_mouseMove)
                return;
            Graphics g = e.Graphics;
            Pen p = new Pen(Color.Blue, 2);
            Rectangle rect = new Rectangle(startPoint.X, startPoint.Y, (endPoint.X - startPoint.X), (endPoint.Y - startPoint.Y));
            g.DrawRectangle(p, rect);
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (pictureBox1.Image == null)
                return;
            if (!m_mouseDown) return;

            m_mouseMove = true;
            endPoint = e.Location;

            pictureBox1.Invalidate();
        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            if (!m_mouseDown || !m_mouseMove)
                return;
            m_mouseDown = false;
            m_mouseMove = false;

            System.Drawing.Point image_startPoint = ConvertCooridinate(startPoint);
            System.Drawing.Point image_endPoint = ConvertCooridinate(endPoint);
            if (image_startPoint.X < 0)
                image_startPoint.X = 0;
            if (image_startPoint.Y < 0)
                image_startPoint.Y = 0;
            if (image_endPoint.X < 0)
                image_endPoint.X = 0;
            if (image_endPoint.Y < 0)
                image_endPoint.Y = 0;
            if (image_startPoint.X > currentFrame.Cols)
                image_startPoint.X = currentFrame.Cols;
            if (image_startPoint.Y > currentFrame.Rows)
                image_startPoint.Y = currentFrame.Rows;
            if (image_endPoint.X > currentFrame.Cols)
                image_endPoint.X = currentFrame.Cols;
            if (image_endPoint.Y > currentFrame.Rows)
                image_endPoint.Y = currentFrame.Rows;

            label2.Text = String.Format("ROI:({0},{1})-({2},{3})", image_startPoint.X, image_startPoint.Y, image_endPoint.X, image_endPoint.Y);
            int w = (image_endPoint.X - image_startPoint.X);
            int h = (image_endPoint.Y - image_startPoint.Y);
            if (w > 10 && h > 10)
            {
                roi = new Rect(image_startPoint.X, image_startPoint.Y, w, h);

                Mat roi_mat = currentFrame[roi];
                pictureBox2.Image = BitmapConverter.ToBitmap(roi_mat);
            }
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (pictureBox1.Image == null)
                return;
            play = false;
            m_mouseDown = true;

            startPoint = e.Location;
        }

        private System.Drawing.Point ConvertCooridinate(System.Drawing.Point point)
        {
            System.Reflection.PropertyInfo rectangleProperty = this.pictureBox1.GetType().GetProperty("ImageRectangle", BindingFlags.Instance | BindingFlags.NonPublic);
            Rectangle pictureBox = (Rectangle)rectangleProperty.GetValue(this.pictureBox1, null);

            int zoomedWidth = pictureBox.Width;
            int zoomedHeight = pictureBox.Height;

            int imageWidth = pictureBox1.Image.Width;
            int imageHeight = pictureBox1.Image.Height;

            double zoomRatex = (double)(zoomedWidth) / (double)(imageWidth);
            double zoomRatey = (double)(zoomedHeight) / (double)(imageHeight);
            int black_left_width = (zoomedWidth == this.pictureBox1.Width) ? 0 : (this.pictureBox1.Width - zoomedWidth) / 2;
            int black_top_height = (zoomedHeight == this.pictureBox1.Height) ? 0 : (this.pictureBox1.Height - zoomedHeight) / 2;

            int zoomedX = point.X - black_left_width;
            int zoomedY = point.Y - black_top_height;

            System.Drawing.Point outPoint = new System.Drawing.Point();
            outPoint.X = (int)((double)zoomedX / zoomRatex);
            outPoint.Y = (int)((double)zoomedY / zoomRatey);

            return outPoint;
        }

    }
}

下载

源码下载