用 C# 和 ONNX Runtime 实现图像验证码识别

本示例展示如何在 C# 中加载训练好的 ONNX 模型,并实现图像验证码的预测识别。

一、准备工作

  1. 安装 ONNX Runtime NuGet 包
    在 Visual Studio 的 NuGet 管理器中添加:

Microsoft.ML.OnnxRuntime
可选图像处理支持:
更多内容访问ttocr.com或联系1436423940
SixLabors.ImageSharp
二、模型说明
建议在 Python 中训练并导出模型为 ONNX 格式:

PyTorch 示例

torch.onnx.export(model, dummy_input, "captcha_model.onnx", input_names=["input"], output_names=["output"])
模型输入格式应为 [1, 3, 60, 160],输出为 [1, 4, 36](4 个字符位置,每个位置为 36 类概率)。

三、C# 图像处理与输入转换

using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;

float[] LoadImageAsTensor(string imagePath)
{
using var image = Image.Load(imagePath);
image.Mutate(x => x.Resize(160, 60));

float[] tensor = new float[3 * 60 * 160];
int idx = 0;
for (int y = 0; y < 60; y++)
{
    for (int x = 0; x < 160; x++)
    {
        var pixel = image[x, y];
        tensor[idx++] = (pixel.R / 255f - 0.5f) / 0.5f;
        tensor[idx++] = (pixel.G / 255f - 0.5f) / 0.5f;
        tensor[idx++] = (pixel.B / 255f - 0.5f) / 0.5f;
    }
}
return tensor;

}
四、加载模型并进行预测

var session = new InferenceSession("captcha_model.onnx");

var inputTensor = new DenseTensor(LoadImageAsTensor("test.png"), new[] { 1, 3, 60, 160 });
var inputs = new List {
NamedOnnxValue.CreateFromTensor("input", inputTensor)
};

var result = session.Run(inputs);
var output = result.First().AsTensor().ToArray();

string characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string prediction = "";

for (int i = 0; i < 4; i++)
{
float max = -1;
int maxIdx = -1;
for (int j = 0; j < 36; j++)
{
float score = output[i * 36 + j];
if (score > max)
{
max = score;
maxIdx = j;
}
}
prediction += characters[maxIdx];
}

Console.WriteLine($"预测结果: {prediction}");
五、效果说明
预测输出是按字符位置拼接的结果。

模型是预训练的 CNN+LSTM 类网络(建议在 Python 中准备)。

ONNX 模型支持跨平台部署,C# 可结合 WPF、Blazor、ASP.NET 实现前后端系统。

posted @ 2025-05-27 17:30  ttocr、com  阅读(154)  评论(0)    收藏  举报