-
Notifications
You must be signed in to change notification settings - Fork 5
/
ReferenceManager.java
323 lines (277 loc) · 10.4 KB
/
ReferenceManager.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
package org.genericsystem.cv.application;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Random;
import java.util.TreeMap;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Size;
import org.opencv.utils.Converters;
public class ReferenceManager {
private static final Mat IDENTITY_MAT = Mat.eye(new Size(3, 3), CvType.CV_64F);
private TreeMap<ImgDescriptor, Mat> toReferenceGraphy = new TreeMap<>(new Comparator<ImgDescriptor>() {
@Override
public int compare(ImgDescriptor d1, ImgDescriptor d2) {
return new Long(d1.getTimeStamp()).compareTo(new Long(d2.getTimeStamp()));
}
});
private ImgDescriptor reference;
// private List<Rect> referenceRects = new ArrayList<>();
private Fields fields = new Fields();
private Size frameSize;
public ReferenceManager(Size frameSize) {
this.frameSize = frameSize;
}
public void submit(ImgDescriptor newImgDescriptor, List<Rect> detectedrects) {
if (reference == null) {
toReferenceGraphy.put(newImgDescriptor, IDENTITY_MAT);
reference = newImgDescriptor;
return;
}
int bestMatchingPointsCount = 0;
ImgDescriptor bestImgDescriptor = null;
Reconciliation bestReconciliation = null;
ImgDescriptor lastStored = toReferenceGraphy.lastKey();
Reconciliation reconciliationWithlast = newImgDescriptor.computeReconciliation(lastStored);
if (reconciliationWithlast != null) {
bestReconciliation = reconciliationWithlast;
bestImgDescriptor = lastStored;
}
else {
Reconciliation reconciliationWithRef = newImgDescriptor.computeReconciliation(reference);
if (reconciliationWithRef != null) {
bestReconciliation = reconciliationWithRef;
bestImgDescriptor = reference;
}
else {
int counter = 0;
while(counter<5){
ImgDescriptor randomImgDescriptor = getRandomDescriptor();
Reconciliation reconciliation = newImgDescriptor.computeReconciliation(randomImgDescriptor);
if (reconciliation != null) {
int matchingPointsCount = reconciliation.getPts().size();
if (matchingPointsCount >= bestMatchingPointsCount) {
bestMatchingPointsCount = matchingPointsCount;
bestReconciliation = reconciliation;
bestImgDescriptor = randomImgDescriptor;
}
}
counter++;
}
}
}
if (bestReconciliation == null) {
System.out.println("no reconciliation found");
if (toReferenceGraphy.size() <= 1) {
toReferenceGraphy.clear();
toReferenceGraphy.put(newImgDescriptor, IDENTITY_MAT);
reference = newImgDescriptor;
}
return;
}
Mat homographyToReference = new Mat();
Core.gemm(bestReconciliation.getHomography(), toReferenceGraphy.get(bestImgDescriptor), 1, new Mat(), 0, homographyToReference);
toReferenceGraphy.put(newImgDescriptor, homographyToReference);
consolidate(shift(detectedrects, homographyToReference));
updateReference();
cleanReferenceNeighbours();
}
private ImgDescriptor getRandomDescriptor(){
List<ImgDescriptor> list = new ArrayList<>(toReferenceGraphy.keySet());
return list.get(new Random().nextInt(list.size()));
}
private void cleanReferenceNeighbours() {
if (toReferenceGraphy.size() > 20) {
double bestDistance = Double.MAX_VALUE;
ImgDescriptor closestDescriptor = null;
for (Entry<ImgDescriptor, Mat> entry : toReferenceGraphy.entrySet()) {
if (!entry.getKey().equals(reference)) {
double distance = distance(entry.getValue());
if (distance < bestDistance) {
bestDistance = distance;
closestDescriptor = entry.getKey();
}
}
}
toReferenceGraphy.remove(closestDescriptor);
}
}
private void updateReference() {
ImgDescriptor consensualDescriptor = findConsensualDescriptor();
if (reference != consensualDescriptor) {
System.out.println("Change reference");
Mat homoInv = toReferenceGraphy.get(consensualDescriptor).inv();
for (Entry<ImgDescriptor, Mat> entry : toReferenceGraphy.entrySet()) {
if (!entry.getKey().equals(consensualDescriptor)) {
Mat result = new Mat();
Core.gemm(entry.getValue(), homoInv, 1, new Mat(), 0, result);
toReferenceGraphy.put(entry.getKey(), result);
} else
toReferenceGraphy.put(entry.getKey(), IDENTITY_MAT);
}
reference = consensualDescriptor;
fields.shift(homoInv);
}
}
private ImgDescriptor findConsensualDescriptor() {
double bestDistance = Double.MAX_VALUE;
ImgDescriptor bestDescriptor = null;
for (Entry<ImgDescriptor, Mat> entry : toReferenceGraphy.entrySet()) {
double distance = 0;
for (Entry<ImgDescriptor, Mat> entry2 : toReferenceGraphy.entrySet()) {
if (!entry.getKey().equals(entry2.getKey())) {
Mat betweenHomography = new Mat();
Core.gemm(entry.getValue(), entry2.getValue().inv(), 1, new Mat(), 0, betweenHomography);
distance += distance(betweenHomography);
}
}
if (distance < bestDistance) {
bestDistance = distance;
bestDescriptor = entry.getKey();
}
}
return bestDescriptor;
}
private static class Field {
private Rect rect;
private int level = 0;
Field(Rect rect) {
this.rect = rect;
}
public int getLevel() {
return level;
}
public void decrease() {
level--;
}
public void increase() {
level++;
}
public boolean isEnoughOverlapping(Rect shiftedRect, int pts) {
return (Math.abs(rect.tl().x - shiftedRect.tl().x) < pts) && (Math.abs(rect.tl().y - shiftedRect.tl().y) < pts) && (Math.abs(rect.br().x - shiftedRect.br().x) < pts) && (Math.abs(rect.br().y - shiftedRect.br().y) < pts);
}
public boolean isOverlapping(Rect other) {
return rect.tl().x <= other.br().x && other.tl().x <= rect.br().x && rect.tl().y <= other.br().y && other.tl().y <= rect.br().y;
}
public void dump(Rect shiftedRect, double dumpingSize) {
this.rect = new Rect(new Point(Math.round(rect.tl().x * ((dumpingSize - 1) / dumpingSize) + shiftedRect.tl().x / dumpingSize), Math.round(rect.tl().y * ((dumpingSize - 1) / dumpingSize) + shiftedRect.tl().y / dumpingSize)),
new Point(Math.round(rect.br().x * (dumpingSize - 1) / dumpingSize + shiftedRect.br().x / dumpingSize), Math.round(rect.br().y * (dumpingSize - 1) / dumpingSize + shiftedRect.br().y / dumpingSize)));
}
public Rect getRect() {
return rect;
}
public void shift(Mat homography) {
Mat original = Converters.vector_Point2d_to_Mat(Arrays.asList(rect.tl(), rect.br()));
Mat results = new Mat();
Core.perspectiveTransform(original, results, homography);
List<Point> res = new ArrayList<>();
Converters.Mat_to_vector_Point2d(results, res);
rect = new Rect(res.get(0), res.get(1));
}
public boolean contains(Rect shiftedRect) {
return (rect.tl().x <= shiftedRect.tl().x && rect.tl().y <= shiftedRect.tl().y && rect.br().x >= shiftedRect.br().x && rect.br().y >= shiftedRect.br().y);
}
public boolean isInner(Rect shiftedRect) {
return (rect.tl().x >= shiftedRect.tl().x && rect.tl().y >= shiftedRect.tl().y && rect.br().x <= shiftedRect.br().x && rect.br().y <= shiftedRect.br().y);
}
}
private static class Fields {
private List<Field> fieldsList = new ArrayList<>();
public void clean(Predicate<Field> predicate) {
fieldsList.removeIf(predicate);
}
public void shift(Mat homoInv) {
fieldsList.forEach(field -> field.shift(homoInv));
}
public List<Field> findOverlapingFields(Rect shiftedRect) {
return fieldsList.stream().filter(field -> field.isOverlapping(shiftedRect)).collect(Collectors.toList());
}
public void add(Field field) {
fieldsList.add(field);
}
public List<Rect> getPositiveLevelRects() {
return fieldsList.stream().filter(field -> field.getLevel() >= 0).map(field -> field.getRect()).collect(Collectors.toList());
}
public void decreaseAll() {
fieldsList.forEach(field -> field.decrease());
}
}
private void consolidate(List<Rect> shiftedRects) {
for (Rect shiftedRect : shiftedRects) {
List<Field> targetFields = fields.findOverlapingFields(shiftedRect);
boolean toAdd = true;
for (Field targetField : targetFields) {
if (targetField.isEnoughOverlapping(shiftedRect, 5)) {
targetField.dump(shiftedRect, 3);
targetField.increase();
targetField.increase();
toAdd = false;
}
}
if (toAdd) {
Field newField = new Field(shiftedRect);
newField.increase();
newField.increase();
fields.add(newField);
}
}
fields.decreaseAll();
fields.clean(targetField -> targetField.getLevel() < -3);
}
public List<Rect> getReferenceRects() {
return fields.getPositiveLevelRects();
}
private List<Rect> shift(List<Rect> detectedRects, Mat homography) {
List<Point> pts = new ArrayList<>(2 * detectedRects.size());
detectedRects.forEach(rect -> {
pts.add(rect.tl());
pts.add(rect.br());
});
List<Point> transform = transform(pts, homography);
List<Rect> result = new ArrayList<>(detectedRects.size());
for (int i = 0; i < transform.size(); i += 2)
result.add(new Rect(transform.get(i), transform.get(i + 1)));
return result;
}
private List<Point> transform(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;
}
public Reconciliation computeHomography(ImgDescriptor newDescriptor) {
return newDescriptor.computeReconciliation(getReference());
}
private double distance(Mat betweenHomography) {
List<Point> originalPoints = Arrays.asList(new Point[] { new Point(0, 0), new Point(frameSize.width, 0), new Point(frameSize.width, frameSize.height), new Point(0, frameSize.height) });
List<Point> points = transform(originalPoints, betweenHomography);
return distance(points, originalPoints);
}
private double distance(List<Point> newPointList, List<Point> oldPointList) {
double error = 0.0;
for (int i = 0; i < oldPointList.size(); i++) {
double deltaX = newPointList.get(i).x - oldPointList.get(i).x;
double deltaY = newPointList.get(i).y - oldPointList.get(i).y;
error += deltaX * deltaX + deltaY * deltaY;
}
return Math.sqrt(error) / oldPointList.size();
}
public ImgDescriptor getReference() {
return reference;
}
public void clear() {
reference = null;
toReferenceGraphy.clear();
fields.clean(field -> true);
}
}