-
Notifications
You must be signed in to change notification settings - Fork 5
/
RadonTransform.java
310 lines (272 loc) · 12.4 KB
/
RadonTransform.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
package org.genericsystem.cv.application;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import org.apache.commons.math3.analysis.interpolation.LinearInterpolator;
import org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction;
import org.genericsystem.cv.Img;
import org.genericsystem.cv.lm.LevenbergImpl;
import org.genericsystem.cv.utils.NativeLibraryLoader;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Range;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RadonTransform {
static {
NativeLibraryLoader.load();
}
private static final Logger logger = LoggerFactory.getLogger(RadonTransform.class);
public static Mat transform(Mat src, int minMaxAngle) {
Mat dst = Mat.zeros(src.rows(), src.rows(), CvType.CV_64FC1);
int center = dst.rows() / 2;
src.convertTo(new Mat(dst, new Rect(new Point(center - src.cols() / 2, 0), new Point(center + src.cols() / 2, src.rows()))), CvType.CV_64FC1);
Mat radon = Mat.zeros(dst.rows(), 2 * minMaxAngle, CvType.CV_64FC1);
for (int t = -minMaxAngle; t < minMaxAngle; t++) {
Mat rotated = new Mat();
Mat rotation = Imgproc.getRotationMatrix2D(new Point(center, center), t, 1);
Imgproc.warpAffine(dst, rotated, rotation, new Size(dst.cols(), dst.rows()), Imgproc.INTER_NEAREST);
Core.reduce(rotated, radon.col(t + minMaxAngle), 1, Core.REDUCE_SUM);
rotated.release();
rotation.release();
}
Core.normalize(radon, radon, 0, 255, Core.NORM_MINMAX);
return radon;
}
public static Mat transformV(Mat src, Size boxFilterSize, double thresHold, int minMaxAngle) {
Mat dst = Mat.zeros(src.cols(), src.cols(), CvType.CV_64FC1);
int center = dst.cols() / 2;
src.convertTo(new Mat(dst, new Rect(new Point(0, center - src.rows() / 2), new Point(src.cols(), center + src.rows() / 2))), CvType.CV_64FC1);
Mat radon = Mat.zeros(2 * minMaxAngle, dst.cols(), CvType.CV_64FC1);
for (int t = -minMaxAngle; t < minMaxAngle; t++) {
Mat rotated = new Mat();
Mat rotation = Imgproc.getRotationMatrix2D(new Point(center, center), t, 1);
Imgproc.warpAffine(dst, rotated, rotation, new Size(dst.cols(), dst.rows()), Imgproc.INTER_NEAREST);
Core.reduce(rotated, radon.row(t + minMaxAngle), 0, Core.REDUCE_SUM);
}
Core.normalize(radon, radon, 0, 255, Core.NORM_MINMAX);
return radon;
}
public static Mat projectionMap(Mat radon) {
Mat projectionMap = Mat.zeros(radon.rows(), radon.cols(), CvType.CV_64FC1);
for (int k = 0; k < projectionMap.rows(); k++) {
for (int tetha = 0; tetha < projectionMap.cols(); tetha++) {
int p = (int) ((k - projectionMap.rows() / 2) * Math.sin(((double) tetha + 45) / 180 * Math.PI) + radon.rows() / 2);
projectionMap.put(k, tetha, radon.get(p, tetha)[0]);
}
}
return projectionMap;
}
public static Mat projectionMapV(Mat radon) {
Mat projectionMap = Mat.zeros(radon.rows(), radon.cols(), CvType.CV_64FC1);
for (int k = 0; k < projectionMap.cols(); k++) {
for (int tetha = 0; tetha < projectionMap.rows(); tetha++) {
int p = (int) ((k - projectionMap.cols() / 2) * Math.sin(((double) tetha - 35 + 90) / 180 * Math.PI) + radon.cols() / 2);
projectionMap.put(tetha, k, radon.get(tetha, p)[0]);
}
}
return projectionMap;
}
public static void main(String[] args) {
Mat projectionMat = Mat.eye(new Size(3, 3), CvType.CV_64FC1);
System.out.println(Arrays.toString(bestTraject(projectionMat, 0, 2)));
}
public static int[] bestTraject(Mat projectionMap, double anglePenality, double pow) {
double[][] score = new double[projectionMap.rows()][projectionMap.cols()];
int[][] thetaPrev = new int[projectionMap.rows()][projectionMap.cols()];
for (int theta = 0; theta < projectionMap.cols(); theta++)
score[0][theta] = Math.pow(projectionMap.get(0, theta)[0], pow);
for (int k = 1; k < projectionMap.rows(); k++) {
for (int theta = 0; theta < projectionMap.cols(); theta++) {
double magnitude = projectionMap.get(k, theta)[0];
double scoreFromPrevTheta = theta != 0 ? score[k - 1][theta - 1] : Double.NEGATIVE_INFINITY;
double scoreFromSameTheta = score[k - 1][theta];
double scoreFromNextTheta = theta < projectionMap.cols() - 1 ? score[k - 1][theta + 1] : Double.NEGATIVE_INFINITY;
double bestScore4Pos = -1;
if (scoreFromSameTheta >= (scoreFromPrevTheta + anglePenality) && scoreFromSameTheta >= (scoreFromNextTheta + anglePenality)) {
bestScore4Pos = scoreFromSameTheta;
thetaPrev[k][theta] = theta;
} else if ((scoreFromPrevTheta + anglePenality) >= scoreFromSameTheta && ((scoreFromPrevTheta + anglePenality) >= (scoreFromNextTheta + anglePenality))) {
bestScore4Pos = scoreFromPrevTheta + anglePenality;
thetaPrev[k][theta] = theta - 1;
} else {
bestScore4Pos = scoreFromNextTheta + anglePenality;
thetaPrev[k][theta] = theta + 1;
}
score[k][theta] = Math.pow(magnitude, pow) + bestScore4Pos;
}
}
// System.out.println(Arrays.toString(score[projectionMap.rows() - 1]));
// System.out.println(Arrays.deepToString(thetaPrev));
double maxScore = Double.NEGATIVE_INFINITY;
int prevTheta = -1;
int[] thetas = new int[projectionMap.rows()];
for (int theta = 0; theta < projectionMap.cols(); theta++) {
double lastScore = score[projectionMap.rows() - 1][theta];
// System.out.println(lastScore);
if (lastScore > maxScore) {
maxScore = lastScore;
prevTheta = theta;
}
}
assert prevTheta != -1;
// System.out.println(maxScore + " for theta : " + prevTheta);
for (int k = projectionMap.rows() - 1; k >= 0; k--) {
thetas[k] = prevTheta;
// System.out.println(prevTheta);
prevTheta = thetaPrev[k][prevTheta];
}
return thetas;
}
public static int[] bestTrajectV(Mat projectionMap, double anglePenality) {
double[][] score = new double[projectionMap.rows()][projectionMap.cols()];
int[][] thetaPrev = new int[projectionMap.rows()][projectionMap.cols()];
for (int theta = 0; theta < projectionMap.rows(); theta++)
score[theta][0] = Math.pow(projectionMap.get(theta, 0)[0], 3);
for (int k = 1; k < projectionMap.cols(); k++) {
for (int theta = 0; theta < projectionMap.rows(); theta++) {
double magnitude = projectionMap.get(theta, k)[0];
double scoreFromPrevTheta = theta != 0 ? score[theta - 1][k - 1] : Double.NEGATIVE_INFINITY;
double scoreFromSameTheta = score[theta][k - 1];
double scoreFromNextTheta = theta < projectionMap.rows() - 1 ? score[theta + 1][k - 1] : Double.NEGATIVE_INFINITY;
double bestScore4Pos = -1;
if (scoreFromSameTheta >= (scoreFromPrevTheta + anglePenality) && scoreFromSameTheta >= (scoreFromNextTheta + anglePenality)) {
bestScore4Pos = scoreFromSameTheta;
thetaPrev[theta][k] = theta;
} else if ((scoreFromPrevTheta + anglePenality) >= scoreFromSameTheta && ((scoreFromPrevTheta + anglePenality) >= (scoreFromNextTheta + anglePenality))) {
bestScore4Pos = scoreFromPrevTheta + anglePenality;
thetaPrev[theta][k] = theta - 1;
} else {
bestScore4Pos = scoreFromNextTheta + anglePenality;
thetaPrev[theta][k] = theta + 1;
}
score[theta][k] = Math.pow(magnitude, 3) + bestScore4Pos;
}
}
// System.out.println(Arrays.toString(score[projectionMap.rows() - 1]));
// System.out.println(Arrays.deepToString(thetaPrev));
double maxScore = Double.NEGATIVE_INFINITY;
int prevTheta = -1;
int[] thetas = new int[projectionMap.cols()];
for (int theta = 0; theta < projectionMap.rows(); theta++) {
double lastScore = score[theta][projectionMap.cols() - 1];
// System.out.println(lastScore);
if (lastScore > maxScore) {
maxScore = lastScore;
prevTheta = theta;
}
}
assert prevTheta != -1;
// System.out.println(maxScore + " for theta : " + prevTheta);
for (int k = projectionMap.cols() - 1; k >= 0; k--) {
thetas[k] = prevTheta;
// System.out.println(prevTheta);
prevTheta = thetaPrev[prevTheta][k];
}
return thetas;
}
public static List<Mat> extractStrips(Mat src, int stripWidth) {
List<Mat> strips = new ArrayList<>();
for (int col = 0; col + stripWidth <= src.cols(); col += stripWidth / 2)
strips.add(extractStrip(src, col, stripWidth));
return strips;
}
public static Mat extractStrip(Mat src, int startX, int width) {
return new Mat(src, new Range(0, src.rows()), new Range(startX, startX + width));
}
public static Mat[] estimateBaselines(Mat image, double anglePenalty, int minMaxAngle, double magnitudePow) {
Mat result = image.clone();
Mat curve = image.clone();
Mat preprocessed = new Img(result, false).gaussianBlur(new Size(5, 5)).adaptativeGaussianInvThreshold(5, 3).canny(60, 180).getSrc();
// Number of overlapping vertical strips.
int n = 20;
// Overlap ratio between two consecutive strips.
float r = .5f;
// w = width of a vertical strip.
// Image width = [n(1 - r) + r] w
double w = (image.width() / (n * (1 - r) + r));
double step = (int) ((1 - r) * w);
int[][] angles = new int[n][];
// 0, center of each vertical strip, image.width() - 1
double[] xs = new double[n + 2];
BiFunction<Double, double[], Double> f = (y, params) -> params[0] + params[1] * y + params[2] * y * y;
double[][] approxParams = new double[n][];
int x = 0;
for (int i = 0; i < n; i++) {
Mat radonTransform = transform(extractStrip(preprocessed, x, (int) w), minMaxAngle);
Mat projMap = projectionMap(radonTransform);
Imgproc.morphologyEx(projMap, projMap, Imgproc.MORPH_GRADIENT, Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(2, 4)));
angles[i] = bestTraject(projMap, anglePenalty, magnitudePow);
projMap.release();
radonTransform.release();
List<double[]> values = new ArrayList<>();
for (int k = 0; k < image.height(); k++)
values.add(new double[] { k, angles[i][k] });
approxParams[i] = LevenbergImpl.fromBiFunction(f, values, new double[] { 0, 0, 0 }).getParams();
xs[i + 1] = x + .5 * w;
x += step;
}
xs[n + 1] = image.width() - 1;
int lines = image.height() / 15;
double yStep = image.height() / lines;
logger.info("Image width {}, xs {}, step {}, w {}", image.width(), Arrays.toString(xs), step, w);
for (int i = 0; i < lines; i++) {
double[] ys = new double[n + 2];
// Start building line from the middle.
ys[n / 2] = i * yStep + .5 * yStep;
for (int j = n / 2; j <= n; j++) {
double theta = (f.apply(ys[j], approxParams[j - 1]) - minMaxAngle) / 180 * Math.PI;
// Line passing by the point G at the middle of the strip with ordinate currY (x_G, y_G),
// making an angle of theta with the horizontal:
// y = y_G + (x - x_G) tan theta
if (j == n)
ys[n + 1] = ys[n] + (image.width() - 1 - xs[j]) * Math.tan(theta);
else {
// Ordinate of the next point:
ys[j + 1] = ys[j] + step * Math.tan(theta);
}
}
for (int j = n / 2; j > 0; j--) {
double theta = (f.apply(ys[j], approxParams[j - 1]) - minMaxAngle) / 180 * Math.PI;
ys[j - 1] = ys[j] - step * Math.tan(theta);
}
// Draw line segments.
for (int j = 0; j < xs.length - 1; j++)
Imgproc.line(result, new Point(xs[j], ys[j]), new Point(xs[j + 1], ys[j + 1]), new Scalar(255, 0, 255));
// Approximate line with polynomial curve.
PolynomialSplineFunction psf = new LinearInterpolator().interpolate(xs, ys);
int currX = 0;
Point prevPoint = new Point(currX, psf.value(currX));
while (currX < image.width()) {
currX += 5;
Point newPoint = new Point(currX, 0);
if (psf.isValidPoint(currX)) {
newPoint.y = psf.value(currX);
if (psf.isValidPoint(prevPoint.x) && inImage(prevPoint, result) && inImage(newPoint, result))
Imgproc.line(curve, prevPoint, newPoint, new Scalar(255, 255, 0));
}
prevPoint = newPoint;
}
}
return new Mat[] { result, curve };
}
public static Function<Double, Double> approxTraject(int[] traj) {
List<double[]> values = new ArrayList<>();
for (int k = 0; k < traj.length; k++)
values.add(new double[] { k, traj[k] });
BiFunction<Double, double[], Double> f = (x, params) -> params[0] + params[1] * x + params[2] * x * x;
double[] params = LevenbergImpl.fromBiFunction(f, values, new double[] { 0, 0, 0 }).getParams();
return x -> f.apply(x, params);
}
private static boolean inImage(Point p, Mat img) {
return p.x >= 0 && p.y >= 0 && p.x < img.width() && p.y < img.height();
}
}