-
Notifications
You must be signed in to change notification settings - Fork 5
/
AbstractField.java
330 lines (284 loc) · 11.2 KB
/
AbstractField.java
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
package org.genericsystem.cv.retriever;
import java.lang.invoke.MethodHandles;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.IntStream;
import org.genericsystem.cv.Img;
import org.genericsystem.cv.Ocr;
import org.genericsystem.cv.utils.OCRPlasty;
import org.genericsystem.cv.utils.OCRPlasty.RANSAC;
import org.genericsystem.cv.utils.OCRPlasty.Tuple;
import org.genericsystem.cv.utils.RectToolsMapper;
import org.genericsystem.reinforcer.tools.GSRect;
import org.genericsystem.reinforcer.tools.RectangleTools;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;
import org.opencv.utils.Converters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractField {
protected static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
protected static final int MIN_SIZE_CONSOLIDATION = 5;
private static final int OCR_CONFIDENCE_THRESH = 0;
protected GSRect rect;
protected Map<String, Integer> labels;
protected String consolidated;
protected double confidence;
protected long attempts;
protected int deadCounter;
protected boolean truncated = false;
public boolean isTruncated() {
return truncated;
}
public void setTruncated(boolean truncated) {
this.truncated = truncated;
}
public AbstractField() {
this(new GSRect());
}
public AbstractField(GSRect rect) {
updateRect(rect);
this.labels = new HashMap<>();
this.consolidated = null;
this.attempts = 0;
this.confidence = 0;
this.deadCounter = 0;
}
public AbstractField(AbstractField other) {
updateRect(other.getRect());
this.labels = other.getLabels();
this.consolidated = other.getConsolidated();
this.attempts = other.getAttempts();
this.confidence = other.getConfidence();
this.deadCounter = other.getDeadCounter();
}
void updateRect(GSRect rect) {
if (rect.isTruncated() && this.rect != null) {
switch (rect.getTruncateDirection()) {
case GSRect.UP:
this.rect = new GSRect(rect.getX(), this.rect.getY(), rect.getWidth(), this.rect.getHeight());
break;
case GSRect.LEFT:
this.rect = new GSRect(rect.getX(), rect.getY(), this.rect.getWidth(), rect.getHeight());
break;
case GSRect.RIGHT:
this.rect = new GSRect(this.rect.getX(), rect.getY(), this.rect.getWidth(), rect.getHeight());
break;
case GSRect.BOTTOM:
this.rect = new GSRect(rect.getX(), rect.getY(), rect.getWidth(), this.rect.getHeight());
break;
case GSRect.BOTTOM_LEFT:
this.rect = new GSRect(rect.getX(), rect.getY(), this.rect.getWidth(), this.rect.getHeight());
break;
case GSRect.BOTTOM_RIGHT:
this.rect = new GSRect(this.rect.getX(), rect.getY(), this.rect.getWidth(), this.rect.getHeight());
break;
case GSRect.UP_LEFT:
this.rect = new GSRect(rect.getX(), this.rect.getY(), this.rect.getWidth(), this.rect.getHeight());
break;
case GSRect.UP_RIGHT:
this.rect = new GSRect(this.rect.getX(), this.rect.getY(), this.rect.getWidth(), this.rect.getHeight());
break;
default:
this.rect = rect;
}
} else {
this.rect = rect;
}
}
public void ocr(Img rootImg) {
if (rootImg.getSrc().empty() || rootImg.getSrc().width() <= 3 || rootImg.getSrc().height() <= 3)
return;
Rect largeRect = getLargeRect(rootImg, 0.03, 0.1);
if (largeRect.empty() || largeRect.width <= 3 || largeRect.height <= 3)
return;
// Prevent OpenCV assertion failure
if (!(0 <= largeRect.x && 0 <= largeRect.y && largeRect.x + largeRect.width < rootImg.getSrc().cols() && largeRect.y + largeRect.height < rootImg.getSrc().rows()))
return;
Mat roi = new Mat(rootImg.getSrc(), largeRect);
String ocr = Ocr.doWork(roi, OCR_CONFIDENCE_THRESH);
if (!ocr.isEmpty()) {
labels.merge(ocr, 1, Integer::sum);
attempts++;
}
roi.release();
}
public void consolidateOcr(boolean force) {
consolidateOcr(Integer.MAX_VALUE, force);
}
protected void consolidateOcr(int limit, boolean force) {
int labelsSize = getLabelsSize();
if (force || labelsSize >= MIN_SIZE_CONSOLIDATION) {
List<String> strings;
if (Integer.MAX_VALUE == limit)
strings = labels.entrySet().stream().collect(ArrayList<String>::new, (list, e) -> IntStream.range(0, e.getValue()).forEach(count -> list.add(e.getKey())), List::addAll);
else
strings = labels.entrySet().stream().sorted(Entry.<String, Integer>comparingByValue().reversed()).limit(limit).collect(ArrayList<String>::new, (list, e) -> IntStream.range(0, e.getValue()).forEach(count -> list.add(e.getKey())),
List::addAll);
Tuple res = OCRPlasty.correctStringsAndGetOutliers(strings, RANSAC.NORM_LEVENSHTEIN);
this.consolidated = res.getString().orElse(null);
this.confidence = res.getConfidence();
if (labelsSize >= 2 * MIN_SIZE_CONSOLIDATION)
res.getOutliers().forEach(outlier -> labels.remove(outlier));
} else {
logger.trace("Not enough labels to consolidate OCR (current minimum = {})", MIN_SIZE_CONSOLIDATION);
this.consolidated = null;
this.confidence = 0;
}
}
public void drawOcrPerspectiveInverse(Img display, Mat homography, Scalar color, int thickness) {
if (isOnDisplay(display)) {
Point[] targets = getRectPointsWithHomography(homography);
drawRect(display, targets, deadCounter == 0 ? color : new Scalar(0, 0, 255), thickness);
drawText(display, targets, new Scalar(0, 64, 255), thickness);
}
}
public void drawRect(Img stabilizedDisplay, Scalar color, int thickness) {
Point[] points = RectToolsMapper.gsPointToPoint(Arrays.asList(rect.decomposeClockwise())).toArray(new Point[0]);
drawRect(stabilizedDisplay, points, color, thickness);
}
public void drawRect(Img display, Point[] targets, Scalar color, int thickness) {
for (int i = 0; i < targets.length; ++i)
Imgproc.line(display.getSrc(), targets[i], targets[(i + 1) % targets.length], color, thickness);
}
public void drawText(Img display, Point[] targets, Scalar color, int thickness) {
if (consolidated != null) {
String text = Normalizer.normalize(consolidated, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "");
String conf = String.format("%.3f", confidence);
// --- //
Point topCenter = new Point((targets[0].x + targets[1].x) / 2, (targets[0].y + targets[1].y) / 2);
double l = Math.sqrt(Math.pow(targets[0].x - topCenter.x, 2) + Math.pow(targets[0].y - topCenter.y, 2));
Imgproc.line(display.getSrc(), new Point(topCenter.x, topCenter.y - 2), new Point(topCenter.x, topCenter.y - 20), color, 1);
Imgproc.putText(display.getSrc(), text, new Point(topCenter.x - l, topCenter.y - 22), Core.FONT_HERSHEY_TRIPLEX, 0.45, color, 1);
Imgproc.putText(display.getSrc(), conf, new Point(topCenter.x - l, topCenter.y - 12), Core.FONT_HERSHEY_TRIPLEX, 0.35, color.conj());
}
}
protected Point[] getRectPointsWithHomography(Mat homography) {
List<Point> points = RectToolsMapper.gsPointToPoint(Arrays.asList(rect.decomposeClockwise()));
MatOfPoint2f results = new MatOfPoint2f();
Core.perspectiveTransform(Converters.vector_Point2f_to_Mat(points), results, homography);
return results.toArray();
}
public Rect getLargeRect(Img imgRoot, double deltaW, double deltaH) {
int adjustW = 3 + Double.valueOf(Math.floor(rect.getWidth() * deltaW)).intValue();
int adjustH = 3 + Double.valueOf(Math.floor(rect.getHeight() * deltaH)).intValue();
Point tl = new Point(rect.tl().getX() - adjustW > 0 ? rect.tl().getX() - adjustW : 0, rect.tl().getY() - adjustH > 0 ? rect.tl().getY() - adjustH : 0);
Point br = new Point(rect.br().getX() + adjustW > imgRoot.width() ? imgRoot.width() : rect.br().getX() + adjustW, rect.br().getY() + adjustH > imgRoot.height() ? imgRoot.height() : rect.br().getY() + adjustH);
return new Rect(tl, br);
}
public boolean isOverlapping(GSRect otherRect) {
return this.rect.isOverlapping(otherRect);
}
public boolean isIn(AbstractField other) {
return rect.getInsider(other.getRect()).map(r -> r.equals(rect) ? true : false).orElse(false);
}
public boolean overlapsMoreThanThresh(GSRect otherRect, double overlapThreshold) {
return this.rect.inclusiveArea(otherRect) > overlapThreshold;
}
public boolean isClusteredWith(GSRect otherRect, double epsilon) {
return RectangleTools.isInCluster(this.rect, otherRect, epsilon);
}
public boolean isClusteredWith(GSRect otherRect, double epsilon, int sides) {
return RectangleTools.isInCluster(this.rect, otherRect, epsilon, sides);
}
public boolean isOnDisplay(Img display) {
GSRect imgRect = new GSRect(0, 0, display.width(), display.height());
return imgRect.isOverlapping(this.rect);
}
public boolean isConsolidated() {
return consolidated != null;
}
public void incrementDeadCounter() {
deadCounter++;
}
public void resetDeadCounter() {
deadCounter = 0;
}
public int getLabelsSize() {
return labels.entrySet().stream().mapToInt(entry -> entry.getValue()).sum();
}
public Map<String, Integer> getLabels() {
return labels;
}
public String getConsolidated() {
return consolidated;
}
public long getAttempts() {
return attempts;
}
public GSRect getRect() {
return rect;
}
public double getConfidence() {
return confidence;
}
public int getDeadCounter() {
return deadCounter;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("AbstractField: ").append("\n").append(" -> rect: ").append(rect).append("\n").append(" -> labels size: ").append(getLabelsSize()).append("\n").append(" -> consolidated: ").append(consolidated).append("\n").append(" -> confidence: ")
.append(confidence).append("\n");
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (attempts ^ (attempts >>> 32));
long temp;
temp = Double.doubleToLongBits(confidence);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((consolidated == null) ? 0 : consolidated.hashCode());
result = prime * result + deadCounter;
result = prime * result + ((labels == null) ? 0 : labels.hashCode());
result = prime * result + ((rect == null) ? 0 : rect.hashCode());
result = prime * result + (truncated ? 1231 : 1237);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AbstractField other = (AbstractField) obj;
if (attempts != other.attempts)
return false;
if (Double.doubleToLongBits(confidence) != Double.doubleToLongBits(other.confidence))
return false;
if (consolidated == null) {
if (other.consolidated != null)
return false;
} else if (!consolidated.equals(other.consolidated))
return false;
if (deadCounter != other.deadCounter)
return false;
if (labels == null) {
if (other.labels != null)
return false;
} else if (!labels.equals(other.labels))
return false;
if (rect == null) {
if (other.rect != null)
return false;
} else if (!rect.equals(other.rect))
return false;
if (truncated != other.truncated)
return false;
return true;
}
}