当前位置: 首页 > news >正文

C# OpenCvSharp Tracker 目标追踪

目录

效果

项目

代码

下载


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;}}
}

下载

源码下载

相关文章:

  • ✅技术社区项目—JWT身份验证
  • ​LeetCode解法汇总2583. 二叉树中的第 K 大层和
  • 【黑马程序员】2、TypeScript介绍_黑马程序员前端TypeScript教程,TypeScript零基础入门到实战全套教程
  • 【论文精读】ConvNeXt
  • 2.26作业
  • Kafka3.x进阶
  • 百亿大佬南存辉瞄准光伏板块,正泰电器分拆正泰安能上市
  • Android的LiveData
  • 机器学习理论知识学习
  • 化学分子Mol2文件格式与使用注意事项
  • vue-element-admin如何绕开系统的请求的路由,使用静态路由
  • 【GameFramework框架内置模块】4、内置模块之调试器(Debugger)
  • https://htmlunit.sourceforge.io/
  • SpringBoot快速入门(黑马学习笔记)
  • Vue.js+SpringBoot开发超市商品管理系统
  • 【编码】-360实习笔试编程题(二)-2016.03.29
  •  D - 粉碎叛乱F - 其他起义
  • miniui datagrid 的客户端分页解决方案 - CS结合
  • nodejs调试方法
  • Odoo domain写法及运用
  • Python3爬取英雄联盟英雄皮肤大图
  • SpiderData 2019年2月13日 DApp数据排行榜
  • SpringCloud(第 039 篇)链接Mysql数据库,通过JpaRepository编写数据库访问
  • Tornado学习笔记(1)
  • 欢迎参加第二届中国游戏开发者大会
  • 基于Mobx的多页面小程序的全局共享状态管理实践
  • 如何胜任知名企业的商业数据分析师?
  • 使用前端开发工具包WijmoJS - 创建自定义DropDownTree控件(包含源代码)
  • 以太坊客户端Geth命令参数详解
  • 译自由幺半群
  • - 转 Ext2.0 form使用实例
  • k8s使用glusterfs实现动态持久化存储
  • # Apache SeaTunnel 究竟是什么?
  • #周末课堂# 【Linux + JVM + Mysql高级性能优化班】(火热报名中~~~)
  • $L^p$ 调和函数恒为零
  • (11)工业界推荐系统-小红书推荐场景及内部实践【粗排三塔模型】
  • (145)光线追踪距离场柔和阴影
  • (2)(2.10) LTM telemetry
  • (BFS)hdoj2377-Bus Pass
  • (iPhone/iPad开发)在UIWebView中自定义菜单栏
  • (LeetCode 49)Anagrams
  • (补)B+树一些思想
  • (二十四)Flask之flask-session组件
  • (附源码)ssm教师工作量核算统计系统 毕业设计 162307
  • (附源码)计算机毕业设计ssm-Java网名推荐系统
  • (万字长文)Spring的核心知识尽揽其中
  • (一)Thymeleaf用法——Thymeleaf简介
  • (译)2019年前端性能优化清单 — 下篇
  • (转载)虚函数剖析
  • *上位机的定义
  • . NET自动找可写目录
  • .mkp勒索病毒解密方法|勒索病毒解决|勒索病毒恢复|数据库修复
  • .NET Core 和 .NET Framework 中的 MEF2
  • .net framework 4.0中如何 输出 form 的name属性。
  • .Net MVC + EF搭建学生管理系统