AoiMethodRgb.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 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 int minR = 1;
public int maxR = 255;
public int minG = 1;
public int maxG = 255;
public int minB = 1;
public int maxB = 255;
/// <summary>
/// 抽取出的像素最小占比
/// </summary>
public float minRate = 0;
/// <summary>
/// 抽取出的像素最大占比
/// </summary>
public float maxRate = 100;
public override ResultBean Check(Image standardImage, Image imageToCheck)
{
ResultBean resultBean = new ResultBean();
bool needCut = true;
Image standardRoiImg = GetRoiImage(standardImage, needCut);
resultBean.standardRoiImage = standardRoiImg;
Image currentRoiImg = GetRoiImage(imageToCheck, needCut);
resultBean.currentRoiImage = currentRoiImg;
float rate = GetRate(currentRoiImg, out Image dstImg);
bool result = false;
if(rate >= minRate && rate <= maxRate)
{
result = true;
}
resultBean.result = result;
return resultBean;
}
public float GetRate(Image img, out Image dstImg)
{
float percent = 0;
dstImg = null;
bool needCut = true;
Image currentRoiImg = GetRoiImage(img, needCut);
if (currentRoiImg != null)
{
Mat originalRoiMat = ImageUtil.ToMat(currentRoiImg);
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);
originalRoiMat.CopyTo(dst, dst);
dstImg = 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;
}
}
}