AoiMethod.cs
3.5 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
103
104
105
106
107
108
109
110
111
112
113
114
using OpenCvSharp;
using OpenCvSharp.Extensions;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AOI
{
public abstract class AoiMethod
{
//public string FullTypeName { get; set; }
//public string PathDatas { get; set; }
public string MethodName { get; set; }
/// <summary>
/// 兴趣区域路径
/// </summary>
[Newtonsoft.Json.JsonIgnore()]
public GraphicsPath RoiPath { get; set; }
public PathData GetRoiPathData()
{
if (RoiPath != null)
{
return RoiPath.PathData;
}
return null;
}
public abstract ResultBean Check(Image standardImage, Image imageToCheck);
/// <summary>
/// 获取单通道的掩模图片
/// </summary>
/// <param name="img"></param>
/// <param name="path"></param>
/// <returns></returns>
public Image GetRoiMask(Image img, GraphicsPath path)
{
if (path != null)
{
GC.Collect();
var bounds = path.GetBounds();
if (bounds.Width > 0 && bounds.Height > 0)
{
try
{
Bitmap mask = new Bitmap(img.Width, img.Height);
using (Graphics g = Graphics.FromImage(mask))
{
var br = new TextureBrush(img);
g.FillPath(br, path);
g.Dispose();
}
return mask;
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
return null;
}
public Image GetRoiImage(Image image, GraphicsPath path, bool needCut)
{
Image maskImg = GetRoiMask(image, path);
if (maskImg != null)
{
var bounds = path.GetBounds();
int resultWidth = (int)bounds.Width;
int resultHeight = (int)bounds.Height;
var srcLocation = bounds.Location;
if (!needCut)
{
//获取带原图位置的大图
resultWidth = image.Width;
resultHeight = image.Height;
srcLocation = PointF.Empty;
}
Bitmap result = new Bitmap(resultWidth, resultHeight);
var dstRect = new RectangleF(0, 0, resultWidth, resultHeight);
var srcRect = new RectangleF(srcLocation.X, srcLocation.Y, resultWidth, resultHeight);
using (Graphics g = Graphics.FromImage(result))
{
//g.Clear(Color.Transparent);
g.DrawImage(maskImg, dstRect, srcRect, GraphicsUnit.Pixel);
g.Dispose();
}
result.MakeTransparent(Color.White);
return result;
}
return null;
}
public Image GetRoiImage(Image image, bool needCut)
{
return GetRoiImage(image, RoiPath, needCut);
}
public AoiMethod GetClone()
{
return (AoiMethod)this.MemberwiseClone();
}
}
}