AoiMethodRgb.cs
3.4 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AOI
{
/// <summary>
/// 颜色抽取
/// </summary>
public class AoiMethodRgb : AoiMethod
{
public AoiMethodRgb()
{
minR = 0;
minG = 0;
minB = 0;
maxR = 255;
maxG = 255;
maxB = 255;
}
public int minR { get; set; }
public int maxR { get; set; }
public int minG { get; set; }
public int maxG { get; set; }
public int minB { get; set; }
public int maxB { get; set; }
/// <summary>
/// 抽取出的像素最小占比
/// </summary>
public float minRate { get; set; }
/// <summary>
/// 抽取出的像素最大占比
/// </summary>
public float maxRate { get; set; }
public override ResultBean Check(Image standardImage, Image imageToCheck)
{
ResultBean resultBean = new ResultBean(MethodName);
bool needCut = true;
Image standardRoiImg = GetRoiImage(standardImage, needCut);
resultBean.standardRoiImage = standardRoiImg;
Image cutImg;
float rate = GetRate(imageToCheck, out cutImg, out Image dstImage);
resultBean.currentRoiImage = cutImg;
bool result = false;
if(rate >= minRate && rate <= maxRate)
{
result = true;
}
resultBean.result = result;
return resultBean;
}
/// <summary>
/// 获取像素占比
/// </summary>
/// <param name="img">相机获取的大图</param>
/// <param name="cutImg">从大图中切割后的原图</param>
/// <param name="dstCutImg">切割并处理后的图片</param>
/// <returns></returns>
public float GetRate(Image img, out Image cutImg, out Image dstCutImg)
{
float percent = 0;
dstCutImg = null;
bool needCut = true;
cutImg = GetRoiImage(img, needCut);
if (cutImg != null)
{
Mat originalRoiMat = ImageUtil.ToMat(cutImg);
Mat roiMat = new Mat();
Cv2.CvtColor(originalRoiMat, roiMat, ColorConversionCodes.BGRA2BGR);
Mat dst = new Mat();
//如果不是矩形可能会把透明像素也计算进去,所以这里最小从1开始
int lowR = minR > 0 ? minR : 1;
int lowG = minG > 0 ? minG : 1;
int lowB = minB > 0 ? minB : 1;
Scalar minScalar = Scalar.FromRgb(lowR, lowG, lowB);
Scalar maxScalar = Scalar.FromRgb(maxR, maxG, maxB);
Cv2.InRange(roiMat, minScalar, maxScalar, dst);
int count = Cv2.CountNonZero(dst);
roiMat.CopyTo(dst, dst);
dstCutImg = ImageUtil.ToImage(dst);
//计算总像素
minScalar = Scalar.FromRgb(1, 1, 1);
maxScalar = Scalar.FromRgb(255, 255, 255);
Cv2.InRange(roiMat, minScalar, maxScalar, dst);
int totalCount = Cv2.CountNonZero(dst);
percent = count * 100.0f / totalCount;
}
return percent;
}
}
}