链接:https://pan.baidu.com/s/1I9N3lRe_t9C24IKJRcv89Q?pwd=1212
由于OpenCVSharp缺少相关api,这次使用EmguCv,这个demo网上都是python版本的,抄写为C#
使用ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt和frozen_inference_graph.pb模型
public class EasyObjectDetection
{
public static void Run()
{
string modelPathBase = @"D:\SourceCode\Models\";
string classesfile = modelPathBase + "coco.names";
string configPath = modelPathBase + "ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt";
string weightsPath = modelPathBase + "frozen_inference_graph.pb";
var thres = 0.5f;
var cap = new VideoCapture(modelPathBase + "Road_traffic_video2.mp4");
string[] classes = File.ReadAllLines(classesfile);
var net = new Emgu.CV.Dnn.DetectionModel(weightsPath, configPath);
//net.SetPreferableBackend(Backend.Cuda);
//net.SetPreferableTarget(Target.Cuda);
net.SetInputSize(new Size(320, 320));
net.SetInputScale(1.0 / 127.5);
net.SetInputMean(new Emgu.CV.Structure.MCvScalar(127.5, 127.5, 127.5));
net.SetInputSwapRB(true);
Mat frame = new Mat();
while (true)
{
var isSuccess = cap.Read(frame);
var classIds = new VectorOfInt();
var confs = new VectorOfFloat();
var bbox = new VectorOfRect();
var indices = new VectorOfInt();
net.Detect(frame, classIds, confs, bbox, confThreshold: 0.5f);
DnnInvoke.NMSBoxes(bbox, confs, thres, 0.2f, indices);
for (int i = 0; i < indices.Size; i++)
{
var confidence = confs[i].ToString();
var classId = classIds[i] - 1;
string classname = classes[classId];
Rectangle box = bbox[indices[i]];
CvInvoke.Rectangle(frame, box, new Emgu.CV.Structure.MCvScalar(255, 0, 255), 2);
CvInvoke.PutText(frame, classes[classId].ToUpper(), new Point(box.X + 2, box.Y + 2),
Emgu.CV.CvEnum.FontFace.HersheyPlain, 1, new Emgu.CV.Structure.MCvScalar(0, 0, 0), 1);
}
CvInvoke.Imshow("output", frame);
int c = CvInvoke.WaitKey(5);
if (c == 27)
{ // ESC退出
break;
}
}
}
}