C# OpenCvShar4.windows 图像追踪
C# 图像追踪
NuGet 包管理器 安装 OpenCvSharp4.Windows
using bmpTo;
using DlibDotNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using static pubVar;
using static CsAPI;
using Rectangle = DlibDotNet.Rectangle;
using OpenCvSharp;
using System.Diagnostics;
class pubThr
{
private void subsA(object sender, DoWorkEventArgs e)
{
while (bl == true)
{
var tracker = new CorrelationTracker();
int init = 0;
Mat temp = null;
using (var win = new ImageWindow())
{
win.SetPos(1000, 0);
//选择追踪对象
while (!win.IsClosed())
{
CsAPI.Rect fx = new CsAPI.Rect();
GetWindowRect(hwnd_main, out fx);//h为窗口句柄
int width = fx.Right - fx.Left; //窗口的宽度
int height = fx.Bottom - fx.Top; //窗口的高度
GetCursorPos(ref defPnt);
int xx = defPnt.X- fx.Left;
int yy = defPnt.Y- fx.Top;
bitmap = windowprint.GetWindow(hwnd_main);
temp = BitmapConverter.ToMat(bitmap);//BitmapToMat(bitmap);
System.Threading.Thread.Sleep(10);
//释放资源
//bitmap.Dispose();
//bitmap = null;
//g.Dispose();
//GC.Collect();
if (temp == null)
{
Debug.WriteLine("图像获取错误!");
return;
}
var array = new byte[temp.Width * temp.Height * temp.ElemSize()];
Marshal.Copy(temp.Data, array, 0, array.Length);
using (var cimg = Dlib.LoadImageData<BgrPixel>(array, (uint)temp.Height, (uint)temp.Width, (uint)(temp.Width * temp.ElemSize())))
{
init++;
if (init > 1)
{
if (t_start == 1)
{
Debug.WriteLine("开始追踪目标!");
t_start = 0;
blwindow = true;
//确定 追踪 位置
var rect2 = DRectangle.CenteredRect(xx, yy, 100, 100);
//开始追踪
tracker.StartTrack(cimg, rect2);
win.SetImage(cimg);
win.ClearOverlay();
win.AddOverlay(rect2);
break;
}
}
var rect1 = DRectangle.CenteredRect(xx, yy, 100, 100);
//显示图片
win.SetImage(cimg);
win.ClearOverlay();
//显示框
win.AddOverlay(rect1);
}
}
if (win.IsClosed()) blwindow = false;
//选择追踪对象
while (blwindow==true)
{
bitmap = windowprint.GetWindow(hwnd_main);
temp = BitmapConverter.ToMat(bitmap);//BitmapToMat(bitmap);
//System.Threading.Thread.Sleep(100);
if (temp == null)
{
Debug.WriteLine("图像获取错误!");
return;
}
var array = new byte[temp.Width * temp.Height * temp.ElemSize()];
Marshal.Copy(temp.Data, array, 0, array.Length);
using (var cimg = Dlib.LoadImageData<BgrPixel>(array, (uint)temp.Height, (uint)temp.Width, (uint)(temp.Width * temp.ElemSize())))
{
//更新追踪图像
tracker.Update(cimg);
win.SetImage(cimg);
win.ClearOverlay();
//获得追踪到的目标位置
DRectangle rect2 = tracker.GetPosition();
win.AddOverlay(rect2);
System.Diagnostics.Debug.WriteLine("OBJ RECT:" + (int)rect2.Left + " " + (int)rect2.Top + " " + (int)rect2.Width + " " + (int)rect2.Height);
System.Threading.Thread.Sleep(10);
}
}
}
}
}
public void thr_start()
{
if (objsub.IsBusy==false)
{
objsub.DoWork -= new DoWorkEventHandler(subsA);
objsub.DoWork += new DoWorkEventHandler(subsA);
objsub.WorkerSupportsCancellation = true;
objsub.WorkerReportsProgress = true;
objsub.RunWorkerAsync();
}
}
}
F2 获取窗口
F3 鼠标指向窗口定位图像
F4 重新加载
需要释放内存