AoiColorMatchMethod.cs
2.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;
using OpenCvSharp.Blob;
using OpenCvSharp.XFeatures2D;
namespace AOI
{
/// <summary>
/// 颜色匹配,各种颜色占比(灰度图的直方图)进行匹配,不方向无关
/// </summary>
public class AoiColorMatchMethod : AoiMethod
{
/// <summary>
/// 相似度百分比
/// </summary>
public double SamePercent = 50;
public override ResultBean Check(Image standardImage, Image imageToCheck)
{
ResultBean resultBean = new ResultBean(MethodName,5,SamePercent,SamePercent);
bool needCut = true;
Image standardRoiImg = GetRoiImage(standardImage, needCut);
resultBean.standardRoiImage = standardRoiImg;
double percent = GetColorMatchPercent(standardImage, imageToCheck, out Image cutImg);
bool result = false;
if(SamePercent > 100)
{
SamePercent = 100;
}
if(percent >= SamePercent)
{
result = true;
}
resultBean.currentRoiImage = cutImg;
resultBean.result = result;
resultBean.percentValue =Math.Round( percent,3);
return resultBean;
}
/// <summary>
/// 获取模板相似度
/// </summary>
/// <param name="standardImage"></param>
/// <param name="imageToCheck"></param>
/// <param name="cutImg"></param>
/// <returns></returns>
public double GetColorMatchPercent(Image standardImage, Image imageToCheck, out Image cutImg)
{
bool needCut = true;
//标准图中的Mart区域
Image templateImage = GetRoiImage(standardImage, RoiPath, needCut);
//搜索区域
Image searchImage = GetRoiImage(imageToCheck, RoiPath, needCut);
cutImg = searchImage;
try
{
//searchImage = imageToCheck;
if (templateImage != null && searchImage != null)
{
Mat searchMat = ImageUtil.ToMat(new Bitmap(searchImage));
Mat templateMat = ImageUtil.ToMat(new Bitmap(templateImage));
//转换为灰度图,对直方图进行匹配
Mat searchHist = ImageUtil.GetGrayHist(searchMat);
Mat templateHist = ImageUtil.GetGrayHist(templateMat);
double compareValue = Cv2.CompareHist(templateHist, searchHist, HistCompMethods.Correl);
return compareValue * 100;
}
}catch(Exception ex)
{
Console.Write(ex.ToString());
}
return 0;
}
}
}