用OpenCVSharp (4.5)跑一遍 OpenCV 官方教程。
原 OpenCV 官方教程链接:OpenCV: Load Caffe framework models
using System;
using OpenCvSharp;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp.Dnn;
using System.IO;
namespace ConsoleApp1
{
class tutorial57 : ITutorial
{
public void Run()
{
int rszWidth = 224;
int rszHeight = 244;
float scale = 1;
Scalar mean = new Scalar(104, 117, 123);
Scalar std = new Scalar(0.0, 0.0, 0.0);
bool swapRB = true;
bool crop = false;
int inpWidth = 224;
int inpHeight = 161;
string model = @"I:\csharp\images\caffe\bvlc_googlenet.caffemodel";
string config = @"I:\csharp\images\caffe\bvlc_googlenet.prototxt";
string classesfile = @"I:\csharp\images\caffe\classification_classes_ILSVRC2012.txt";
// string imagefile = @"I:\csharp\images\caffe\space_shuttle.jpg";
// string imagefile = @"I:\csharp\images\caffe\bird.jpg";
// string imagefile = @"I:\csharp\images\caffe\butterfly.jpg";
string imagefile = @"I:\csharp\images\caffe\fish.jpg";
int backendId = 0; //auto
int targetId = 0; //cpu
// Open file with classes names.
var classes = File.ReadAllLines(classesfile)
.Select(line => line.Split(' ').Last())
.ToArray();
Net net = Net.ReadNet(model, config);
net.SetPreferableBackend(Backend.OPENCV);
net.SetPreferableTarget(Target.CPU);
// Create a window
string kWinName = "Deep learning image classification in OpenCV";
Cv2.NamedWindow(kWinName, WindowFlags.Normal);
Mat frame = new Mat(imagefile), blob = new Mat();
if (frame.Empty())
{
return;
}
if (rszWidth != 0 && rszHeight != 0)
{
Cv2.Resize(frame, frame, new Size(rszWidth, rszHeight));
inpHeight = rszHeight;
inpWidth = rszWidth;
}
blob = CvDnn.BlobFromImage(frame, scale, new Size(inpWidth, inpHeight), mean, swapRB, crop);
// Check std values.
if (std.Val0 != 0.0 && std.Val1 != 0.0 && std.Val2 != 0.0)
{
// Divide blob by std.
Cv2.Divide(blob, std, blob);
}
net.SetInput(blob);
Mat prob = net.Forward();
Point classIdPoint, minLoc;
double confidence, minValue;
Cv2.MinMaxLoc(prob.Reshape(1, 1), out minValue, out confidence, out minLoc, out classIdPoint);
int classId = classIdPoint.X;
// Put efficiency information.
double[] layersTimes;
double freq = Cv2.GetTickFrequency() / 1000;
double t = net.GetPerfProfile(out layersTimes) / freq;
String label = String.Format("Inference time:{0:00.0}ms", t);
Cv2.PutText(frame, label, new Point(0, 15), HersheyFonts.HersheySimplex, 0.5, new Scalar(0, 0, 255));
// Print predicted class.
label = String.Format("{0}:{1:0.000}", classes[classId], confidence);
Cv2.PutText(frame, label, new Point(0, 40), HersheyFonts.HersheySimplex, 0.5, new Scalar(0, 0, 255));
Cv2.ImShow(kWinName, frame);
Cv2.WaitKey();
}
}
}