-
Notifications
You must be signed in to change notification settings - Fork 5
/
RobustTextDetector.java
364 lines (318 loc) · 12.6 KB
/
RobustTextDetector.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
package org.genericsystem.cv.application;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.genericsystem.cv.AbstractApp;
import org.genericsystem.cv.Img;
import org.genericsystem.cv.utils.NativeLibraryLoader;
import org.opencv.core.Core;
import org.opencv.core.Core.MinMaxLocResult;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfDouble;
import org.opencv.core.MatOfPoint;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.features2d.MSER;
import org.opencv.imgproc.Imgproc;
import org.opencv.utils.Converters;
import javafx.application.Platform;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
public class RobustTextDetector extends AbstractApp {
public static void main(String[] args) {
launch(args);
}
static {
NativeLibraryLoader.load();
}
private final double f = 6.053 / 0.009;
private final GSCapture gsCapture = new GSVideoCapture(0, f, GSVideoCapture.HD, GSVideoCapture.VGA);
private SuperFrameImg superFrame = gsCapture.read();
private ScheduledExecutorService timer = new BoundedScheduledThreadPoolExecutor();
private Config config = new Config();
private final ImageView[][] imageViews = new ImageView[][] { new ImageView[3], new ImageView[3], new ImageView[3], new ImageView[3] };
private void startTimer() {
timer.scheduleAtFixedRate(() -> {
try {
Image[] images = doWork();
if (images != null)
Platform.runLater(() -> {
Iterator<Image> it = Arrays.asList(images).iterator();
for (int row = 0; row < imageViews.length; row++)
for (int col = 0; col < imageViews[row].length; col++)
if (it.hasNext())
imageViews[row][col].setImage(it.next());
});
} catch (Throwable e) {
e.printStackTrace();
}
}, 30, 30, TimeUnit.MILLISECONDS);
}
@Override
protected void fillGrid(GridPane mainGrid) {
double displaySizeReduction = 1.5;
for (int col = 0; col < imageViews.length; col++)
for (int row = 0; row < imageViews[col].length; row++) {
ImageView imageView = new ImageView();
imageViews[col][row] = imageView;
mainGrid.add(imageViews[col][row], col, row);
imageView.setFitWidth(superFrame.width() / displaySizeReduction);
imageView.setFitHeight(superFrame.height() / displaySizeReduction);
}
startTimer();
}
private Image[] doWork() {
System.out.println("do work");
if (!config.stabilizedMode)
superFrame = gsCapture.read();
Image[] images = new Image[8];
MSER detector = MSER.create(3, 10, 2000, 0.25, 0.1, 100, 1.01, 0.03, 5);
Img gray = superFrame.getFrame().bgr2Gray();
// detector.detect(gray.getSrc(), keypoint);
ArrayList<MatOfPoint> regions = new ArrayList<>();
MatOfRect mor = new MatOfRect();
detector.detectRegions(gray.getSrc(), regions, mor);
// System.out.println(mor);
Mat mserMask = new Mat(gray.size(), CvType.CV_8UC1, new Scalar(0));
for (MatOfPoint mop : regions) {
for (Point p : mop.toList())
mserMask.put((int) p.y, (int) p.x, 255);
}
// for (Rect rect : mor.toList()) {
// Imgproc.rectangle(mserMask, rect.tl(), rect.br(), new Scalar(255), -1);
// // mserMask.put((int) kpoint.pt.x, (int) kpoint.pt.y, 255);
// }
Mat edges = new Mat();
Imgproc.Canny(gray.getSrc(), edges, 20, 100);
Mat edge_mser_intersection = new Mat();
Core.bitwise_and(edges, mserMask, edge_mser_intersection);
Mat gradientGrown = growEdges(gray.getSrc(), edge_mser_intersection);
Mat edgeEnhancedMser = new Mat();
Mat notGradientGrown = new Mat();
Core.bitwise_not(gradientGrown, notGradientGrown);
Core.bitwise_and(notGradientGrown, mserMask, edgeEnhancedMser);
Mat labels = new Mat();
Mat stats = new Mat();
Mat centroid = new Mat();
int labelsIds = Imgproc.connectedComponentsWithStats(edgeEnhancedMser, labels, stats, centroid, 4, CvType.CV_32S);
Mat result2 = new Mat(labels.size(), CvType.CV_8UC1, new Scalar(0));
for (int labelId = 0; labelId < labelsIds; labelId++) {
double area = stats.get(labelId, Imgproc.CC_STAT_AREA)[0];
if (area < 3 || area > 600)
continue;
Mat labelMask = new Mat();
Core.inRange(labels, new Scalar(labelId), new Scalar(labelId), labelMask);
Core.bitwise_or(result2, labelMask, result2);
}
Imgproc.distanceTransform(result2, result2, Imgproc.DIST_L2, 3);
result2.convertTo(result2, CvType.CV_32SC1);
// Core.multiply(result2, new Scalar(50), result2);
Mat strokeWidth = computeStrokeWidth(result2);
// Core.multiply(stokeWidth, new Scalar(50), stokeWidth);
Mat filtered_stroke_width = new Mat(strokeWidth.size(), CvType.CV_8UC1, new Scalar(0));
Mat strokeWithCV8U = new Mat();
strokeWidth.convertTo(strokeWithCV8U, CvType.CV_8UC1);
labelsIds = Imgproc.connectedComponentsWithStats(strokeWithCV8U, labels, stats, centroid, 4, CvType.CV_32S);
for (int labelId = 0; labelId < labelsIds; labelId++) {
Mat labelMask = new Mat();
Core.inRange(labels, new Scalar(labelId), new Scalar(labelId), labelMask);
Mat temp = new Mat(strokeWithCV8U.size(), strokeWithCV8U.type(), new Scalar(0));
strokeWithCV8U.copyTo(temp, labelMask);
int area = Core.countNonZero(temp);
MatOfDouble meanD = new MatOfDouble();
MatOfDouble stdDev = new MatOfDouble();
Core.meanStdDev(strokeWithCV8U, meanD, stdDev, labelMask);
if (area != 0) {
/* Filter out those which are out of the prespecified ratio */
if ((stdDev.get(0, 0)[0] / meanD.get(0, 0)[0]) > 0.5)
continue;
/* Collect the filtered stroke width */
Core.bitwise_or(filtered_stroke_width, labelMask, filtered_stroke_width);
}
}
Mat bounding_region = new Mat();
Imgproc.morphologyEx(filtered_stroke_width, bounding_region, Imgproc.MORPH_CLOSE, Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(25, 25)));
Imgproc.morphologyEx(bounding_region, bounding_region, Imgproc.MORPH_OPEN, Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(7, 7)));
Mat result3 = new Mat();
superFrame.getFrame().getSrc().copyTo(result3, bounding_region);
images[0] = new Img(result3, false).toJfxImage();
return images;
}
private static int booleansToInt(boolean[] arr) {
int n = 0;
for (boolean b : arr)
n = (n << 1) | (b ? 1 : 0);
return n;
}
private static int getNeighborsLessThan(Mat mat, int y, int x) {
boolean[] neighbors = new boolean[8];
neighbors[0] = mat.get(y, x - 1)[0] == 0 ? false : mat.get(y, x - 1)[0] < mat.get(y, x)[0];
neighbors[1] = mat.get(y - 1, x - 1)[0] == 0 ? false : mat.get(y - 1, x - 1)[0] < mat.get(y, x)[0];
neighbors[2] = mat.get(y - 1, x)[0] == 0 ? false : mat.get(y - 1, x)[0] < mat.get(y, x)[0];
neighbors[3] = mat.get(y - 1, x + 1)[0] == 0 ? false : mat.get(y - 1, x + 1)[0] < mat.get(y, x)[0];
neighbors[4] = mat.get(y, x + 1)[0] == 0 ? false : mat.get(y, x + 1)[0] < mat.get(y, x)[0];
neighbors[5] = mat.get(y + 1, x + 1)[0] == 0 ? false : mat.get(y + 1, x + 1)[0] < mat.get(y, x)[0];
neighbors[6] = mat.get(y + 1, x)[0] == 0 ? false : mat.get(y + 1, x)[0] < mat.get(y, x)[0];
neighbors[7] = mat.get(y + 1, x - 1)[0] == 0 ? false : mat.get(y + 1, x - 1)[0] < mat.get(y, x)[0];
return booleansToInt(neighbors);
}
private static Mat computeStrokeWidth(Mat dist) {
/* Pad the distance transformed matrix to avoid boundary checking */
Mat padded = new Mat(dist.rows() + 1, dist.cols() + 1, dist.type(), new Scalar(0));
dist.copyTo(new Mat(padded, new Rect(1, 1, dist.cols(), dist.rows())));
Mat lookup = new Mat(padded.size(), CvType.CV_8UC1, new Scalar(0));
for (int y = 1; y < padded.rows() - 1; y++) {
for (int x = 1; x < padded.cols() - 1; x++) {
/* Extract all the neighbors whose value < curr_ptr[x], encoded in 8-bit uchar */
if (padded.get(y, x)[0] != 0)
lookup.put(y, x, (double) getNeighborsLessThan(padded, y, x));
}
}
/* Get max stroke from the distance transformed */
MinMaxLocResult minMaxLocResult = Core.minMaxLoc(padded);
int maxStroke = (int) Math.round(minMaxLocResult.maxVal);
for (double stroke = maxStroke; stroke > 0; stroke--) {
Mat stroke_indices_mat = new Mat();
Mat mask = new Mat();
Core.inRange(padded, new Scalar(stroke - 0.1), new Scalar(stroke + 0.1), mask);
Mat masked = new Mat();
padded.copyTo(masked, mask);
masked.convertTo(masked, CvType.CV_8UC1);
Core.findNonZero(masked, stroke_indices_mat);
List<Point> stroke_indices = new ArrayList<>();
if (stroke_indices_mat.cols() > 0)
Converters.Mat_to_vector_Point(stroke_indices_mat, stroke_indices);
List<Point> neighbors = new ArrayList<>();
for (Point stroke_index : stroke_indices) {
List<Point> temp = convertToCoords((int) stroke_index.x, (int) stroke_index.y, (int) lookup.get((int) stroke_index.y, (int) stroke_index.x)[0]);
neighbors.addAll(temp);
}
while (!neighbors.isEmpty()) {
for (Point neighbor : neighbors)
padded.put((int) neighbor.y, (int) neighbor.x, stroke);
neighbors.clear();
List<Point> temp = new ArrayList<>(neighbors);
neighbors.clear();
/* Recursively gets neighbors of the current neighbors */
for (Point neighbor : temp) {
List<Point> temp2 = convertToCoords((int) neighbor.x, (int) neighbor.y, (int) lookup.get((int) neighbor.y, (int) neighbor.x)[0]);
neighbors.addAll(temp2);
}
}
}
return new Mat(padded, new Rect(1, 1, dist.cols(), dist.rows()));
}
private static List<Point> convertToCoords(int x, int y, int neighbors) {
List<Point> coords = new ArrayList<>();
if (((neighbors & ((int) Math.pow(2, 7))) != 0))
coords.add(new Point(x - 1, y));
if (((neighbors & ((int) Math.pow(2, 6))) != 0))
coords.add(new Point(x - 1, y - 1));
if (((neighbors & ((int) Math.pow(2, 5))) != 0))
coords.add(new Point(x, y - 1));
if (((neighbors & ((int) Math.pow(2, 4))) != 0))
coords.add(new Point(x + 1, y - 1));
if (((neighbors & ((int) Math.pow(2, 3))) != 0))
coords.add(new Point(x + 1, y));
if (((neighbors & ((int) Math.pow(2, 2))) != 0))
coords.add(new Point(x + 1, y + 1));
if (((neighbors & ((int) Math.pow(2, 1))) != 0))
coords.add(new Point(x, y + 1));
if (((neighbors & ((int) Math.pow(2, 0))) != 0))
coords.add(new Point(x - 1, y + 1));
return coords;
}
public static int toBin(double angle, int neighbors) {
float divisor = 180.0f / neighbors;
return (int) (((Math.floor(angle / divisor) - 1) / 2) + 1) % neighbors + 1;
}
public static Mat growEdges(Mat image, Mat edges) {
Mat grad_x = new Mat(), grad_y = new Mat();
Imgproc.Sobel(image, grad_x, CvType.CV_64FC1, 1, 0);
Imgproc.Sobel(image, grad_y, CvType.CV_64FC1, 0, 1);
Core.subtract(Mat.zeros(image.size(), CvType.CV_64FC1), grad_x, grad_x);
Mat grad_mag = new Mat(), grad_dir = new Mat();
Core.cartToPolar(grad_x, grad_y, grad_mag, grad_dir, true);
/*
* Convert the angle into predefined 3x3 neighbor locations | 2 | 3 | 4 | | 1 | 0 | 5 | | 8 | 7 | 6 |
*/
for (int y = 0; y < grad_dir.rows(); y++)
for (int x = 0; x < grad_dir.cols(); x++)
grad_dir.put(y, x, toBin((grad_dir.get(y, x))[0], 8));
grad_dir.convertTo(grad_dir, CvType.CV_8UC1);
/* Perform region growing based on the gradient direction */
Mat result = new Mat();
edges.copyTo(result);
for (int y = 1; y < edges.rows() - 1; y++) {
for (int x = 1; x < edges.cols() - 1; x++) {
/* Only consider the contours */
if (edges.get(y, x)[0] != 0) {
/* .. there should be a better way .... */
switch ((int) grad_dir.get(y, x)[0]) {
case 1:
result.put(y, x - 1, 255);
break;
case 2:
result.put(y - 1, x - 1, 255);
break;
case 3:
result.put(y - 1, x, 255);
break;
case 4:
result.put(y - 1, x + 1, 255);
break;
case 5:
result.put(y, x + 1, 255);
break;
case 6:
result.put(y + 1, x + 1, 255);
break;
case 7:
result.put(y + 1, x, 255);
break;
case 8:
result.put(y + 1, x - 1, 255);
break;
default:
System.out.println("Error : " + (int) grad_dir.get(y, x)[0]);
break;
}
}
}
}
return result;
}
@Override
protected void onS() {
config.stabilizedMode = !config.stabilizedMode;
}
@Override
protected void onSpace() {
if (config.isOn)
timer.shutdown();
else {
timer = new BoundedScheduledThreadPoolExecutor();
startTimer();
}
config.isOn = !config.isOn;
}
@Override
protected void onT() {
config.textsEnabledMode = !config.textsEnabledMode;
}
@Override
public void stop() throws Exception {
super.stop();
timer.shutdown();
timer.awaitTermination(5000, TimeUnit.MILLISECONDS);
gsCapture.release();
}
}