用OpenCVSharp 4.5 跑一遍 OpenCV 官方教程
原OpenCV官方教程链接:OpenCV: Meanshift and Camshift
核心函数:meanShift
using System;
using OpenCvSharp;
namespace ConsoleApp1
{
class tutorial37 : ITutorial
{
public void Run()
{
string filename = @"I:\csharp\videos\slow_traffic_small.mp4";
VideoCapture capture = new VideoCapture(filename);
if (!capture.IsOpened())
{
//error in opening the video input
Console.WriteLine("Unable to open file!");
return;
}
Mat frame = new Mat(), roi = new Mat(), hsv_roi = new Mat(), mask = new Mat();
// take first frame of the video
capture.Read(frame);
// setup initial location of window
Rect track_window = new Rect(300, 200, 100, 50); // simply hardcoded the values
// set up the ROI for tracking
roi = frame[track_window];
Cv2.NamedWindow("ROI", WindowFlags.AutoSize);
Cv2.ImShow("ROI", roi);
Cv2.CvtColor(roi, hsv_roi, ColorConversionCodes.BGR2HSV);
Cv2.InRange(hsv_roi, new Scalar(0, 60, 32), new Scalar(180, 255, 255), mask);
float[] range_ = { 0, 180 };
float[][] range = { range_ };
Mat roi_hist = new Mat();
int[] histSize = { 180 };
int[] channels = { 0 };
Cv2.CalcHist(new Mat[] { hsv_roi }, channels, mask, roi_hist, 1, histSize, range);
Cv2.Normalize(roi_hist, roi_hist, 0, 255, NormTypes.MinMax);
// Setup the termination criteria, either 10 iteration or move by atleast 1 pt
TermCriteria term_crit = new TermCriteria(CriteriaTypes.Eps | CriteriaTypes.Count, 10, 1);
while (true)
{
Mat hsv = new Mat(), dst = new Mat();
capture.Read(frame);
if (frame.Empty())
break;
Cv2.CvtColor(frame, hsv, ColorConversionCodes.BGR2HSV);
Rangef[] ranges = new Rangef[] { new Rangef(0, 180) };
Cv2.CalcBackProject(new Mat[] { hsv }, channels, roi_hist, dst, ranges);
// apply meanshift to get the new location
Cv2.MeanShift(dst, ref track_window, term_crit);
// Draw it on image
Cv2.Rectangle(frame, track_window, 255, 2);
Cv2.ImShow("img2", frame);
int keyboard = Cv2.WaitKey(30);
if (keyboard == 'q' || keyboard == 27)
break;
}
}
}
}