blob: d2de43113cf41b8cb67410a19503a47773666773 [file] [log] [blame]
jerrym6ebe6452013-02-18 03:00:31 +00001package org.frc971;
2
3import java.util.ArrayList;
4
5import com.googlecode.javacv.cpp.opencv_core;
6import com.googlecode.javacv.cpp.opencv_core.CvSize;
7import com.googlecode.javacv.cpp.opencv_core.IplImage;
8import com.googlecode.javacv.cpp.opencv_imgproc;
9import com.googlecode.javacv.cpp.opencv_imgproc.IplConvKernel;
10
11import edu.wpi.first.wpijavacv.DaisyExtensions;
12import edu.wpi.first.wpijavacv.WPIBinaryImage;
13import edu.wpi.first.wpijavacv.WPIColor;
14import edu.wpi.first.wpijavacv.WPIColorImage;
15import edu.wpi.first.wpijavacv.WPIContour;
16import edu.wpi.first.wpijavacv.WPIImage;
17import edu.wpi.first.wpijavacv.WPIPoint;
18import edu.wpi.first.wpijavacv.WPIPolygon;
19
20/**
21 * Vision target recognizer for FRC 2013.
22 *
23 * @author jerry
24 */
25public class Recognizer2013 implements Recognizer {
26
jerrymaa7a63b2013-02-18 06:31:22 +000027 // --- Constants that need to be tuned.
jerrymcd2c3322013-02-18 08:49:01 +000028 static final double kRoughlyHorizontalSlope = Math.tan(Math.toRadians(30));
29 static final double kRoughlyVerticalSlope = Math.tan(Math.toRadians(90 - 30));
30 private int min1Hue;
31 private int max1Hue;
32 private int min1Sat;
33 private int min1Val;
34 static final int kHoleClosingIterations = 2;
35 static final double kPolygonPercentFit = 12;
jerrymaa7a63b2013-02-18 06:31:22 +000036
37 static final int kMinWidthAt320 = 35; // for high goal and middle goals
38
39 // These aspect ratios include the outside edges of the vision target tape.
40 static final double kHighGoalAspect = (21 + 8.0) / (54 + 8);
41 static final double kMiddleGoalAspect = (24 + 8.0) / (54 + 8);
42 static final double kMinAspect = kHighGoalAspect * 0.6;
43 static final double kMaxAspect = kMiddleGoalAspect * 1.4;
jerrym6ebe6452013-02-18 03:00:31 +000044
45 static final double kShooterOffsetDeg = 0;
46 static final double kHorizontalFOVDeg = 47.0;
47 static final double kVerticalFOVDeg = 480.0 / 640.0 * kHorizontalFOVDeg;
48
jerrymaa7a63b2013-02-18 06:31:22 +000049 // --- Colors for drawing indicators on the image.
jerrym6ebe6452013-02-18 03:00:31 +000050 private static final WPIColor reject1Color = WPIColor.GRAY;
51 private static final WPIColor reject2Color = WPIColor.YELLOW;
52 private static final WPIColor candidateColor = WPIColor.BLUE;
53 private static final WPIColor targetColor = new WPIColor(255, 0, 0);
54
55 // Show intermediate images for parameter tuning.
56 private final DebugCanvas thresholdedCanvas = new DebugCanvas("thresholded");
57 private final DebugCanvas morphedCanvas = new DebugCanvas("morphed");
58
jerrymaa7a63b2013-02-18 06:31:22 +000059 // Data to reuse for each frame.
jerrym6ebe6452013-02-18 03:00:31 +000060 private final DaisyExtensions daisyExtensions = new DaisyExtensions();
61 private final IplConvKernel morphKernel = IplConvKernel.create(3, 3, 1, 1,
jerrymdda60132013-02-18 09:25:03 +000062 opencv_imgproc.CV_SHAPE_RECT, null);
jerrym6ebe6452013-02-18 03:00:31 +000063 private final ArrayList<WPIPolygon> polygons = new ArrayList<WPIPolygon>();
jerrymaa7a63b2013-02-18 06:31:22 +000064
65 // Frame-size-dependent data to reuse for each frame.
66 private CvSize size = null;
jerrym6ebe6452013-02-18 03:00:31 +000067 private WPIColorImage rawImage;
68 private IplImage bin;
69 private IplImage hsv;
70 private IplImage hue;
71 private IplImage sat;
72 private IplImage val;
jerrymaa7a63b2013-02-18 06:31:22 +000073 private int minWidth;
jerrym6ebe6452013-02-18 03:00:31 +000074 private WPIPoint linePt1, linePt2; // crosshair endpoints
75
76 public Recognizer2013() {
jerrymdda60132013-02-18 09:25:03 +000077 setHSVRange(70, 106, 137, 27);
jerrym6ebe6452013-02-18 03:00:31 +000078 }
79
80 @Override
jerrymcd2c3322013-02-18 08:49:01 +000081 public void setHSVRange(int minHue, int maxHue, int minSat, int minVal) {
jerrymdda60132013-02-18 09:25:03 +000082 min1Hue = minHue - 1; // - 1 because cvThreshold() does > instead of >=
83 max1Hue = maxHue + 1;
84 min1Sat = minSat - 1;
85 min1Val = minVal - 1;
jerrymcd2c3322013-02-18 08:49:01 +000086 }
87 @Override
88 public int getHueMin() { return min1Hue + 1; }
89 @Override
90 public int getHueMax() { return max1Hue - 1; }
91 @Override
92 public int getSatMin() { return min1Sat - 1; }
93 @Override
94 public int getValMin() { return min1Val - 1; }
95
96 @Override
jerrymf96c32c2013-02-18 19:30:45 +000097 public void showIntermediateStages(boolean enable) {
98 thresholdedCanvas.show = enable;
99 morphedCanvas.show = enable;
100 }
101
102 @Override
jerrym6ebe6452013-02-18 03:00:31 +0000103 public WPIImage processImage(WPIColorImage cameraImage) {
jerrymdda60132013-02-18 09:25:03 +0000104 // (Re)allocate the intermediate images if the input is a different
105 // size than the previous image.
jerrym6ebe6452013-02-18 03:00:31 +0000106 if (size == null || size.width() != cameraImage.getWidth()
jerrymdda60132013-02-18 09:25:03 +0000107 || size.height() != cameraImage.getHeight()) {
jerrym6ebe6452013-02-18 03:00:31 +0000108 size = opencv_core.cvSize(cameraImage.getWidth(),
jerrymdda60132013-02-18 09:25:03 +0000109 cameraImage.getHeight());
jerrym6ebe6452013-02-18 03:00:31 +0000110 rawImage = DaisyExtensions.makeWPIColorImage(
jerrymdda60132013-02-18 09:25:03 +0000111 DaisyExtensions.getIplImage(cameraImage));
jerrym6ebe6452013-02-18 03:00:31 +0000112 bin = IplImage.create(size, 8, 1);
113 hsv = IplImage.create(size, 8, 3);
114 hue = IplImage.create(size, 8, 1);
115 sat = IplImage.create(size, 8, 1);
116 val = IplImage.create(size, 8, 1);
jerrymaa7a63b2013-02-18 06:31:22 +0000117 minWidth = (kMinWidthAt320 * cameraImage.getWidth() + 319) / 320;
jerrym6ebe6452013-02-18 03:00:31 +0000118
119 int horizontalOffsetPixels = (int)Math.round(
jerrymdda60132013-02-18 09:25:03 +0000120 kShooterOffsetDeg * size.width() / kHorizontalFOVDeg);
jerrym6ebe6452013-02-18 03:00:31 +0000121 int x = size.width() / 2 + horizontalOffsetPixels;
122 linePt1 = new WPIPoint(x, size.height() - 1);
123 linePt2 = new WPIPoint(x, 0);
124 } else {
jerrymaa7a63b2013-02-18 06:31:22 +0000125 // Copy the camera image so it's safe to draw on.
jerrym6ebe6452013-02-18 03:00:31 +0000126 opencv_core.cvCopy(DaisyExtensions.getIplImage(cameraImage),
jerrymdda60132013-02-18 09:25:03 +0000127 DaisyExtensions.getIplImage(rawImage));
jerrym6ebe6452013-02-18 03:00:31 +0000128 }
129
130 IplImage input = DaisyExtensions.getIplImage(rawImage);
131
132 // Threshold the pixels in HSV color space.
133 // TODO(jerry): Do this in one pass of a pixel-processing loop.
jerrymaa7a63b2013-02-18 06:31:22 +0000134 opencv_imgproc.cvCvtColor(input, hsv, opencv_imgproc.CV_BGR2HSV_FULL);
jerrym6ebe6452013-02-18 03:00:31 +0000135 opencv_core.cvSplit(hsv, hue, sat, val, null);
136
137 // NOTE: Since red is at the end of the cyclic color space, you can OR
138 // a threshold and an inverted threshold to match red pixels.
139 // TODO(jerry): Use tunable constants instead of literals.
jerrymcd2c3322013-02-18 08:49:01 +0000140 opencv_imgproc.cvThreshold(hue, bin, min1Hue, 255, opencv_imgproc.CV_THRESH_BINARY);
141 opencv_imgproc.cvThreshold(hue, hue, max1Hue, 255, opencv_imgproc.CV_THRESH_BINARY_INV);
142 opencv_imgproc.cvThreshold(sat, sat, min1Sat, 255, opencv_imgproc.CV_THRESH_BINARY);
143 opencv_imgproc.cvThreshold(val, val, min1Val, 255, opencv_imgproc.CV_THRESH_BINARY);
jerrym6ebe6452013-02-18 03:00:31 +0000144
145 // Combine the results to obtain a binary image which is mostly the
146 // interesting pixels.
147 opencv_core.cvAnd(hue, bin, bin, null);
148 opencv_core.cvAnd(bin, sat, bin, null);
149 opencv_core.cvAnd(bin, val, bin, null);
150
151 thresholdedCanvas.showImage(bin);
152
153 // Fill in gaps using binary morphology.
154 opencv_imgproc.cvMorphologyEx(bin, bin, null, morphKernel,
jerrymdda60132013-02-18 09:25:03 +0000155 opencv_imgproc.CV_MOP_CLOSE, kHoleClosingIterations);
jerrym6ebe6452013-02-18 03:00:31 +0000156
157 morphedCanvas.showImage(bin);
158
159 // Find contours.
jerrymaa7a63b2013-02-18 06:31:22 +0000160 //
161 // TODO(jerry): Request contours as a two-level hierarchy (blobs and
162 // holes)? The targets have known sizes and their holes have known,
163 // smaller sizes. This matters for distance measurement. OTOH it's moot
164 // if/when we use the vertical stripes for distance measurement.
jerrym6ebe6452013-02-18 03:00:31 +0000165 WPIBinaryImage binWpi = DaisyExtensions.makeWPIBinaryImage(bin);
jerrymaa7a63b2013-02-18 06:31:22 +0000166 WPIContour[] contours = daisyExtensions.findConvexContours(binWpi);
jerrym6ebe6452013-02-18 03:00:31 +0000167
jerrymaa7a63b2013-02-18 06:31:22 +0000168 // Simplify the contours to polygons and filter by size and aspect ratio.
169 //
170 // TODO(jerry): Also look for the two vertical stripe vision targets.
171 // They'll greatly increase the precision of measuring the distance. If
172 // both stripes are visible, they'll increase the accuracy for
173 // identifying the high goal.
jerrym6ebe6452013-02-18 03:00:31 +0000174 polygons.clear();
175 for (WPIContour c : contours) {
jerrymaa7a63b2013-02-18 06:31:22 +0000176 if (c.getWidth() >= minWidth) {
jerrymdda60132013-02-18 09:25:03 +0000177 double ratio = ((double) c.getHeight()) / c.getWidth();
178 if (ratio >= kMinAspect && ratio <= kMaxAspect) {
179 polygons.add(c.approxPolygon(kPolygonPercentFit));
180 // System.out.println(" Accepted aspect ratio " + ratio);
181 } else {
182 // System.out.println(" Rejected aspect ratio " + ratio);
183 }
jerrym6ebe6452013-02-18 03:00:31 +0000184 }
185 }
186
jerrymaa7a63b2013-02-18 06:31:22 +0000187 // Pick the target with the highest center-point that matches yet more
188 // filter criteria.
jerrym6ebe6452013-02-18 03:00:31 +0000189 WPIPolygon bestTarget = null;
190 int highestY = Integer.MAX_VALUE;
191
192 for (WPIPolygon p : polygons) {
jerrymaa7a63b2013-02-18 06:31:22 +0000193 // TODO(jerry): Replace boolean filters with a scoring function?
jerrym6ebe6452013-02-18 03:00:31 +0000194 if (p.isConvex() && p.getNumVertices() == 4) { // quadrilateral
195 WPIPoint[] points = p.getPoints();
jerrymaa7a63b2013-02-18 06:31:22 +0000196 // Filter for polygons with 2 ~horizontal and 2 ~vertical sides.
jerrym6ebe6452013-02-18 03:00:31 +0000197 int numRoughlyHorizontal = 0;
198 int numRoughlyVertical = 0;
199 for (int i = 0; i < 4; ++i) {
200 double dy = points[i].getY() - points[(i + 1) % 4].getY();
201 double dx = points[i].getX() - points[(i + 1) % 4].getX();
202 double slope = Double.MAX_VALUE;
203 if (dx != 0) {
204 slope = Math.abs(dy / dx);
205 }
206
207 if (slope < kRoughlyHorizontalSlope) {
208 ++numRoughlyHorizontal;
209 } else if (slope > kRoughlyVerticalSlope) {
210 ++numRoughlyVertical;
211 }
212 }
213
jerrymaa7a63b2013-02-18 06:31:22 +0000214 if (numRoughlyHorizontal >= 2 && numRoughlyVertical == 2) {
jerrym6ebe6452013-02-18 03:00:31 +0000215 rawImage.drawPolygon(p, candidateColor, 2);
216
217 int pCenterX = p.getX() + p.getWidth() / 2;
218 int pCenterY = p.getY() + p.getHeight() / 2;
219
220 rawImage.drawPoint(new WPIPoint(pCenterX, pCenterY),
jerrymdda60132013-02-18 09:25:03 +0000221 targetColor, 2);
jerrym6ebe6452013-02-18 03:00:31 +0000222 if (pCenterY < highestY) {
223 bestTarget = p;
224 highestY = pCenterY;
225 }
226 } else {
227 rawImage.drawPolygon(p, reject2Color, 1);
228 }
229 } else {
230 rawImage.drawPolygon(p, reject1Color, 1);
231 }
232 }
233
234 if (bestTarget != null) {
235 double w = bestTarget.getWidth();
236 double h = bestTarget.getHeight();
237 double x = bestTarget.getX() + w / 2;
238 double y = bestTarget.getY() + h / 2;
239
240 rawImage.drawPolygon(bestTarget, targetColor, 2);
241
242 System.out.println("Best target at (" + x + ", " + y + ") size "
jerrymdda60132013-02-18 09:25:03 +0000243 + w + " x " + h);
jerrym6ebe6452013-02-18 03:00:31 +0000244 } else {
245 System.out.println("No target found");
246 }
247
248 // Draw a crosshair
249 rawImage.drawLine(linePt1, linePt2, targetColor, 1);
250
251 daisyExtensions.releaseMemory();
252 //System.gc();
253
254 return rawImage;
255 }
256
257}