C#测试程序
本页面提供C#测试程序的入门教程,方便大家快速上手。
在开始之前,请先确保你已经安装了:
- Visual Studio 2022 或者更高版本
- .NET Framework 4.7.2 或者更高版本
点击展开 Visual Studio 2022 版本信息

拉取代码
你可以使用以下命令拉取代码:
git clone https://github.com/dl-cv/OpenIVS
也可以直接在网站上下载zip:

下载完成之后,解压到本地,打开OpenIVS.sln文件:

编译工程
进去之后,选择 DlcvDemo 工程为启动工程,按 F5 编译即可。


代码解析
当你想看某个功能是怎么实现的时候,可以直接在 Form1.cs 中双击对应的按钮,查看它的具体代码。

加载模型
比如我们双击加载模型的按钮,可以看到以下对应代码:
private void button_loadmodel_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.RestoreDirectory = true;
openFileDialog.Filter = "深度视觉模型 (*.dvt;*.dvp;*.dvo;*.dvst;*.dvso;*.dvsp)|*.dvt;*.dvp;*.dvo;*.dvst;*.dvso;*.dvsp|所有文件 (*.*)|*.*";
openFileDialog.Title = "选择模型";
try
{
openFileDialog.InitialDirectory = Path.GetDirectoryName(Properties.Settings.Default.LastModelPath);
openFileDialog.FileName = Path.GetFileName(Properties.Settings.Default.LastModelPath);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string selectedFilePath = openFileDialog.FileName;
Properties.Settings.Default.LastModelPath = selectedFilePath;
Properties.Settings.Default.Save();
int device_id = GetSelectedDeviceId();
try
{
if (model != null)
{
model = null;
GC.Collect();
}
bool rpc_mode = false;
try
{
rpc_mode = this.checkBox_rpc_mode != null && this.checkBox_rpc_mode.Checked;
}
catch { }
model = new Model(selectedFilePath, device_id, rpc_mode);
button_getmodelinfo_Click(sender, e);
}
catch (Exception ex)
{
richTextBox1.Text = ex.Message;
}
}
}
代码比较长,重点就只有下面这一句:
model = new Model(selectedFilePath, device_id, rpc_mode);
模型推理
模型推理也是类似的,双击推理按钮,可以看到以下对应代码。因为代码比较多,我这边只节选部分:
// 读图
Mat image = Cv2.ImRead(image_path, ImreadModes.Color);
// 因为模型输入是RGB,所以需要转换BGR格式为RGB
Mat image_rgb = new Mat();
Cv2.CvtColor(image, image_rgb, ColorConversionCodes.BGR2RGB);
// 设置批处理大小,这里只是压测用,实际推理时无需拷贝多份图片
batch_size = (int)numericUpDown_batch_size.Value;
var image_list = new List<Mat>();
for (int i = 0; i < batch_size; i++)
{
image_list.Add(image_rgb);
}
// 设置推理参数
JObject data = new JObject();
data["threshold"] = (float)numericUpDown_threshold.Value;
data["with_mask"] = true;
// 推理
CSharpResult result = model.InferBatch(image_list, data);
返回结果解析
返回结果的格式是 CSharpResult,可以参考 高性能SDK套件 - C#接口 中的说明,也可以直接打开 OpenIVS/DlcvCsharpApi/DataTypes.cs 文件查看定义。