-
Notifications
You must be signed in to change notification settings - Fork 10
/
LaneFinder.kt
202 lines (169 loc) · 9.08 KB
/
LaneFinder.kt
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
package com.argos.android.opencv.lineDetection
import com.argos.android.opencv.lineDetection.windowFinding.*
import org.opencv.core.*
import org.opencv.imgproc.Imgproc
import kotlin.collections.ArrayList
class LaneFinderException(message: String) : Exception(message)
/*
ToDo: Im Camera-Modus gibt es einen Fehler, wenn man den Screen sperrt und dann wieder in die App geht
*/
class LaneFinder {
companion object {
const val WIDTH_IMAGE = 640
const val HEIGHT_IMAGE = 360
private const val HEIGHT_CROPPED_IMAGE = 185
private const val WIDTH_WARPED_IMAGE = 360
private const val HEIGHT_WARPED_IMAGE = 360
private const val WARPED_SRC_TOP = 300
private const val WARPED_SRC_BOTTOM = 50
private const val WARPED_DST_TOP = 85
private const val WARPED_DST_BOTTOM = 85
private const val WIDTH_RECT_THRESH = 181
private const val HEIGHT_RECT_THRESH = 101
private const val THRESH_OVER_AVG = 10
private const val THRESH_BINARY_IMAGE_THRESHOLD = 250
private const val THRESH_BINARY_IMAGE_CANNY = 10
}
private val mWindowFinder = WindowFinder(32, 32, 8, 64, 10, 64)
fun getLanesAndBinaryImage(image: Mat): Pair<Mat, Mat> {
checkImage(image)
var preProcessedImage = preProcessImageThreshold(image)
val imageLane = Mat(HEIGHT_IMAGE, WIDTH_IMAGE, CvType.CV_8UC3, Scalar(0.0, 0.0, 0.0, 1.0))
try {
findAndDrawLane(imageLane, preProcessedImage, THRESH_BINARY_IMAGE_THRESHOLD)
} catch (e: NoWindowFoundException) {
preProcessedImage = preProcessImageCanny(image)
try {
findAndDrawLane(imageLane, preProcessedImage, THRESH_BINARY_IMAGE_CANNY)
} catch (e: NoWindowFoundException) { }
}
return Pair(imageLane, preProcessedImage)
}
private fun checkImage(image: Mat) {
if (image.width() != WIDTH_IMAGE)
throw LaneFinderException("Wrong image width")
if (image.height() != HEIGHT_IMAGE)
throw LaneFinderException("Wrong image height")
if (!(image.type() == CvType.CV_8UC3 || image.type() == CvType.CV_8UC4))
throw LaneFinderException("Wrong image type")
}
private fun preProcessImageThreshold(image: Mat): Mat {
val croppedImage = cropImage(image.clone())
// ToDo: try to move gaussian blur after warp
Imgproc.GaussianBlur(croppedImage, croppedImage, Size(7.0, 7.0), 1.0)
warpImage(croppedImage)
Imgproc.threshold(croppedImage, croppedImage, getThreshValue(croppedImage), 255.0, Imgproc.THRESH_BINARY)
Imgproc.cvtColor(croppedImage, croppedImage, Imgproc.COLOR_BGR2GRAY)
return croppedImage
}
private fun preProcessImageCanny(image: Mat): Mat {
val croppedImage = cropImage(image.clone())
// ToDo: try to move gaussian blur after warp
Imgproc.GaussianBlur(croppedImage, croppedImage, Size(7.0, 7.0), 1.0)
Imgproc.cvtColor(croppedImage, croppedImage, Imgproc.COLOR_BGR2GRAY)
Imgproc.Canny(croppedImage, croppedImage, 100.0, 100.0)
warpImage(croppedImage)
return croppedImage
}
private fun cropImage(image: Mat): Mat {
val rectCrop = Rect(0, HEIGHT_IMAGE - HEIGHT_CROPPED_IMAGE, WIDTH_IMAGE, HEIGHT_CROPPED_IMAGE)
return image.submat(rectCrop)
}
private fun getThreshValue(image: Mat): Double {
val values = ArrayList<Double>()
val subImage = image.submat(Rect(WIDTH_WARPED_IMAGE/2 - WIDTH_RECT_THRESH/2, HEIGHT_WARPED_IMAGE- HEIGHT_RECT_THRESH, WIDTH_RECT_THRESH, HEIGHT_RECT_THRESH))
for (x in 0..(subImage.width()-1) step 10)
for (y in 0..(subImage.height()-1) step 10)
values.add(subImage.get(y, x).average())
values.sort()
for (i in 0..values.size/20)
values.removeAt(values.lastIndex)
for (i in 0..values.size*3/4)
values.removeAt(0)
return values.average() + THRESH_OVER_AVG
}
private fun warpImage(image: Mat) {
val m = Imgproc.getPerspectiveTransform(getSrcMatrix(), getDstMatrix())
Imgproc.warpPerspective(image, image, m, Size(WIDTH_WARPED_IMAGE.toDouble(), HEIGHT_WARPED_IMAGE.toDouble()))
}
private fun invWarpImage(image: Mat) {
val m = Imgproc.getPerspectiveTransform(getDstMatrix(), getSrcMatrix())
Imgproc.warpPerspective(image, image, m, Size(WIDTH_IMAGE.toDouble(), HEIGHT_CROPPED_IMAGE.toDouble()))
}
private fun getSrcMatrix(): Mat {
val leftTop = Point(WARPED_SRC_TOP.toDouble(), 0.0)
val rightTop = Point((WIDTH_IMAGE - WARPED_SRC_TOP).toDouble(), 0.0)
val rightBottom = Point((WIDTH_IMAGE - WARPED_SRC_BOTTOM).toDouble(), HEIGHT_CROPPED_IMAGE.toDouble())
val leftBottom = Point(WARPED_SRC_BOTTOM.toDouble(), HEIGHT_CROPPED_IMAGE.toDouble())
return MatOfPoint2f(leftTop, rightTop, rightBottom, leftBottom)
}
private fun getDstMatrix(): Mat {
val leftTop = Point(WARPED_DST_TOP.toDouble(), 0.0)
val rightTop = Point((WIDTH_WARPED_IMAGE - WARPED_DST_TOP).toDouble(), 0.0)
val rightBottom = Point((WIDTH_WARPED_IMAGE - WARPED_DST_BOTTOM).toDouble(), HEIGHT_WARPED_IMAGE.toDouble())
val leftBottom = Point(WARPED_DST_BOTTOM.toDouble(), HEIGHT_WARPED_IMAGE.toDouble())
return MatOfPoint2f(leftTop, rightTop, rightBottom, leftBottom)
}
private fun findAndDrawLane(imageLane: Mat, preProcessedImage: Mat, threshBinary: Int) {
val windows = mWindowFinder.findWindows(BinaryImageMatWrapper(preProcessedImage.clone(), threshBinary))
Imgproc.cvtColor(preProcessedImage, preProcessedImage, Imgproc.COLOR_GRAY2BGR)
if (windows.first.size >= 2 && windows.second.size >= 2) {
drawWindows(preProcessedImage, windows.first)
drawWindows(preProcessedImage, windows.second)
drawLinesOnPreprocessedImage(preProcessedImage, windows)
drawLinesOnBlackOriginalImage(imageLane, windows)
} else
throw NoWindowFoundException("Not enough windows found. Minimum 2 windows required for each side.")
}
private fun drawLinesOnPreprocessedImage(preProcessedImage: Mat, windows: Pair<ArrayList<Window>, ArrayList<Window>>) {
val croppedPart = Mat(HEIGHT_WARPED_IMAGE, WIDTH_WARPED_IMAGE, CvType.CV_8UC3, Scalar(0.0, 0.0, 0.0))
drawLane(croppedPart, windows.first, windows.second)
Core.addWeighted(preProcessedImage, 1.0, croppedPart, 0.7, 0.0, preProcessedImage)
}
private fun drawLinesOnBlackOriginalImage(image: Mat, windows: Pair<ArrayList<Window>, ArrayList<Window>>) {
val croppedPart = Mat(HEIGHT_WARPED_IMAGE, WIDTH_WARPED_IMAGE, CvType.CV_8UC3, Scalar(0.0, 0.0, 0.0, 0.0))
drawLane(croppedPart, windows.first, windows.second)
invWarpImage(croppedPart)
croppedPart.copyTo(image.submat(Rect(0, HEIGHT_IMAGE - HEIGHT_CROPPED_IMAGE, WIDTH_IMAGE, HEIGHT_CROPPED_IMAGE)))
}
private fun drawLane(image: Mat, windowsLeft: ArrayList<Window>, windowsRight: ArrayList<Window>) {
val lineLeft = getLine(windowsLeft)
lineLeft.sortBy { point -> point.y }
val lineRight = getLine(windowsRight)
lineRight.sortByDescending { point -> point.y }
val points = MatOfPoint(*(lineLeft+lineRight).toTypedArray())
try { Imgproc.fillConvexPoly(image, points, Scalar(0.0, 255.0, 0.0)) } catch (e: CvException) {}
}
private fun getLine(windows: ArrayList<Window>): ArrayList<Point> {
val points = getPoints(windows)
val line = ArrayList<Point>()
if (points.size >= 2) {
val x = points.map { point -> point.x.toFloat() }
val y = points.map { point -> point.y.toFloat() }
val cubicSpline = SplineInterpolator.createMonotoneCubicSpline(y, x)
for (i in (y.min()!!.toInt()..y.max()!!.toInt()))
line.add(Point(cubicSpline.interpolate(i.toFloat()).toDouble(), i.toDouble()))
line.add(Point(cubicSpline.interpolate(y.max()!!.toFloat()).toDouble(), HEIGHT_WARPED_IMAGE.toDouble()))
}
return line
}
private fun getPoints(windows: ArrayList<Window>): ArrayList<Point> {
windows.sortBy { window -> window.getMidpointY() }
val points = ArrayList<Point>()
try { points.add(windows[0].getMidpointAbove()) } catch (e: WindowException) { }
for (i in 0..(windows.lastIndex-1))
points.add(windows[i].getMidpoint())
try { points.add(windows[windows.lastIndex].getMidpointAbove()) } catch (e: WindowException) { }
points.add(windows[windows.lastIndex].getMidpoint())
try { points.add(windows[windows.lastIndex].getMidpointBelow()) } catch (e: WindowException) { }
return points
}
private fun drawWindows(image: Mat, windows: ArrayList<Window>) {
for (window in windows)
Imgproc.rectangle(
image,
Point(window.getX().toDouble(), window.getY().toDouble()),
Point(window.getBorderRight().toDouble(), window.getBorderBelow().toDouble()),
Scalar(0.0, 0.0, 255.0))
}
}