blob: 7fbf28eb5b8d626aee240a7d029582ef0930b30b [file] [log] [blame]
jerrym6ebe6452013-02-18 03:00:31 +00001package org.frc971;
2
3import java.util.ArrayList;
danielp54e997e2013-02-21 01:54:23 +00004import java.util.logging.Logger;
jerrym6ebe6452013-02-18 03:00:31 +00005
6import com.googlecode.javacv.cpp.opencv_core;
7import com.googlecode.javacv.cpp.opencv_core.CvSize;
8import com.googlecode.javacv.cpp.opencv_core.IplImage;
9import com.googlecode.javacv.cpp.opencv_imgproc;
10import com.googlecode.javacv.cpp.opencv_imgproc.IplConvKernel;
11
12import edu.wpi.first.wpijavacv.DaisyExtensions;
13import edu.wpi.first.wpijavacv.WPIBinaryImage;
14import edu.wpi.first.wpijavacv.WPIColor;
15import edu.wpi.first.wpijavacv.WPIColorImage;
16import edu.wpi.first.wpijavacv.WPIContour;
17import edu.wpi.first.wpijavacv.WPIImage;
18import edu.wpi.first.wpijavacv.WPIPoint;
19import edu.wpi.first.wpijavacv.WPIPolygon;
20
21/**
22 * Vision target recognizer for FRC 2013.
23 *
jerrymf0c84552013-02-19 00:51:20 +000024 * @author jrussell
jerrym6ebe6452013-02-18 03:00:31 +000025 * @author jerry
26 */
27public class Recognizer2013 implements Recognizer {
danielp54e997e2013-02-21 01:54:23 +000028
29 private final static Logger LOG = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
jerrym6ebe6452013-02-18 03:00:31 +000030
jerrymf0c84552013-02-19 00:51:20 +000031 // --- Tunable recognizer constants.
jerrymcd2c3322013-02-18 08:49:01 +000032 static final double kRoughlyHorizontalSlope = Math.tan(Math.toRadians(30));
33 static final double kRoughlyVerticalSlope = Math.tan(Math.toRadians(90 - 30));
jerrymcd2c3322013-02-18 08:49:01 +000034 static final int kHoleClosingIterations = 2;
35 static final double kPolygonPercentFit = 12;
jerrymaa7a63b2013-02-18 06:31:22 +000036 static final int kMinWidthAt320 = 35; // for high goal and middle goals
37
jerrymf0c84552013-02-19 00:51:20 +000038 // --- Field dimensions.
39 // The target aspect ratios are for the midlines of the vision target tape.
40 static final double kGoalWidthIn = 54; // of the high and middle targets
41 static final double kTargetWidthIn = kGoalWidthIn + 4;
42 static final double kHighGoalAspect = (21 + 4) / kTargetWidthIn;
43 static final double kMiddleGoalAspect = (24 + 4) / kTargetWidthIn;
jerrymaa7a63b2013-02-18 06:31:22 +000044 static final double kMinAspect = kHighGoalAspect * 0.6;
45 static final double kMaxAspect = kMiddleGoalAspect * 1.4;
jerrymf0c84552013-02-19 00:51:20 +000046 static final double kTopTargetHeightIn = 104.125 + 21.0/2; // center of target
jerrym6ebe6452013-02-18 03:00:31 +000047
jerrymf0c84552013-02-19 00:51:20 +000048 // --- Robot and camera dimensions.
49 static final double kShooterOffsetDeg = 0; // azimuth offset from camera to shooter
50 static final double kHorizontalFOVDeg = 44.0; // Logitech C210 camera
jerrym6ebe6452013-02-18 03:00:31 +000051 static final double kVerticalFOVDeg = 480.0 / 640.0 * kHorizontalFOVDeg;
jerrymf0c84552013-02-19 00:51:20 +000052 static final double kCameraHeightIn = 24.0; // TODO
53 static final double kCameraPitchDeg = 21.0; // TODO
54 static final double kTanHFOV2 = Math.tan(Math.toRadians(kHorizontalFOVDeg / 2));
55 static final double kTanVFOV2 = Math.tan(Math.toRadians(kVerticalFOVDeg / 2));
jerrym6ebe6452013-02-18 03:00:31 +000056
jerrymaa7a63b2013-02-18 06:31:22 +000057 // --- Colors for drawing indicators on the image.
jerrym6ebe6452013-02-18 03:00:31 +000058 private static final WPIColor reject1Color = WPIColor.GRAY;
59 private static final WPIColor reject2Color = WPIColor.YELLOW;
60 private static final WPIColor candidateColor = WPIColor.BLUE;
jerrymf0c84552013-02-19 00:51:20 +000061 private static final WPIColor targetColor = WPIColor.RED;
jerrym6ebe6452013-02-18 03:00:31 +000062
jerrymf0c84552013-02-19 00:51:20 +000063 // --- Color thresholds, initialized in the constructor.
jerrymcd2469c2013-02-18 20:15:28 +000064 private int min1Hue, max1Hue, min1Sat, min1Val;
65
jerrym6ebe6452013-02-18 03:00:31 +000066 // Show intermediate images for parameter tuning.
67 private final DebugCanvas thresholdedCanvas = new DebugCanvas("thresholded");
68 private final DebugCanvas morphedCanvas = new DebugCanvas("morphed");
69
jerrymaa7a63b2013-02-18 06:31:22 +000070 // Data to reuse for each frame.
jerrym6ebe6452013-02-18 03:00:31 +000071 private final DaisyExtensions daisyExtensions = new DaisyExtensions();
72 private final IplConvKernel morphKernel = IplConvKernel.create(3, 3, 1, 1,
jerrymdda60132013-02-18 09:25:03 +000073 opencv_imgproc.CV_SHAPE_RECT, null);
jerrym6ebe6452013-02-18 03:00:31 +000074 private final ArrayList<WPIPolygon> polygons = new ArrayList<WPIPolygon>();
jerrymaa7a63b2013-02-18 06:31:22 +000075
76 // Frame-size-dependent data to reuse for each frame.
77 private CvSize size = null;
jerrym6ebe6452013-02-18 03:00:31 +000078 private WPIColorImage rawImage;
79 private IplImage bin;
80 private IplImage hsv;
81 private IplImage hue;
82 private IplImage sat;
83 private IplImage val;
jerrymaa7a63b2013-02-18 06:31:22 +000084 private int minWidth;
jerrym6ebe6452013-02-18 03:00:31 +000085 private WPIPoint linePt1, linePt2; // crosshair endpoints
86
87 public Recognizer2013() {
jerrymdda60132013-02-18 09:25:03 +000088 setHSVRange(70, 106, 137, 27);
jerrym6ebe6452013-02-18 03:00:31 +000089 }
90
91 @Override
jerrymcd2c3322013-02-18 08:49:01 +000092 public void setHSVRange(int minHue, int maxHue, int minSat, int minVal) {
jerrymdda60132013-02-18 09:25:03 +000093 min1Hue = minHue - 1; // - 1 because cvThreshold() does > instead of >=
94 max1Hue = maxHue + 1;
95 min1Sat = minSat - 1;
96 min1Val = minVal - 1;
jerrymcd2c3322013-02-18 08:49:01 +000097 }
98 @Override
99 public int getHueMin() { return min1Hue + 1; }
100 @Override
101 public int getHueMax() { return max1Hue - 1; }
102 @Override
jerrymcd2469c2013-02-18 20:15:28 +0000103 public int getSatMin() { return min1Sat + 1; }
jerrymcd2c3322013-02-18 08:49:01 +0000104 @Override
jerrymcd2469c2013-02-18 20:15:28 +0000105 public int getValMin() { return min1Val + 1; }
jerrymcd2c3322013-02-18 08:49:01 +0000106
107 @Override
jerrymf96c32c2013-02-18 19:30:45 +0000108 public void showIntermediateStages(boolean enable) {
109 thresholdedCanvas.show = enable;
110 morphedCanvas.show = enable;
111 }
112
113 @Override
jerrym6ebe6452013-02-18 03:00:31 +0000114 public WPIImage processImage(WPIColorImage cameraImage) {
jerrymdda60132013-02-18 09:25:03 +0000115 // (Re)allocate the intermediate images if the input is a different
116 // size than the previous image.
jerrym6ebe6452013-02-18 03:00:31 +0000117 if (size == null || size.width() != cameraImage.getWidth()
jerrymdda60132013-02-18 09:25:03 +0000118 || size.height() != cameraImage.getHeight()) {
jerrym6ebe6452013-02-18 03:00:31 +0000119 size = opencv_core.cvSize(cameraImage.getWidth(),
jerrymdda60132013-02-18 09:25:03 +0000120 cameraImage.getHeight());
jerrym6ebe6452013-02-18 03:00:31 +0000121 rawImage = DaisyExtensions.makeWPIColorImage(
jerrymdda60132013-02-18 09:25:03 +0000122 DaisyExtensions.getIplImage(cameraImage));
jerrym6ebe6452013-02-18 03:00:31 +0000123 bin = IplImage.create(size, 8, 1);
124 hsv = IplImage.create(size, 8, 3);
125 hue = IplImage.create(size, 8, 1);
126 sat = IplImage.create(size, 8, 1);
127 val = IplImage.create(size, 8, 1);
jerrymaa7a63b2013-02-18 06:31:22 +0000128 minWidth = (kMinWidthAt320 * cameraImage.getWidth() + 319) / 320;
jerrym6ebe6452013-02-18 03:00:31 +0000129
130 int horizontalOffsetPixels = (int)Math.round(
jerrymdda60132013-02-18 09:25:03 +0000131 kShooterOffsetDeg * size.width() / kHorizontalFOVDeg);
jerrym6ebe6452013-02-18 03:00:31 +0000132 int x = size.width() / 2 + horizontalOffsetPixels;
133 linePt1 = new WPIPoint(x, size.height() - 1);
134 linePt2 = new WPIPoint(x, 0);
135 } else {
jerrymaa7a63b2013-02-18 06:31:22 +0000136 // Copy the camera image so it's safe to draw on.
jerrym6ebe6452013-02-18 03:00:31 +0000137 opencv_core.cvCopy(DaisyExtensions.getIplImage(cameraImage),
jerrymdda60132013-02-18 09:25:03 +0000138 DaisyExtensions.getIplImage(rawImage));
jerrym6ebe6452013-02-18 03:00:31 +0000139 }
140
141 IplImage input = DaisyExtensions.getIplImage(rawImage);
142
143 // Threshold the pixels in HSV color space.
144 // TODO(jerry): Do this in one pass of a pixel-processing loop.
jerrymaa7a63b2013-02-18 06:31:22 +0000145 opencv_imgproc.cvCvtColor(input, hsv, opencv_imgproc.CV_BGR2HSV_FULL);
jerrym6ebe6452013-02-18 03:00:31 +0000146 opencv_core.cvSplit(hsv, hue, sat, val, null);
147
148 // NOTE: Since red is at the end of the cyclic color space, you can OR
149 // a threshold and an inverted threshold to match red pixels.
jerrymcd2c3322013-02-18 08:49:01 +0000150 opencv_imgproc.cvThreshold(hue, bin, min1Hue, 255, opencv_imgproc.CV_THRESH_BINARY);
151 opencv_imgproc.cvThreshold(hue, hue, max1Hue, 255, opencv_imgproc.CV_THRESH_BINARY_INV);
152 opencv_imgproc.cvThreshold(sat, sat, min1Sat, 255, opencv_imgproc.CV_THRESH_BINARY);
153 opencv_imgproc.cvThreshold(val, val, min1Val, 255, opencv_imgproc.CV_THRESH_BINARY);
jerrym6ebe6452013-02-18 03:00:31 +0000154
155 // Combine the results to obtain a binary image which is mostly the
156 // interesting pixels.
157 opencv_core.cvAnd(hue, bin, bin, null);
158 opencv_core.cvAnd(bin, sat, bin, null);
159 opencv_core.cvAnd(bin, val, bin, null);
160
161 thresholdedCanvas.showImage(bin);
162
163 // Fill in gaps using binary morphology.
164 opencv_imgproc.cvMorphologyEx(bin, bin, null, morphKernel,
jerrymdda60132013-02-18 09:25:03 +0000165 opencv_imgproc.CV_MOP_CLOSE, kHoleClosingIterations);
jerrym6ebe6452013-02-18 03:00:31 +0000166
167 morphedCanvas.showImage(bin);
168
169 // Find contours.
jerrymf0c84552013-02-19 00:51:20 +0000170 //
171 // NOTE: If we distinguished between the inner and outer boundaries of
172 // the vision target rectangles, we could apply a more accurate width
173 // filter and more accurately compute the target range.
jerrym6ebe6452013-02-18 03:00:31 +0000174 WPIBinaryImage binWpi = DaisyExtensions.makeWPIBinaryImage(bin);
jerrymaa7a63b2013-02-18 06:31:22 +0000175 WPIContour[] contours = daisyExtensions.findConvexContours(binWpi);
jerrym6ebe6452013-02-18 03:00:31 +0000176
jerrymaa7a63b2013-02-18 06:31:22 +0000177 // Simplify the contours to polygons and filter by size and aspect ratio.
178 //
179 // TODO(jerry): Also look for the two vertical stripe vision targets.
180 // They'll greatly increase the precision of measuring the distance. If
181 // both stripes are visible, they'll increase the accuracy for
182 // identifying the high goal.
jerrym6ebe6452013-02-18 03:00:31 +0000183 polygons.clear();
184 for (WPIContour c : contours) {
jerrymaa7a63b2013-02-18 06:31:22 +0000185 if (c.getWidth() >= minWidth) {
jerrymdda60132013-02-18 09:25:03 +0000186 double ratio = ((double) c.getHeight()) / c.getWidth();
187 if (ratio >= kMinAspect && ratio <= kMaxAspect) {
188 polygons.add(c.approxPolygon(kPolygonPercentFit));
189 // System.out.println(" Accepted aspect ratio " + ratio);
190 } else {
191 // System.out.println(" Rejected aspect ratio " + ratio);
192 }
jerrym6ebe6452013-02-18 03:00:31 +0000193 }
194 }
195
jerrymaa7a63b2013-02-18 06:31:22 +0000196 // Pick the target with the highest center-point that matches yet more
197 // filter criteria.
jerrym6ebe6452013-02-18 03:00:31 +0000198 WPIPolygon bestTarget = null;
199 int highestY = Integer.MAX_VALUE;
200
201 for (WPIPolygon p : polygons) {
jerrymaa7a63b2013-02-18 06:31:22 +0000202 // TODO(jerry): Replace boolean filters with a scoring function?
jerrym6ebe6452013-02-18 03:00:31 +0000203 if (p.isConvex() && p.getNumVertices() == 4) { // quadrilateral
204 WPIPoint[] points = p.getPoints();
jerrymaa7a63b2013-02-18 06:31:22 +0000205 // Filter for polygons with 2 ~horizontal and 2 ~vertical sides.
jerrym6ebe6452013-02-18 03:00:31 +0000206 int numRoughlyHorizontal = 0;
207 int numRoughlyVertical = 0;
208 for (int i = 0; i < 4; ++i) {
209 double dy = points[i].getY() - points[(i + 1) % 4].getY();
210 double dx = points[i].getX() - points[(i + 1) % 4].getX();
211 double slope = Double.MAX_VALUE;
212 if (dx != 0) {
213 slope = Math.abs(dy / dx);
214 }
215
216 if (slope < kRoughlyHorizontalSlope) {
217 ++numRoughlyHorizontal;
218 } else if (slope > kRoughlyVerticalSlope) {
219 ++numRoughlyVertical;
220 }
221 }
222
jerrymaa7a63b2013-02-18 06:31:22 +0000223 if (numRoughlyHorizontal >= 2 && numRoughlyVertical == 2) {
jerrym6ebe6452013-02-18 03:00:31 +0000224 int pCenterX = p.getX() + p.getWidth() / 2;
225 int pCenterY = p.getY() + p.getHeight() / 2;
226
jerrymf0c84552013-02-19 00:51:20 +0000227 rawImage.drawPolygon(p, candidateColor, 2);
jerrym6ebe6452013-02-18 03:00:31 +0000228 rawImage.drawPoint(new WPIPoint(pCenterX, pCenterY),
jerrymdda60132013-02-18 09:25:03 +0000229 targetColor, 2);
jerrym6ebe6452013-02-18 03:00:31 +0000230 if (pCenterY < highestY) {
231 bestTarget = p;
232 highestY = pCenterY;
233 }
234 } else {
235 rawImage.drawPolygon(p, reject2Color, 1);
236 }
237 } else {
238 rawImage.drawPolygon(p, reject1Color, 1);
239 }
240 }
241
242 if (bestTarget != null) {
jerrym6ebe6452013-02-18 03:00:31 +0000243 rawImage.drawPolygon(bestTarget, targetColor, 2);
jerrymf0c84552013-02-19 00:51:20 +0000244 measureTarget(bestTarget);
jerrym6ebe6452013-02-18 03:00:31 +0000245 } else {
danielp54e997e2013-02-21 01:54:23 +0000246 LOG.fine("No target found");
jerrym6ebe6452013-02-18 03:00:31 +0000247 }
248
249 // Draw a crosshair
250 rawImage.drawLine(linePt1, linePt2, targetColor, 1);
251
252 daisyExtensions.releaseMemory();
253 //System.gc();
254
255 return rawImage;
256 }
257
jerrymf0c84552013-02-19 00:51:20 +0000258 /**
259 * Uses the camera, field, and robot dimensions to compute targeting info.
260 */
261 private void measureTarget(WPIPolygon target) {
262 double w = target.getWidth();
263 double h = target.getHeight();
264 double x = target.getX() + w / 2; // target center in view coords
265 double y = target.getY() + h / 2;
266
267 double vw = size.width();
268 double vh = size.height();
269 double xc = x - vw / 2; // target center pos'n ±from view center
270 double yc = vh / 2 - y; // ... in world coords on the viewing plane
271
272 // Target angles relative to the camera.
273 double azimuthCam = Math.atan2(xc * 2 * kTanHFOV2, vw);
274 double elevationCam = Math.atan2(yc * 2 * kTanVFOV2, vh);
275 double rangeIn = kTargetWidthIn * vw / (w * 2 * kTanHFOV2);
276
danielp54e997e2013-02-21 01:54:23 +0000277 LOG.fine("Best target at (" + x + ", " + y + ") " + w +" x " + h
278 + ", shot azimuth=" + (Math.toDegrees(azimuthCam) - kShooterOffsetDeg) +
279 " elevation=" + (Math.toDegrees(elevationCam) + kCameraPitchDeg) +
280 " range=" + (rangeIn / 12));
jerrymf0c84552013-02-19 00:51:20 +0000281 }
282
jerrym6ebe6452013-02-18 03:00:31 +0000283}