/
targets.cpp
399 lines (345 loc) · 13.4 KB
/
targets.cpp
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
/* Target Detector
*
* Detect a bull's-eye or a set of bulls-eyes in an input image
*
* Note: this is my first piece of opencv code. it will probably suck
*
* Author: Austin Hendrix
*/
#include <math.h>
#include <map>
#include <set>
#include <list>
#include <queue>
#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <sensor_msgs/Image.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <dynamic_reconfigure/server.h>
#include <target_detector/TargetDetectorConfig.h>
#include <target_detector/PointArray.h>
namespace enc = sensor_msgs::image_encodings;
class TargetsDetector {
ros::NodeHandle nh_;
image_transport::ImageTransport it_;
image_transport::Subscriber image_sub_;
image_transport::Publisher image_pub_;
image_transport::Publisher edges_pub_;
ros::Subscriber points_sub_;
ros::Publisher targets_pub_;
double t1;
double t2;
double allowed_error;
double center_threshold;
public:
TargetsDetector() : it_(nh_), t1(300.0), t2(150.0), allowed_error(10) {
image_sub_ = it_.subscribe("in", 1, &TargetsDetector::imageCb, this);
points_sub_ = nh_.subscribe("points2", 1, &TargetsDetector::cloudCb,
this);
image_pub_ = it_.advertise("out", 1);
edges_pub_ = it_.advertise("edges", 1);
targets_pub_ = nh_.advertise<target_detector::PointArray>("targets", 1);
}
// dynamic-reconfigure callback
void dyn_callback(target_detector::TargetDetectorConfig & config,
uint32_t level) {
// this probably isn't thread-safe and I DON'T CARE
// (it should only screw up one image in the worse case)
t1 = config.t1;
t2 = config.t2;
allowed_error = config.error;
center_threshold = config.center;
}
inline float dist(cv::Point a, cv::Point b) {
return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y));
}
class Ellipse {
public:
cv::Point center;
float error;
Ellipse(cv::Point c, float e) : center(c), error(e) {}
};
// average RMS error
float ellipseError(cv::RotatedRect rect, std::vector<cv::Point> &points){
cv::Point2f center = rect.center;
float a = rect.size.width / 2.0f;
float b = rect.size.height / 2.0f;
float angle = (90.0 + rect.angle) * M_PI / 180.0;
//ROS_ASSERT(a >= b);
float err = 0;
float theta_max = 0;
float d_max = 0;
for( std::vector<cv::Point>::iterator itr = points.begin();
itr != points.end(); ++itr ) {
float d = dist(center, *itr);
float t = atan2f(itr->y - center.y, itr->x - center.x);
if( d > d_max ) {
d_max = d;
theta_max = t;
}
float t2 = t - angle;
float r = a * b / sqrt( (a*cosf(t2)) * (a*cosf(t2)) +
(b*sinf(t2)) * (b*sinf(t2)) );
err += ((r-d)/r) * ((r-d)/r);
}
err /= points.size();
err = sqrt(err);
return err;
}
struct groups {
int * contours;
int end;
int count;
};
// Grouping algorithm by Michael LeKander <michaelll@michaelll.com>
groups extractContours(cv::Mat edges) {
int count = 0;
int i, o, endBound = edges.rows * edges.cols;
int * contours = (int*)malloc((sizeof(int)*endBound) + 2);
int *stack = contours, *queue = contours;
uchar * isWhite = edges.data;
int width = edges.cols;
for (i = 0; i < endBound; i++) {
if (isWhite[i]) {
*stack++ = i;
isWhite[i] = 0;
for (o = *queue; queue != stack; o = *++queue) {
// all surrounding points
for( int j=-1; j<=1; j++ ) {
for( int k=-1; k<=1; k++ ) {
int p = o + j + k*width;
if( p%width == o%width + j ) {
if( p >= 0 && p < endBound ) {
if( isWhite[p] ) {
*stack++ = p;
isWhite[p] = 0;
}
}
}
}
}
}
*stack++ = -1;
queue++;
count++;
}
}
*stack++ = -1;
groups g;
g.contours = contours;
g.end = endBound;
g.count = count;
return g;
}
void falseColorGroups(groups g, std_msgs::Header header, int h, int w) {
if( edges_pub_.getNumSubscribers() > 0 ) {
// generate colors
std::map<int, cv::Vec3b> colors;
srand(0);
for( int i=0; i<g.count+1; i++ ) {
int a = rand();
uchar r = a & 0xFF;
uchar g = (a >> 8) & 0xFF;
uchar b = (a >> 16) & 0xFF;
if( r < 20 ) r = 255 - r;
if( g < 20 ) g = 255 - g;
if( b < 20 ) b = 255 - b;
colors[i] = cv::Vec3b(r, g, b);
}
// publish edge image for viewing
cv_bridge::CvImage out;
// output grouped and colored edges
out.encoding = enc::BGR8;
out.header = header;
out.image.create(h, w, CV_8UC3);
out.image.setTo(0);
int color = 0;
for( int i = 0;
i < g.end && (g.contours[i] >= 0 || g.contours[i+1] >= 0);
i++ ) {
if( g.contours[i] >= 0 ) {
int j = g.contours[i] / w;
int k = g.contours[i] % w;
out.image.at<cv::Vec3b>(j, k) = colors[color];
} else {
color++;
}
}
edges_pub_.publish(out.toImageMsg());
}
}
// image callback
void imageCb(const sensor_msgs::ImageConstPtr & msg) {
try {
cv_bridge::CvImagePtr cv_ptr;
cv_ptr = cv_bridge::toCvCopy(msg, enc::MONO8);
std::list<cv::Point2f> centers = extractCenters(cv_ptr);
publishCrosshairs(msg, centers);
} catch(cv_bridge::Exception &e) {
ROS_ERROR("cv_Bridge exception: %s", e.what());
}
}
// point cloud callback
void cloudCb(const sensor_msgs::PointCloud2ConstPtr & cloud) {
if( (cloud->width * cloud->height) == 0 ) {
// not a dense cloud; return
return;
}
try {
sensor_msgs::ImagePtr image = boost::make_shared<sensor_msgs::Image>();
pcl::toROSMsg( *cloud, *image );
cv_bridge::CvImagePtr cv_ptr;
cv_ptr = cv_bridge::toCvCopy(image, enc::MONO8);
std::list<cv::Point2f> centers = extractCenters(cv_ptr);
// TODO: extract depth to points
pcl::PointCloud<pcl::PointXYZ> depth;
pcl::fromROSMsg( *cloud, depth);
// TODO: find appropriate output data type
// many PointStamped on one topic?
target_detector::PointArray targets;
for( std::list<cv::Point2f>::iterator itr = centers.begin();
itr != centers.end(); ++itr ) {
unsigned int x = itr->x;
unsigned int y = itr->y;
int dx[] = { 0, 1, 0, -1 };
int dy[] = { 1, 0, -1, 0 };
if( x >= depth.width ) x = depth.width-1;
if( x == depth.width - 1 ) dx[1] = 0;
if( y >= depth.height ) y = depth.height-1;
if( y == depth.height - 1) dy[0] = 0;
if( 0 == x ) dx[3] = 0;
if( 0 == y ) dy[2] = 0;
pcl::PointXYZ p1 = depth.at(x, y);
for( int i=0; isnan(p1.x) && i < 4; ++i ) {
p1 = depth.at(x + dx[i], y + dy[i]);
}
geometry_msgs::Point p2;
p2.x = p1.x; p2.y = p1.y; p2.z = p1.z;
ROS_INFO("Target point at (%lf, %lf, %lf)", p2.x, p2.y, p2.z);
if( ! isnan(p2.x) ) {
targets.points.push_back(p2);
}
}
targets_pub_.publish(targets);
publishCrosshairs(image, centers);
} catch( std::runtime_error e ) {
ROS_ERROR_STREAM("Error in converting point cloud to image: " << e.what());
}
}
std::list<cv::Point2f> extractCenters(cv_bridge::CvImagePtr cv_ptr) {
// detect edges in input image
cv::Mat edges;
cv::Canny(cv_ptr->image, edges, t1, t2);
// group points
groups g = extractContours(edges);
// fit ellipses
int width = edges.cols;
std::vector<cv::Point> points;
std::list<cv::RotatedRect> ellipses;
std::list<cv::Point2f> centers;
for( int i=0;
i < g.end && (g.contours[i] >= 0 || g.contours[i+1] >= 0);
i++ ) {
if( g.contours[i] >= 0 ) {
// another point. add it
int j = g.contours[i] / width;
int k = g.contours[i] % width;
points.push_back(cv::Point(k, j));
} else {
// fit ellipse; need at least 5 points
if( points.size() >= 5 ) {
cv::RotatedRect ellipse = cv::fitEllipse(cv::Mat(points));
float error = ellipseError(ellipse, points);
// TODO: determine quality of fit; either write custom
// fitting algorithm or measure fit.
// TODO: only consider ellipses that fit "well"
if( error < allowed_error ) {
ellipses.push_back(ellipse);
centers.push_back(ellipse.center);
}
}
points.clear();
}
}
printf("Fit %zd ellipses\n", ellipses.size());
// gather center points
typedef std::list<std::pair<cv::Point2f, std::list<cv::Point2f> > > cgType;
cgType center_groups;
for( std::list<cv::Point2f>::iterator itr = centers.begin();
itr != centers.end(); itr++ ) {
bool f = false;
for( cgType::iterator itr2 = center_groups.begin();
itr2 != center_groups.end() && !f; ++itr2 ) {
if( dist(*itr, itr2->first) < center_threshold ) {
itr2->second.push_back(*itr);
cv::Point2f avg;
for( std::list<cv::Point2f>::iterator itr3 = itr2->second.begin(); itr3 != itr2->second.end(); ++itr3 ) {
avg += *itr3;
}
avg.x /= itr2->second.size();
avg.y /= itr2->second.size();
itr2->first = avg;
f = true;
}
}
// if we didn't find a group for this point, make a new one
if( !f ) {
cv::Point2f avg = *itr;
std::list<cv::Point2f> l;
l.push_back(*itr);
center_groups.push_back(std::pair<cv::Point2f, std::list<cv::Point2f> >(avg, l));
}
}
centers.clear();
// threshold on number of circles required for target
for( cgType::iterator itr = center_groups.begin();
itr != center_groups.end(); ++itr ) {
if( itr->second.size() > 2 ) { // TODO: remove magic
printf("Found target at %f %f with %zd ellipses\n",
itr->first.x, itr->first.y, itr->second.size());
centers.push_back(itr->first);
}
}
falseColorGroups(g, cv_ptr->header, edges.rows, edges.cols);
free(g.contours);
return centers;
}
void publishCrosshairs( const sensor_msgs::ImageConstPtr & msg,
std::list<cv::Point2f> & centers) {
if( image_pub_.getNumSubscribers() > 0 ) {
// republish original image
cv_bridge::CvImagePtr out_ptr = cv_bridge::toCvCopy(msg, enc::BGR8);
// draw crosshairs at target centers
static int ll = 5; // half line-length of center cross
for( std::list<cv::Point2f>::iterator itr = centers.begin();
itr != centers.end(); ++itr ) {
cv::Point a1 = *itr;
cv::Point a2 = *itr;
cv::Point b1 = *itr;
cv::Point b2 = *itr;
a1.x -= ll;
a2.x += ll;
b1.y -= ll;
b2.y += ll;
cv::line(out_ptr->image, a1, a2, CV_RGB(0, 255, 0));
cv::line(out_ptr->image, b1, b2, CV_RGB(0, 255, 0));
}
image_pub_.publish(out_ptr->toImageMsg());
}
}
};
int main(int argc, char ** argv) {
ros::init(argc, argv, "targets");
TargetsDetector td;
dynamic_reconfigure::Server<target_detector::TargetDetectorConfig> server;
dynamic_reconfigure::Server<target_detector::TargetDetectorConfig>::CallbackType f;
f = boost::bind(&TargetsDetector::dyn_callback, &td, _1, _2);
server.setCallback(f);
ros::spin();
return 0;
}