58 lines
		
	
	
		
			2.0 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
			
		
		
	
	
			58 lines
		
	
	
		
			2.0 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
| using HalconTemplateMatch;
 | |
| using System;
 | |
| using System.Collections.Generic;
 | |
| using System.Linq;
 | |
| using System.Text;
 | |
| using System.Threading.Tasks;
 | |
| using System.Drawing;
 | |
| 
 | |
| namespace Check.Main.Infer
 | |
| {
 | |
|     public class HalconTemplateDetector : IDetector
 | |
|     {
 | |
|         private LogoMatcher _matcher; // 使用您现有的 LogoMatcher
 | |
|         private double _scoreThreshold = 0.5; // 可以从 ModelSettings 中配置
 | |
| 
 | |
|         public void Initialize(string modelPath, object detectionSettings = null)
 | |
|         {
 | |
|             _matcher = new LogoMatcher();
 | |
|             _matcher.LoadTemplates(modelPath); // modelPath 现在是 Halcon 模板目录
 | |
| 
 | |
|             // 如果 detectionSettings 包含阈值,可以在这里解析
 | |
|             if (detectionSettings is HalconDetectionSettings halconSettings)
 | |
|             {
 | |
|                 _scoreThreshold = halconSettings.ScoreThreshold;
 | |
|             }
 | |
|         }
 | |
| 
 | |
|         public DetectionResult Detect(Bitmap image)
 | |
|         {
 | |
|             if (_matcher == null)
 | |
|                 throw new InvalidOperationException("HalconTemplateDetector 未初始化。");
 | |
| 
 | |
|             Bitmap resultImage;
 | |
|             double score = _matcher.FindLogo(image, out resultImage);
 | |
|             bool isOk = score >= _scoreThreshold;
 | |
|             string message = isOk ? "OK" : "NG";
 | |
| 
 | |
|             // 如果需要绘制结果图像,可以在 LogoMatcher 中添加绘制逻辑并返回
 | |
|             // 假设 LogoMatcher 也可以返回一个带有匹配标记的 Bitmap
 | |
|             // Bitmap resultImage = _matcher.DrawResults(image, score);
 | |
| 
 | |
|             return new DetectionResult(isOk, message, score); //, resultImage
 | |
|         }
 | |
| 
 | |
|         public void Dispose()
 | |
|         {
 | |
|             // LogoMatcher 如果有需要释放的资源,可以在这里处理
 | |
|         }
 | |
|     }
 | |
| 
 | |
|     // 辅助设置类,用于传递给 HalconTemplateDetector
 | |
|     public class HalconDetectionSettings
 | |
|     {
 | |
|         public double ScoreThreshold { get; set; } = 0.5;
 | |
|         // 可以添加其他 Halcon 匹配参数
 | |
|     }
 | |
| }
 |