Files
CheckDevice/Check.Main/Common/LogoTemplateTrainer.cs
2025-10-20 14:47:17 +08:00

63 lines
2.0 KiB
C#

using HalconDotNet;
using System;
using System.Collections.Generic;
using System.IO;
namespace HalconTemplateMatch
{
public class LogoTemplateTrainer
{
/// <summary>
/// 从多张样本图像生成模板并保存到文件
/// </summary>
/// <param name="imagePaths">训练图片路径集合</param>
/// <param name="saveDir">模板保存目录</param>
public void TrainAndSaveTemplates(List<string> imagePaths, string saveDir)
{
if (!Directory.Exists(saveDir))
Directory.CreateDirectory(saveDir);
int index = 0;
foreach (var path in imagePaths)
{
HObject ho_Image;
HOperatorSet.ReadImage(out ho_Image, path);
// 转灰度
HOperatorSet.Rgb1ToGray(ho_Image, out HObject ho_Gray);
// 二值化
HOperatorSet.Threshold(ho_Gray, out HObject ho_Region, 128, 255);
// 提取连通域
HOperatorSet.Connection(ho_Region, out HObject ho_Connected);
HOperatorSet.SelectShapeStd(ho_Connected, out HObject ho_Selected, "max_area", 70);
// ROI 约束
HOperatorSet.ReduceDomain(ho_Gray, ho_Selected, out HObject ho_ROI);
// 创建形状模板
HTuple modelID;
HOperatorSet.CreateShapeModel(
ho_ROI,
"auto",
new HTuple(0).TupleRad(),
new HTuple(360).TupleRad(),
"auto",
"auto",
"use_polarity",
"auto",
"auto",
out modelID);
// 保存模板到文件
string modelFile = Path.Combine(saveDir, $"logo_model_{index}.shm");
HOperatorSet.WriteShapeModel(modelID, modelFile);
Console.WriteLine($"训练完成并保存模板: {modelFile}");
index++;
}
}
}
}