-
Notifications
You must be signed in to change notification settings - Fork 5
/
Fields.java
398 lines (343 loc) · 12.5 KB
/
Fields.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package org.genericsystem.cv.retriever;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.genericsystem.cv.Img;
import org.genericsystem.cv.utils.ParallelTasks;
import org.genericsystem.cv.utils.RectToolsMapper;
import org.genericsystem.reinforcer.tools.GSPoint;
import org.genericsystem.reinforcer.tools.GSRect;
import org.opencv.calib3d.Calib3d;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import org.opencv.utils.Converters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Fields extends AbstractFields<Field> {
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private static final int MAX_DELETE_UNMERGED = 5;
private static final int OCR_TIMEOUT = 100;
public Fields(List<Field> fields) {
super(fields);
}
public Fields() {
super();
}
public void reset() {
//displayFieldsTree();
fields = new ArrayList<>();
}
@Override
public void drawOcrPerspectiveInverse(Img display, Mat homography, int thickness) {
stream().forEach(field -> field.drawWithHomography(display, homography, thickness));
}
public void drawFieldsOnStabilized(Img stabilized) {
stream().forEach(field -> field.draw(stabilized, 1));
}
public void drawFieldsOnStabilizedDebug(Img stabilized) {
for (GSRect rect : mergeRectsList(stabilized)) {
Point[] targets = RectToolsMapper.gsPointToPoint(Arrays.asList(rect.decomposeClockwise())).toArray(new Point[0]);
for (int i = 0; i < targets.length; ++i)
Imgproc.line(stabilized.getSrc(), targets[i], targets[(i + 1) % targets.length], new Scalar(255, 0, 0), 1);
}
}
public void displayFieldsTree() {
StringBuffer sb = new StringBuffer();
sb.append("\n").append("--- FIELDS ---").append("\n");
getRoots().forEach(field -> sb.append(field.recursiveToString()));
sb.append("\n").append("--- /FIELDS ---").append("\n");
System.out.println(sb.toString());
}
public List<Field> getRoots() {
return fields.stream().filter(field -> field.isOrphan()).collect(Collectors.toList());
}
public void consolidate(Img img) {
fields.forEach(f -> {
if(f.isInFrame(img)){
f.incrementDeadCounter();
f.adjustLockLevel(-0.5);
}
});
mergeRects(img, 0.70);
removeDeadTrees();
}
public List<GSRect> mergeRectsList(Img img) {
RectDetector rd = new RectDetector(img);
List<GSRect> rects = rd.getRects(200, 11, 3, new Size(11, 3));
List<GSRect> children = rd.getRects(40, 17, 3, new Size(7, 3));
return cleanList(rects, children, 0.70);
}
public List<GSRect> cleanList(List<GSRect> bigRects, List<GSRect> smallRects, double overlapThreshold) {
smallRects.removeIf(smallRect -> bigRects.stream().anyMatch(bigRect -> smallRect.inclusiveArea(bigRect) > overlapThreshold));
return Stream.concat(smallRects.stream().filter(smallRect -> bigRects.stream().filter(rect -> rect.isOverlapping(smallRect)).noneMatch(rect -> rect.getInsider(smallRect) == null)), bigRects.stream()).collect(Collectors.toList());
}
private void mergeRects(Img img, double overlapThreshold) {
List<GSRect> rects = mergeRectsList(img);
Collections.reverse(rects);
for (GSRect rect : rects) {
Field match = findMatch(rect, overlapThreshold, img.width(), img.height());
if (match != null)
updateNode(rect, match, img.width(), img.height());
else if (!rect.isNearEdge(img.width(), img.height(), 10)) {
Field parent = findPotentialParent(rect);
if (parent == null) {
List<Field> children = findPotentialChildren(rect);
if (children.isEmpty())
createNode(rect, null);
else
createNodeWithChildren(rect, children);
} else
createNode(rect, parent);
} else
logger.trace("Rect {} was too close to the frame's edges", rect);
}
}
private List<Field> findPotentialChildren(GSRect rect) {
return getRoots().stream().filter(f -> f.getRect().isInside(rect) && f.getRect().inclusiveArea(rect)<0.3).collect(Collectors.toList());
}
private Field findPotentialParent(GSRect rect) {
for (Field root : getRoots()) {
Field parent = root.findPotentialParent(rect);
if (parent != null)
return parent;
}
return null;
}
public void createNode(GSRect rect, Field parent) {
if (checkOverlapConstraint(rect)) {
//logger.info("Creating a new node for {}", rect);
Field f = new Field(rect);
if (parent != null)
f.updateParent(parent);
fields.add(f);
}
// else
// logger.info("Unable to create node: " + rect);
}
public void createNodeWithChildren(GSRect rect, List<Field> children) {
if (checkOverlapConstraint(rect)) {
//logger.info("Creating a new node for {}", rect);
Field f = new Field(rect);
if (children != null)
for (Field child : children)
child.updateParent(f);
fields.add(f);
}
// else
// logger.info("Unable to create node: " + rect);
}
public void updateNode(GSRect rect, Field field, int width, int height) {
//logger.info("Updating node {} with {}", field.getRect(), rect);
// field.updateRect(rect, width, height);
field.updateOcrRect(rect);
field.adjustLockLevel(1.0);
field.resetParentsDeadCounter();
field.resetChildrenDeadCounter();
}
private boolean checkOverlapConstraint(GSRect rect) {
for (Field field : fields)
if (rect.isOverlappingStrict(field.getRect()))
if (rect.getInsider(field.getRect()) == null){
field.adjustLockLevel(-0.8);
return false;
}
return true;
}
public void removeNode(Field field) {
//logger.info("Removing node: {}", field.getRect());
fields.remove(field);
}
private void removeDeadTrees() {
getRoots().stream().filter(field -> isDeadTree(field, MAX_DELETE_UNMERGED)).flatMap(field -> listTree(field).stream()).forEach(this::removeNode);
}
private boolean isDeadTree(Field root, int maxDeadCount) {
if (!root.hasChildren())
return root.isDead(maxDeadCount);
for (Field child : root.getChildren())
if (!isDeadTree(child, maxDeadCount))
return false;
return true;
}
private List<Field> listTree(Field root) {
List<Field> res = new ArrayList<>();
res.add(root);
for (Field child : root.getChildren())
res.addAll(listTree(child));
return res;
}
private Field findMatch(GSRect rect, double areaOverlap, int width, int height) {
GSRect frameRect = new GSRect(0, 0, width, height);
List<Field> matches = fields.stream().filter(f -> rect.inclusiveArea(f.getRect().getIntersection(frameRect)) > areaOverlap).collect(Collectors.toList());
if (matches.isEmpty())
return null;
if (matches.size() > 1)
logger.warn(matches.size() + " matches were detected.");
return matches.get(0);
}
public void restabilizeFields(Mat homography) {
fields.forEach(field -> field.updateRect(findNewRect(field.getRect(), homography)));
}
private GSRect findNewRect(GSRect rect, Mat homography) {
List<Point> originals = RectToolsMapper.gsPointToPoint(Arrays.asList(rect.tl(), rect.br()));
List<GSPoint> points = RectToolsMapper.pointToGSPoint(restabilize(originals, homography));
return new GSRect(points.get(0), points.get(1));
}
private List<Point> restabilize(List<Point> originals, Mat homography) {
Mat original = Converters.vector_Point2d_to_Mat(originals);
Mat results = new Mat();
Core.perspectiveTransform(original, results, homography);
List<Point> res = new ArrayList<>();
Converters.Mat_to_vector_Point2d(results, res);
return res;
}
@Override
public void performOcr(Img rootImg) {
if (size() <= 0)
return;
long TS = System.currentTimeMillis();
while (System.currentTimeMillis() - TS <= OCR_TIMEOUT) {
runParallelOcr(rootImg);
// runSequentialOcr(rootImg);
}
}
private void runSequentialOcr(Img rootImg) {
int idx = ThreadLocalRandom.current().nextInt(size());
Field f = fields.get(idx);
//if (f.needOcr())
f.ocr(rootImg);
}
private void runParallelOcr(Img rootImg) {
ParallelTasks tasks = new ParallelTasks();
int limit = tasks.getCounter() * 2;
for (Set<Integer> indexes = new HashSet<>(); indexes.size() < limit && indexes.size() < size();) {
int idx = ThreadLocalRandom.current().nextInt(size());
if (indexes.add(idx)) {
Field f = fields.get(idx);
//if (f.needOcr())
tasks.add(() -> f.ocr(rootImg));
}
}
try {
tasks.run();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public Map<Field, Field> getLabelMatchesWithOldFields(Img rootImg, Fields oldFields) {
if (size() <= 0)
return null;
long TS = System.currentTimeMillis();
Map<Field, String> ocrs = new ConcurrentHashMap<Field, String>();
while (System.currentTimeMillis() - TS <= OCR_TIMEOUT) {
runParallelOcr(rootImg, ocrs);
}
return findRecoveringMatches(oldFields, ocrs);
}
private void runParallelOcr(Img rootImg, Map<Field, String> ocrs) {
ParallelTasks tasks = new ParallelTasks();
int limit = tasks.getCounter() * 2;
for (Set<Integer> indexes = new HashSet<>(); indexes.size() < limit && indexes.size() < size();) {
int idx = ThreadLocalRandom.current().nextInt(size());
if (indexes.add(idx)) {
Field f = fields.get(idx);
tasks.add(() -> {
String s = f.ocr(rootImg);
if(s!=null)
ocrs.put(f, s);
});
}
}
try {
tasks.run();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void tryRecoveryfromOldFields(Map<Field, Field> labelMatches, Fields oldFields) {
Mat homography = findRecoveringHomography(labelMatches);
if(homography!=null ){
oldFields.restabilizeFields(homography);
transferHistoryFrom(oldFields);
}
}
private Map<Field, Field> findRecoveringMatches(Fields oldFields, Map<Field, String> ocrs){
Map<Field, Field> matches = new HashMap<Field,Field>();
for(Map.Entry<Field, String> entry : ocrs.entrySet()){
if(entry.getValue().trim().length()<4)
continue;
for(Field oldField : oldFields){
if(entry.getValue().equals(oldField.getConsolidated())){
if(matches.containsKey(entry.getKey()))
matches.remove(entry.getKey());
else
matches.put(entry.getKey(), oldField);
}
}
}
System.out.println("returning "+matches);
return matches;
}
private Mat findRecoveringHomography(Map<Field, Field> matches) {
List<Point> newPointList = new ArrayList<>();
List<Point> oldPointList = new ArrayList<>();
for(Map.Entry<Field, Field> entry : matches.entrySet()){
newPointList.addAll(getSquarePoints(entry.getKey().getRect().decomposeClockwise()));
oldPointList.addAll(getSquarePoints(entry.getValue().getRect().decomposeClockwise()));
}
Mat mask = new Mat();
Mat homography = Calib3d.findHomography(new MatOfPoint2f(oldPointList.toArray(new Point[oldPointList.size()])), new MatOfPoint2f(newPointList.toArray(new Point[newPointList.size()])), 8, 2, mask, 2000, 0.995);
for(int i=mask.rows()-1; i>=0 ;i--){
if(mask.get(i, 0)[0]==0){
newPointList.remove(i);
oldPointList.remove(i);
}
}
return evaluateHomographyError(newPointList, oldPointList, homography)<1?homography:null;
}
private double evaluateHomographyError(List<Point> newPointList, List<Point> oldPointList, Mat homography) {
double error = 0.0;
List<Point> restabilizedPoints = restabilize(oldPointList, homography);
for(int i = 0; i < restabilizedPoints.size(); i++){
double deltaX = newPointList.get(i).x - restabilizedPoints.get(i).x;
double deltaY = newPointList.get(i).y - restabilizedPoints.get(i).y;
error+=deltaX*deltaX + deltaY*deltaY;
}
System.out.println("error found: "+ Math.sqrt(error)/restabilizedPoints.size());
return Math.sqrt(error)/restabilizedPoints.size();
}
private List<Point> getSquarePoints(GSPoint[] GSpoints) {
List<Point> points = new ArrayList<>();
for(int i = 0; i < GSpoints.length; i++)
points.add(new Point(GSpoints[i].getX(), GSpoints[i].getY()));
return points;
}
public void transferHistoryFrom(Fields oldFields){
for(Field newField : fields){
Field match = newField.findOldMatch(oldFields);
if(match!=null){
newField.getLabels().putAll(match.getLabels());
newField.setConsolidated(match.getConsolidated());
}
}
}
public void consolidateHierarchyLabels() {
for(Field field : getRoots()){
field.consolidateLabelWithChildren();
}
}
}