blob: e560f1e30059623556a7207d5ba368355f73aa32 [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,
62 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() {
jerrymcd2c3322013-02-18 08:49:01 +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) {
82 min1Hue = minHue - 1; // - 1 because cvThreshold() does > instead of >=
83 max1Hue = maxHue + 1;
84 min1Sat = minSat - 1;
85 min1Val = minVal - 1;
86 }
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
jerrym6ebe6452013-02-18 03:00:31 +000097 public WPIImage processImage(WPIColorImage cameraImage) {
98 // (Re)allocate the intermediate images if the input is a different
99 // size than the previous image.
100 if (size == null || size.width() != cameraImage.getWidth()
101 || size.height() != cameraImage.getHeight()) {
102 size = opencv_core.cvSize(cameraImage.getWidth(),
103 cameraImage.getHeight());
104 rawImage = DaisyExtensions.makeWPIColorImage(
105 DaisyExtensions.getIplImage(cameraImage));
106 bin = IplImage.create(size, 8, 1);
107 hsv = IplImage.create(size, 8, 3);
108 hue = IplImage.create(size, 8, 1);
109 sat = IplImage.create(size, 8, 1);
110 val = IplImage.create(size, 8, 1);
jerrymaa7a63b2013-02-18 06:31:22 +0000111 minWidth = (kMinWidthAt320 * cameraImage.getWidth() + 319) / 320;
jerrym6ebe6452013-02-18 03:00:31 +0000112
113 int horizontalOffsetPixels = (int)Math.round(
114 kShooterOffsetDeg * size.width() / kHorizontalFOVDeg);
115 int x = size.width() / 2 + horizontalOffsetPixels;
116 linePt1 = new WPIPoint(x, size.height() - 1);
117 linePt2 = new WPIPoint(x, 0);
118 } else {
jerrymaa7a63b2013-02-18 06:31:22 +0000119 // Copy the camera image so it's safe to draw on.
jerrym6ebe6452013-02-18 03:00:31 +0000120 opencv_core.cvCopy(DaisyExtensions.getIplImage(cameraImage),
121 DaisyExtensions.getIplImage(rawImage));
122 }
123
124 IplImage input = DaisyExtensions.getIplImage(rawImage);
125
126 // Threshold the pixels in HSV color space.
127 // TODO(jerry): Do this in one pass of a pixel-processing loop.
jerrymaa7a63b2013-02-18 06:31:22 +0000128 opencv_imgproc.cvCvtColor(input, hsv, opencv_imgproc.CV_BGR2HSV_FULL);
jerrym6ebe6452013-02-18 03:00:31 +0000129 opencv_core.cvSplit(hsv, hue, sat, val, null);
130
131 // NOTE: Since red is at the end of the cyclic color space, you can OR
132 // a threshold and an inverted threshold to match red pixels.
133 // TODO(jerry): Use tunable constants instead of literals.
jerrymcd2c3322013-02-18 08:49:01 +0000134 opencv_imgproc.cvThreshold(hue, bin, min1Hue, 255, opencv_imgproc.CV_THRESH_BINARY);
135 opencv_imgproc.cvThreshold(hue, hue, max1Hue, 255, opencv_imgproc.CV_THRESH_BINARY_INV);
136 opencv_imgproc.cvThreshold(sat, sat, min1Sat, 255, opencv_imgproc.CV_THRESH_BINARY);
137 opencv_imgproc.cvThreshold(val, val, min1Val, 255, opencv_imgproc.CV_THRESH_BINARY);
jerrym6ebe6452013-02-18 03:00:31 +0000138
139 // Combine the results to obtain a binary image which is mostly the
140 // interesting pixels.
141 opencv_core.cvAnd(hue, bin, bin, null);
142 opencv_core.cvAnd(bin, sat, bin, null);
143 opencv_core.cvAnd(bin, val, bin, null);
144
145 thresholdedCanvas.showImage(bin);
146
147 // Fill in gaps using binary morphology.
148 opencv_imgproc.cvMorphologyEx(bin, bin, null, morphKernel,
149 opencv_imgproc.CV_MOP_CLOSE, kHoleClosingIterations);
150
151 morphedCanvas.showImage(bin);
152
153 // Find contours.
jerrymaa7a63b2013-02-18 06:31:22 +0000154 //
155 // TODO(jerry): Request contours as a two-level hierarchy (blobs and
156 // holes)? The targets have known sizes and their holes have known,
157 // smaller sizes. This matters for distance measurement. OTOH it's moot
158 // if/when we use the vertical stripes for distance measurement.
jerrym6ebe6452013-02-18 03:00:31 +0000159 WPIBinaryImage binWpi = DaisyExtensions.makeWPIBinaryImage(bin);
jerrymaa7a63b2013-02-18 06:31:22 +0000160 WPIContour[] contours = daisyExtensions.findConvexContours(binWpi);
jerrym6ebe6452013-02-18 03:00:31 +0000161
jerrymaa7a63b2013-02-18 06:31:22 +0000162 // Simplify the contours to polygons and filter by size and aspect ratio.
163 //
164 // TODO(jerry): Also look for the two vertical stripe vision targets.
165 // They'll greatly increase the precision of measuring the distance. If
166 // both stripes are visible, they'll increase the accuracy for
167 // identifying the high goal.
jerrym6ebe6452013-02-18 03:00:31 +0000168 polygons.clear();
169 for (WPIContour c : contours) {
jerrymaa7a63b2013-02-18 06:31:22 +0000170 if (c.getWidth() >= minWidth) {
171 double ratio = ((double) c.getHeight()) / c.getWidth();
172 if (ratio >= kMinAspect && ratio <= kMaxAspect) {
173 polygons.add(c.approxPolygon(kPolygonPercentFit));
174// System.out.println(" Accepted aspect ratio " + ratio);
175 } else {
176// System.out.println(" Rejected aspect ratio " + ratio);
177 }
jerrym6ebe6452013-02-18 03:00:31 +0000178 }
179 }
180
jerrymaa7a63b2013-02-18 06:31:22 +0000181 // Pick the target with the highest center-point that matches yet more
182 // filter criteria.
jerrym6ebe6452013-02-18 03:00:31 +0000183 WPIPolygon bestTarget = null;
184 int highestY = Integer.MAX_VALUE;
185
186 for (WPIPolygon p : polygons) {
jerrymaa7a63b2013-02-18 06:31:22 +0000187 // TODO(jerry): Replace boolean filters with a scoring function?
jerrym6ebe6452013-02-18 03:00:31 +0000188 if (p.isConvex() && p.getNumVertices() == 4) { // quadrilateral
189 WPIPoint[] points = p.getPoints();
jerrymaa7a63b2013-02-18 06:31:22 +0000190 // Filter for polygons with 2 ~horizontal and 2 ~vertical sides.
jerrym6ebe6452013-02-18 03:00:31 +0000191 int numRoughlyHorizontal = 0;
192 int numRoughlyVertical = 0;
193 for (int i = 0; i < 4; ++i) {
194 double dy = points[i].getY() - points[(i + 1) % 4].getY();
195 double dx = points[i].getX() - points[(i + 1) % 4].getX();
196 double slope = Double.MAX_VALUE;
197 if (dx != 0) {
198 slope = Math.abs(dy / dx);
199 }
200
201 if (slope < kRoughlyHorizontalSlope) {
202 ++numRoughlyHorizontal;
203 } else if (slope > kRoughlyVerticalSlope) {
204 ++numRoughlyVertical;
205 }
206 }
207
jerrymaa7a63b2013-02-18 06:31:22 +0000208 if (numRoughlyHorizontal >= 2 && numRoughlyVertical == 2) {
jerrym6ebe6452013-02-18 03:00:31 +0000209 rawImage.drawPolygon(p, candidateColor, 2);
210
211 int pCenterX = p.getX() + p.getWidth() / 2;
212 int pCenterY = p.getY() + p.getHeight() / 2;
213
214 rawImage.drawPoint(new WPIPoint(pCenterX, pCenterY),
jerrymaa7a63b2013-02-18 06:31:22 +0000215 targetColor, 2);
jerrym6ebe6452013-02-18 03:00:31 +0000216 if (pCenterY < highestY) {
217 bestTarget = p;
218 highestY = pCenterY;
219 }
220 } else {
221 rawImage.drawPolygon(p, reject2Color, 1);
222 }
223 } else {
224 rawImage.drawPolygon(p, reject1Color, 1);
225 }
226 }
227
228 if (bestTarget != null) {
229 double w = bestTarget.getWidth();
230 double h = bestTarget.getHeight();
231 double x = bestTarget.getX() + w / 2;
232 double y = bestTarget.getY() + h / 2;
233
234 rawImage.drawPolygon(bestTarget, targetColor, 2);
235
236 System.out.println("Best target at (" + x + ", " + y + ") size "
237 + w + " x " + h);
238 } else {
239 System.out.println("No target found");
240 }
241
242 // Draw a crosshair
243 rawImage.drawLine(linePt1, linePt2, targetColor, 1);
244
245 daisyExtensions.releaseMemory();
246 //System.gc();
247
248 return rawImage;
249 }
250
251}