blob: 115af275327dec85ddf1b76a3e9d55626b176fc4 [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 *
jerrymf0c84552013-02-19 00:51:20 +000023 * @author jrussell
jerrym6ebe6452013-02-18 03:00:31 +000024 * @author jerry
25 */
26public class Recognizer2013 implements Recognizer {
27
jerrymf0c84552013-02-19 00:51:20 +000028 // --- Tunable recognizer constants.
jerrymcd2c3322013-02-18 08:49:01 +000029 static final double kRoughlyHorizontalSlope = Math.tan(Math.toRadians(30));
30 static final double kRoughlyVerticalSlope = Math.tan(Math.toRadians(90 - 30));
jerrymcd2c3322013-02-18 08:49:01 +000031 static final int kHoleClosingIterations = 2;
32 static final double kPolygonPercentFit = 12;
jerrymaa7a63b2013-02-18 06:31:22 +000033 static final int kMinWidthAt320 = 35; // for high goal and middle goals
34
jerrymf0c84552013-02-19 00:51:20 +000035 // --- Field dimensions.
36 // The target aspect ratios are for the midlines of the vision target tape.
37 static final double kGoalWidthIn = 54; // of the high and middle targets
38 static final double kTargetWidthIn = kGoalWidthIn + 4;
39 static final double kHighGoalAspect = (21 + 4) / kTargetWidthIn;
40 static final double kMiddleGoalAspect = (24 + 4) / kTargetWidthIn;
jerrymaa7a63b2013-02-18 06:31:22 +000041 static final double kMinAspect = kHighGoalAspect * 0.6;
42 static final double kMaxAspect = kMiddleGoalAspect * 1.4;
jerrymf0c84552013-02-19 00:51:20 +000043 static final double kTopTargetHeightIn = 104.125 + 21.0/2; // center of target
jerrym6ebe6452013-02-18 03:00:31 +000044
jerrymf0c84552013-02-19 00:51:20 +000045 // --- Robot and camera dimensions.
46 static final double kShooterOffsetDeg = 0; // azimuth offset from camera to shooter
47 static final double kHorizontalFOVDeg = 44.0; // Logitech C210 camera
jerrym6ebe6452013-02-18 03:00:31 +000048 static final double kVerticalFOVDeg = 480.0 / 640.0 * kHorizontalFOVDeg;
jerrymf0c84552013-02-19 00:51:20 +000049 static final double kCameraHeightIn = 24.0; // TODO
50 static final double kCameraPitchDeg = 21.0; // TODO
51 static final double kTanHFOV2 = Math.tan(Math.toRadians(kHorizontalFOVDeg / 2));
52 static final double kTanVFOV2 = Math.tan(Math.toRadians(kVerticalFOVDeg / 2));
jerrym6ebe6452013-02-18 03:00:31 +000053
jerrymaa7a63b2013-02-18 06:31:22 +000054 // --- Colors for drawing indicators on the image.
jerrym6ebe6452013-02-18 03:00:31 +000055 private static final WPIColor reject1Color = WPIColor.GRAY;
56 private static final WPIColor reject2Color = WPIColor.YELLOW;
57 private static final WPIColor candidateColor = WPIColor.BLUE;
jerrymf0c84552013-02-19 00:51:20 +000058 private static final WPIColor targetColor = WPIColor.RED;
jerrym6ebe6452013-02-18 03:00:31 +000059
jerrymf0c84552013-02-19 00:51:20 +000060 // --- Color thresholds, initialized in the constructor.
jerrymcd2469c2013-02-18 20:15:28 +000061 private int min1Hue, max1Hue, min1Sat, min1Val;
62
jerrym6ebe6452013-02-18 03:00:31 +000063 // Show intermediate images for parameter tuning.
64 private final DebugCanvas thresholdedCanvas = new DebugCanvas("thresholded");
65 private final DebugCanvas morphedCanvas = new DebugCanvas("morphed");
66
jerrymaa7a63b2013-02-18 06:31:22 +000067 // Data to reuse for each frame.
jerrym6ebe6452013-02-18 03:00:31 +000068 private final DaisyExtensions daisyExtensions = new DaisyExtensions();
69 private final IplConvKernel morphKernel = IplConvKernel.create(3, 3, 1, 1,
jerrymdda60132013-02-18 09:25:03 +000070 opencv_imgproc.CV_SHAPE_RECT, null);
jerrym6ebe6452013-02-18 03:00:31 +000071 private final ArrayList<WPIPolygon> polygons = new ArrayList<WPIPolygon>();
jerrymaa7a63b2013-02-18 06:31:22 +000072
73 // Frame-size-dependent data to reuse for each frame.
74 private CvSize size = null;
jerrym6ebe6452013-02-18 03:00:31 +000075 private WPIColorImage rawImage;
76 private IplImage bin;
77 private IplImage hsv;
78 private IplImage hue;
79 private IplImage sat;
80 private IplImage val;
jerrymaa7a63b2013-02-18 06:31:22 +000081 private int minWidth;
jerrym6ebe6452013-02-18 03:00:31 +000082 private WPIPoint linePt1, linePt2; // crosshair endpoints
83
84 public Recognizer2013() {
jerrymdda60132013-02-18 09:25:03 +000085 setHSVRange(70, 106, 137, 27);
jerrym6ebe6452013-02-18 03:00:31 +000086 }
87
88 @Override
jerrymcd2c3322013-02-18 08:49:01 +000089 public void setHSVRange(int minHue, int maxHue, int minSat, int minVal) {
jerrymdda60132013-02-18 09:25:03 +000090 min1Hue = minHue - 1; // - 1 because cvThreshold() does > instead of >=
91 max1Hue = maxHue + 1;
92 min1Sat = minSat - 1;
93 min1Val = minVal - 1;
jerrymcd2c3322013-02-18 08:49:01 +000094 }
95 @Override
96 public int getHueMin() { return min1Hue + 1; }
97 @Override
98 public int getHueMax() { return max1Hue - 1; }
99 @Override
jerrymcd2469c2013-02-18 20:15:28 +0000100 public int getSatMin() { return min1Sat + 1; }
jerrymcd2c3322013-02-18 08:49:01 +0000101 @Override
jerrymcd2469c2013-02-18 20:15:28 +0000102 public int getValMin() { return min1Val + 1; }
jerrymcd2c3322013-02-18 08:49:01 +0000103
104 @Override
jerrymf96c32c2013-02-18 19:30:45 +0000105 public void showIntermediateStages(boolean enable) {
106 thresholdedCanvas.show = enable;
107 morphedCanvas.show = enable;
108 }
109
110 @Override
jerrym6ebe6452013-02-18 03:00:31 +0000111 public WPIImage processImage(WPIColorImage cameraImage) {
jerrymdda60132013-02-18 09:25:03 +0000112 // (Re)allocate the intermediate images if the input is a different
113 // size than the previous image.
jerrym6ebe6452013-02-18 03:00:31 +0000114 if (size == null || size.width() != cameraImage.getWidth()
jerrymdda60132013-02-18 09:25:03 +0000115 || size.height() != cameraImage.getHeight()) {
jerrym6ebe6452013-02-18 03:00:31 +0000116 size = opencv_core.cvSize(cameraImage.getWidth(),
jerrymdda60132013-02-18 09:25:03 +0000117 cameraImage.getHeight());
jerrym6ebe6452013-02-18 03:00:31 +0000118 rawImage = DaisyExtensions.makeWPIColorImage(
jerrymdda60132013-02-18 09:25:03 +0000119 DaisyExtensions.getIplImage(cameraImage));
jerrym6ebe6452013-02-18 03:00:31 +0000120 bin = IplImage.create(size, 8, 1);
121 hsv = IplImage.create(size, 8, 3);
122 hue = IplImage.create(size, 8, 1);
123 sat = IplImage.create(size, 8, 1);
124 val = IplImage.create(size, 8, 1);
jerrymaa7a63b2013-02-18 06:31:22 +0000125 minWidth = (kMinWidthAt320 * cameraImage.getWidth() + 319) / 320;
jerrym6ebe6452013-02-18 03:00:31 +0000126
127 int horizontalOffsetPixels = (int)Math.round(
jerrymdda60132013-02-18 09:25:03 +0000128 kShooterOffsetDeg * size.width() / kHorizontalFOVDeg);
jerrym6ebe6452013-02-18 03:00:31 +0000129 int x = size.width() / 2 + horizontalOffsetPixels;
130 linePt1 = new WPIPoint(x, size.height() - 1);
131 linePt2 = new WPIPoint(x, 0);
132 } else {
jerrymaa7a63b2013-02-18 06:31:22 +0000133 // Copy the camera image so it's safe to draw on.
jerrym6ebe6452013-02-18 03:00:31 +0000134 opencv_core.cvCopy(DaisyExtensions.getIplImage(cameraImage),
jerrymdda60132013-02-18 09:25:03 +0000135 DaisyExtensions.getIplImage(rawImage));
jerrym6ebe6452013-02-18 03:00:31 +0000136 }
137
138 IplImage input = DaisyExtensions.getIplImage(rawImage);
139
140 // Threshold the pixels in HSV color space.
141 // TODO(jerry): Do this in one pass of a pixel-processing loop.
jerrymaa7a63b2013-02-18 06:31:22 +0000142 opencv_imgproc.cvCvtColor(input, hsv, opencv_imgproc.CV_BGR2HSV_FULL);
jerrym6ebe6452013-02-18 03:00:31 +0000143 opencv_core.cvSplit(hsv, hue, sat, val, null);
144
145 // NOTE: Since red is at the end of the cyclic color space, you can OR
146 // a threshold and an inverted threshold to match red pixels.
jerrymcd2c3322013-02-18 08:49:01 +0000147 opencv_imgproc.cvThreshold(hue, bin, min1Hue, 255, opencv_imgproc.CV_THRESH_BINARY);
148 opencv_imgproc.cvThreshold(hue, hue, max1Hue, 255, opencv_imgproc.CV_THRESH_BINARY_INV);
149 opencv_imgproc.cvThreshold(sat, sat, min1Sat, 255, opencv_imgproc.CV_THRESH_BINARY);
150 opencv_imgproc.cvThreshold(val, val, min1Val, 255, opencv_imgproc.CV_THRESH_BINARY);
jerrym6ebe6452013-02-18 03:00:31 +0000151
152 // Combine the results to obtain a binary image which is mostly the
153 // interesting pixels.
154 opencv_core.cvAnd(hue, bin, bin, null);
155 opencv_core.cvAnd(bin, sat, bin, null);
156 opencv_core.cvAnd(bin, val, bin, null);
157
158 thresholdedCanvas.showImage(bin);
159
160 // Fill in gaps using binary morphology.
161 opencv_imgproc.cvMorphologyEx(bin, bin, null, morphKernel,
jerrymdda60132013-02-18 09:25:03 +0000162 opencv_imgproc.CV_MOP_CLOSE, kHoleClosingIterations);
jerrym6ebe6452013-02-18 03:00:31 +0000163
164 morphedCanvas.showImage(bin);
165
166 // Find contours.
jerrymf0c84552013-02-19 00:51:20 +0000167 //
168 // NOTE: If we distinguished between the inner and outer boundaries of
169 // the vision target rectangles, we could apply a more accurate width
170 // filter and more accurately compute the target range.
jerrym6ebe6452013-02-18 03:00:31 +0000171 WPIBinaryImage binWpi = DaisyExtensions.makeWPIBinaryImage(bin);
jerrymaa7a63b2013-02-18 06:31:22 +0000172 WPIContour[] contours = daisyExtensions.findConvexContours(binWpi);
jerrym6ebe6452013-02-18 03:00:31 +0000173
jerrymaa7a63b2013-02-18 06:31:22 +0000174 // Simplify the contours to polygons and filter by size and aspect ratio.
175 //
176 // TODO(jerry): Also look for the two vertical stripe vision targets.
177 // They'll greatly increase the precision of measuring the distance. If
178 // both stripes are visible, they'll increase the accuracy for
179 // identifying the high goal.
jerrym6ebe6452013-02-18 03:00:31 +0000180 polygons.clear();
181 for (WPIContour c : contours) {
jerrymaa7a63b2013-02-18 06:31:22 +0000182 if (c.getWidth() >= minWidth) {
jerrymdda60132013-02-18 09:25:03 +0000183 double ratio = ((double) c.getHeight()) / c.getWidth();
184 if (ratio >= kMinAspect && ratio <= kMaxAspect) {
185 polygons.add(c.approxPolygon(kPolygonPercentFit));
186 // System.out.println(" Accepted aspect ratio " + ratio);
187 } else {
188 // System.out.println(" Rejected aspect ratio " + ratio);
189 }
jerrym6ebe6452013-02-18 03:00:31 +0000190 }
191 }
192
jerrymaa7a63b2013-02-18 06:31:22 +0000193 // Pick the target with the highest center-point that matches yet more
194 // filter criteria.
jerrym6ebe6452013-02-18 03:00:31 +0000195 WPIPolygon bestTarget = null;
196 int highestY = Integer.MAX_VALUE;
197
198 for (WPIPolygon p : polygons) {
jerrymaa7a63b2013-02-18 06:31:22 +0000199 // TODO(jerry): Replace boolean filters with a scoring function?
jerrym6ebe6452013-02-18 03:00:31 +0000200 if (p.isConvex() && p.getNumVertices() == 4) { // quadrilateral
201 WPIPoint[] points = p.getPoints();
jerrymaa7a63b2013-02-18 06:31:22 +0000202 // Filter for polygons with 2 ~horizontal and 2 ~vertical sides.
jerrym6ebe6452013-02-18 03:00:31 +0000203 int numRoughlyHorizontal = 0;
204 int numRoughlyVertical = 0;
205 for (int i = 0; i < 4; ++i) {
206 double dy = points[i].getY() - points[(i + 1) % 4].getY();
207 double dx = points[i].getX() - points[(i + 1) % 4].getX();
208 double slope = Double.MAX_VALUE;
209 if (dx != 0) {
210 slope = Math.abs(dy / dx);
211 }
212
213 if (slope < kRoughlyHorizontalSlope) {
214 ++numRoughlyHorizontal;
215 } else if (slope > kRoughlyVerticalSlope) {
216 ++numRoughlyVertical;
217 }
218 }
219
jerrymaa7a63b2013-02-18 06:31:22 +0000220 if (numRoughlyHorizontal >= 2 && numRoughlyVertical == 2) {
jerrym6ebe6452013-02-18 03:00:31 +0000221 int pCenterX = p.getX() + p.getWidth() / 2;
222 int pCenterY = p.getY() + p.getHeight() / 2;
223
jerrymf0c84552013-02-19 00:51:20 +0000224 rawImage.drawPolygon(p, candidateColor, 2);
jerrym6ebe6452013-02-18 03:00:31 +0000225 rawImage.drawPoint(new WPIPoint(pCenterX, pCenterY),
jerrymdda60132013-02-18 09:25:03 +0000226 targetColor, 2);
jerrym6ebe6452013-02-18 03:00:31 +0000227 if (pCenterY < highestY) {
228 bestTarget = p;
229 highestY = pCenterY;
230 }
231 } else {
232 rawImage.drawPolygon(p, reject2Color, 1);
233 }
234 } else {
235 rawImage.drawPolygon(p, reject1Color, 1);
236 }
237 }
238
239 if (bestTarget != null) {
jerrym6ebe6452013-02-18 03:00:31 +0000240 rawImage.drawPolygon(bestTarget, targetColor, 2);
jerrymf0c84552013-02-19 00:51:20 +0000241 measureTarget(bestTarget);
jerrym6ebe6452013-02-18 03:00:31 +0000242 } else {
243 System.out.println("No target found");
244 }
245
246 // Draw a crosshair
247 rawImage.drawLine(linePt1, linePt2, targetColor, 1);
248
249 daisyExtensions.releaseMemory();
250 //System.gc();
251
252 return rawImage;
253 }
254
jerrymf0c84552013-02-19 00:51:20 +0000255 /**
256 * Uses the camera, field, and robot dimensions to compute targeting info.
257 */
258 private void measureTarget(WPIPolygon target) {
259 double w = target.getWidth();
260 double h = target.getHeight();
261 double x = target.getX() + w / 2; // target center in view coords
262 double y = target.getY() + h / 2;
263
264 double vw = size.width();
265 double vh = size.height();
266 double xc = x - vw / 2; // target center pos'n ±from view center
267 double yc = vh / 2 - y; // ... in world coords on the viewing plane
268
269 // Target angles relative to the camera.
270 double azimuthCam = Math.atan2(xc * 2 * kTanHFOV2, vw);
271 double elevationCam = Math.atan2(yc * 2 * kTanVFOV2, vh);
272 double rangeIn = kTargetWidthIn * vw / (w * 2 * kTanHFOV2);
273
274 System.out.format("Best target at (%.2f, %.2f) %.2f x %.2f"
275 + ", shot azimuth=%.2f elevation=%.2f range=%.2f'%n",
276 x, y, w, h,
277 Math.toDegrees(azimuthCam) - kShooterOffsetDeg,
278 Math.toDegrees(elevationCam) + kCameraPitchDeg,
279 rangeIn / 12);
280 }
281
jerrym6ebe6452013-02-18 03:00:31 +0000282}