| 1 | #include <algorithm> |
| 2 | #include <cassert> |
| 3 | #include <fstream> |
| 4 | #include <iostream> |
| 5 | #include <random> |
| 6 | #include <sstream> |
| 7 | |
| 8 | #include <TooN/Cholesky.h> |
| 9 | #include <TooN/helpers.h> |
| 10 | #include <TooN/se3.h> |
| 11 | |
| 12 | #include <cvd/camera.h> |
| 13 | #include <cvd/colourspace_convert.h> |
| 14 | #include <cvd/colourspacebuffer.h> |
| 15 | #include <cvd/colourspaces.h> |
| 16 | #include <cvd/convolution.h> |
| 17 | #include <cvd/gl_helpers.h> |
| 18 | #include <cvd/glwindow.h> |
| 19 | #include <cvd/image_interpolate.h> |
| 20 | #include <cvd/image_io.h> |
| 21 | #include <cvd/timer.h> |
| 22 | #include <cvd/videosource.h> |
| 23 | #include <cvd/vision.h> |
| 24 | |
| 25 | using std::cerr; |
| 26 | using std::clog; |
| 27 | using std::cout; |
| 28 | using std::endl; |
| 29 | using std::istringstream; |
| 30 | using std::make_pair; |
| 31 | using std::mt19937; |
| 32 | using std::normal_distribution; |
| 33 | using std::ofstream; |
| 34 | using std::pair; |
| 35 | using std::string; |
| 36 | using std::vector; |
| 37 | using namespace TooN; |
| 38 | using namespace CVD; |
| 39 | |
| 40 | #include <X11/Xlib.h> |
| 41 | #include <X11/keysym.h> |
| 42 | |
| 43 | typedef byte CAMERA_PIXEL; |
| 44 | VideoBuffer<CAMERA_PIXEL>* videoBuffer = 0; |
| 45 | |
| 46 | // global configuration variables, can be set via command line options |
| 47 | #ifdef CVD_HAVE_QTBUFFER |
| 48 | string videoDevice = "colourspace:[from=yuv422]//qt://0"; |
| 49 | #else |
| 50 | string videoDevice = "v4l2:///dev/video0"; |
| 51 | #endif |
| 52 | |
| 53 | typedef Camera::OldCameraAdapter<Camera::Harris> CameraModel; |
| 54 | static const int NumCameraParams = CameraModel::num_parameters; |
| 55 | |
| 56 | Vector<NumCameraParams> badVector() |
| 57 | { |
| 58 | Vector<NumCameraParams> v; |
| 59 | for(int i = 0; i < NumCameraParams; i++) |
| 60 | v[i] = -1; |
| 61 | |
| 62 | return v; |
| 63 | } |
| 64 | |
| 65 | Vector<NumCameraParams> cameraParameters = badVector(); |
| 66 | int bottomLeftWhite = 1; |
| 67 | int gridx = 11; |
| 68 | int gridy = 7; |
| 69 | double cellSize = 0.02; |
| 70 | double interval = 0.5; |
| 71 | int generateErrorImage = 0; |
| 72 | string output; |
| 73 | |
| 74 | void drawGrid(vector<Vector<2>> grid, int cols, int rows) |
| 75 | { |
| 76 | glBegin(GL_LINES); |
| 77 | for(unsigned int i = 0; i < grid.size(); i++) |
| 78 | { |
| 79 | if(((i + 1) % (cols + 1))) |
| 80 | { |
| 81 | //Not last column, draw a horiz line |
| 82 | glVertex(grid[i]); |
| 83 | glVertex(grid[i + 1]); |
| 84 | } |
| 85 | |
| 86 | if(i < (unsigned int)rows * (cols + 1)) |
| 87 | { |
| 88 | //Not top row, draw a vert line |
| 89 | glVertex(grid[i]); |
| 90 | glVertex(grid[i + cols + 1]); |
| 91 | } |
| 92 | } |
| 93 | glEnd(); |
| 94 | } |
| 95 | |
| 96 | void drawCross(Vector<2> pos, double size) |
| 97 | { |
| 98 | glBegin(GL_LINES); |
| 99 | glVertex2f(pos[0] - size / 2, pos[1]); |
| 100 | glVertex2f(pos[0] + size / 2, pos[1]); |
| 101 | glVertex2f(pos[0], pos[1] - size / 2); |
| 102 | glVertex2f(pos[0], pos[1] + size / 2); |
| 103 | glEnd(); |
| 104 | } |
| 105 | |
| 106 | void drawCross(ImageRef pos, int size) |
| 107 | { |
| 108 | glBegin(GL_LINES); |
| 109 | glVertex2i(pos.x - size / 2, pos.y); |
| 110 | glVertex2i(pos.x + size / 2, pos.y); |
| 111 | glVertex2i(pos.x, pos.y - size / 2); |
| 112 | glVertex2i(pos.x, pos.y + size / 2); |
| 113 | glEnd(); |
| 114 | } |
| 115 | |
| 116 | template <typename B> |
| 117 | Matrix<2> inverse(const Matrix<2, 2, double, B>& A) |
| 118 | { |
| 119 | Matrix<2> result; |
| 120 | const double idet = 1 / (A(0, 0) * A(1, 1) - A(0, 1) * A(1, 0)); |
| 121 | result(0, 0) = A(1, 1); |
| 122 | result(1, 0) = -A(0, 1); |
| 123 | result(0, 1) = -A(1, 0); |
| 124 | result(1, 1) = A(0, 0); |
| 125 | result *= idet; |
| 126 | return result; |
| 127 | } |
| 128 | |
| 129 | template <class A1, class A2, class A3> |
| 130 | inline Vector<2> project_transformed_point(const SE3<>& pose, const Vector<3, double, A1>& in_frame, Matrix<2, 3, double, A2>& J_x, Matrix<2, 6, double, A3>& J_pose) |
| 131 | { |
| 132 | const double z_inv = 1.0 / in_frame[2]; |
| 133 | const double x_z_inv = in_frame[0] * z_inv; |
| 134 | const double y_z_inv = in_frame[1] * z_inv; |
| 135 | const double cross = x_z_inv * y_z_inv; |
| 136 | J_pose[0][0] = J_pose[1][1] = z_inv; |
| 137 | J_pose[0][1] = J_pose[1][0] = 0; |
| 138 | J_pose[0][2] = -x_z_inv * z_inv; |
| 139 | J_pose[1][2] = -y_z_inv * z_inv; |
| 140 | J_pose[0][3] = -cross; |
| 141 | J_pose[0][4] = 1 + x_z_inv * x_z_inv; |
| 142 | J_pose[0][5] = -y_z_inv; |
| 143 | J_pose[1][3] = -1 - y_z_inv * y_z_inv; |
| 144 | J_pose[1][4] = cross; |
| 145 | J_pose[1][5] = x_z_inv; |
| 146 | |
| 147 | const TooN::Matrix<3>& R = pose.get_rotation().get_matrix(); |
| 148 | J_x[0][0] = z_inv * (R[0][0] - x_z_inv * R[2][0]); |
| 149 | J_x[0][1] = z_inv * (R[0][1] - x_z_inv * R[2][1]); |
| 150 | J_x[0][2] = z_inv * (R[0][2] - x_z_inv * R[2][2]); |
| 151 | J_x[1][0] = z_inv * (R[1][0] - y_z_inv * R[2][0]); |
| 152 | J_x[1][1] = z_inv * (R[1][1] - y_z_inv * R[2][1]); |
| 153 | J_x[1][2] = z_inv * (R[1][2] - y_z_inv * R[2][2]); |
| 154 | |
| 155 | return makeVector(x_z_inv, y_z_inv); |
| 156 | } |
| 157 | |
| 158 | template <class A1> |
| 159 | inline Vector<2> transform_and_project(const SE3<>& pose, const Vector<3, double, A1>& x) |
| 160 | { |
| 161 | return project(pose * x); |
| 162 | } |
| 163 | |
| 164 | template <class A1, class A2, class A3> |
| 165 | inline Vector<2> transform_and_project(const SE3<>& pose, const Vector<3, double, A1>& x, Matrix<2, 3, double, A2>& J_x, Matrix<2, 6, double, A3>& J_pose) |
| 166 | { |
| 167 | return project_transformed_point(pose, pose * x, J_x, J_pose); |
| 168 | } |
| 169 | |
| 170 | template <class CamModel, class P> |
| 171 | SE3<> find_pose(const SE3<>& start, const vector<Vector<3>>& x, const vector<pair<size_t, P>>& p, CamModel& camModel, double noise) |
| 172 | { |
| 173 | vector<pair<Vector<2>, Matrix<2>>> unprojected(p.size()); |
| 174 | |
| 175 | for(size_t i = 0; i < p.size(); ++i) |
| 176 | { |
| 177 | unprojected[i].first = camModel.unproject(p[i].second); |
| 178 | Matrix<2> Jinv = inverse(camModel.get_derivative()); |
| 179 | unprojected[i].second = Jinv * (noise * Jinv.T()); |
| 180 | } |
| 181 | |
| 182 | SE3<> bestSE3; |
| 183 | double bestError = numeric_limits<double>::max(); |
| 184 | vector<Vector<2>> up(p.size()); |
| 185 | for(size_t i = 0; i < p.size(); i++) |
| 186 | up[i] = camModel.unproject(p[i].second); |
| 187 | SE3<> se3; |
| 188 | se3 = start; |
| 189 | |
| 190 | for(int iter = 0; iter < 4; ++iter) |
| 191 | { |
| 192 | Matrix<6> I = Zeros; |
| 193 | Vector<6> b = Zeros; |
| 194 | for(size_t i = 0; i < p.size(); ++i) |
| 195 | { |
| 196 | Matrix<2, 3> J_x; |
| 197 | Matrix<2, 6> J_pose; |
| 198 | Vector<2> v = unprojected[i].first - transform_and_project(se3, x[p[i].first], J_x, J_pose); |
| 199 | const Matrix<2> Rinv = inverse(unprojected[i].second); |
| 200 | I += J_pose.T() * Rinv * J_pose; |
| 201 | //transformCovariance<util::PlusEquals>(J_pose.T(), Rinv, I); |
| 202 | b += J_pose.T() * (Rinv * v); |
| 203 | } |
| 204 | Cholesky<6> chol(I); |
| 205 | se3.left_multiply_by(SE3<>::exp(chol.backsub(b))); |
| 206 | |
| 207 | double residual = 0; |
| 208 | for(size_t i = 0; i < p.size(); ++i) |
| 209 | { |
| 210 | Vector<2> v = unprojected[i].first - transform_and_project(se3, x[p[i].first]); |
| 211 | const Matrix<2> Rinv = inverse(unprojected[i].second); |
| 212 | residual += v * (Rinv * v); |
| 213 | } |
| 214 | if(residual < bestError) |
| 215 | { |
| 216 | bestError = residual; |
| 217 | bestSE3 = se3; |
| 218 | } |
| 219 | } |
| 220 | return bestSE3; |
| 221 | } |
| 222 | |
| 223 | template <class CamModel, class P> |
| 224 | SE3<> find_pose_and_params(const SE3<>& start, const vector<Vector<3>>& x, const vector<pair<size_t, P>>& p, CamModel& camModel, double noise) |
| 225 | { |
| 226 | static const int NCP = CamModel::num_parameters; |
| 227 | static const int NP = NCP + 6; |
| 228 | //const Matrix<2> Rinv = Identity<2>(1.0/noise); |
| 229 | Matrix<2> Rinv = Identity; |
| 230 | Rinv /= noise; |
| 231 | SE3<> best_pose = start; |
| 232 | Vector<NCP> best_params = camModel.get_parameters(); |
| 233 | SE3<> pose = start; |
| 234 | |
| 235 | double residual = 0; |
| 236 | for(size_t i = 0; i < p.size(); ++i) |
| 237 | { |
| 238 | Vector<2> v = p[i].second - camModel.project(transform_and_project(pose, x[p[i].first])); |
| 239 | residual += v * Rinv * v; |
| 240 | } |
| 241 | double best_residual = residual; |
| 242 | |
| 243 | double lambda = 1.0; |
| 244 | for(int iter = 0; iter < 10; ++iter) |
| 245 | { |
| 246 | Matrix<NP> I = Identity; |
| 247 | I *= lambda; |
| 248 | Vector<NP> b = Zeros; |
| 249 | for(size_t i = 0; i < p.size(); ++i) |
| 250 | { |
| 251 | Matrix<2, 3> J_x; |
| 252 | Matrix<2, 6> J_pose; |
| 253 | Vector<2> v = p[i].second - camModel.project(transform_and_project(pose, x[p[i].first], J_x, J_pose)); |
| 254 | Matrix<2, NP> J; |
| 255 | J.template slice<0, 0, 2, NCP>() = camModel.get_parameter_derivs().T(); |
| 256 | J.template slice<0, NCP, 2, 6>() = camModel.get_derivative() * J_pose; |
| 257 | |
| 258 | I += J.T() * Rinv * J; |
| 259 | // transformCovariance<util::PlusEquals>(J.T(), Rinv, I); |
| 260 | b += J.T() * (Rinv * v); |
| 261 | } |
| 262 | Cholesky<NP> chol(I); |
| 263 | Vector<NP> delta = chol.backsub(b); |
| 264 | camModel.get_parameters() += delta.template slice<0, NCP>(); |
| 265 | pose.left_multiply_by(SE3<>::exp(delta.template slice<NCP, 6>())); |
| 266 | |
| 267 | double residual = 0; |
| 268 | for(size_t i = 0; i < p.size(); ++i) |
| 269 | { |
| 270 | Vector<2> v = p[i].second - camModel.project(transform_and_project(pose, x[p[i].first])); |
| 271 | residual += v * Rinv * v; |
| 272 | } |
| 273 | if(residual < best_residual) |
| 274 | { |
| 275 | best_residual = residual; |
| 276 | best_pose = pose; |
| 277 | best_params = camModel.get_parameters(); |
| 278 | lambda *= 0.5; |
| 279 | } |
| 280 | else |
| 281 | { |
| 282 | pose = best_pose; |
| 283 | camModel.get_parameters() = best_params; |
| 284 | lambda *= 1e2; |
| 285 | } |
| 286 | } |
| 287 | camModel.get_parameters() = best_params; |
| 288 | return best_pose; |
| 289 | } |
| 290 | |
| 291 | void getOptions(int argc, char* argv[]) |
| 292 | { |
| 293 | for(int i = 1; i < argc; i++) |
| 294 | { |
| 295 | string arg = argv[i]; |
| 296 | if(arg == "-o") |
| 297 | { |
| 298 | output = argv[++i]; |
| 299 | } |
| 300 | else if(arg == "-d") |
| 301 | { |
| 302 | videoDevice = argv[++i]; |
| 303 | } |
| 304 | else if(arg == "-x") |
| 305 | { |
| 306 | gridx = atoi(argv[++i]); |
| 307 | } |
| 308 | else if(arg == "-y") |
| 309 | { |
| 310 | gridy = atoi(argv[++i]); |
| 311 | } |
| 312 | else if(arg == "-s") |
| 313 | { |
| 314 | cellSize = atof(argv[++i]); |
| 315 | } |
| 316 | else if(arg == "-t") |
| 317 | { |
| 318 | interval = atof(argv[++i]); |
| 319 | } |
| 320 | else if(arg == "-c") |
| 321 | { |
| 322 | istringstream sin(argv[++i]); |
| 323 | sin >> cameraParameters; |
| 324 | } |
| 325 | else if(arg == "-e") |
| 326 | { |
| 327 | generateErrorImage = 1; |
| 328 | } |
| 329 | else |
| 330 | { |
| 331 | cerr << argv[0] << " [options]\n\n" |
| 332 | "Move virtual grid over real grid until it snaps on.\n" |
| 333 | "Record a number of frames ~100.\n" |
| 334 | "Press SPACE to calculate camera parameters.\n\n" |
| 335 | "A calibration grid for the default parameters is in libcvd/doc/cameracalib2cm.pdf\n\n" |
| 336 | "flag description\t\t\t\tdefault\n" |
| 337 | " -d device to open, CVD video source URL\tv4l2:///dev/video0\n" |
| 338 | " -x grid dimension in x (width) direction\t11\n" |
| 339 | " -y grid dimension in y (height) direction\t7\n" |
| 340 | " -s grid cell size\t\t\t\t0.02 m\n" |
| 341 | " -t interval between captured frames\t\t0.5 s\n" |
| 342 | " -c initial camera parameters\t\t\t" |
| 343 | << cameraParameters << "\n" |
| 344 | " -e generate image showing errors per pixel\n"; |
| 345 | exit(0); |
| 346 | } |
| 347 | } |
| 348 | try |
| 349 | { |
| 350 | cerr << "opening " << videoDevice << endl; |
| 351 | videoBuffer = open_video_source<CAMERA_PIXEL>(videoDevice); |
| 352 | } |
| 353 | catch(CVD::Exceptions::All& e) |
| 354 | { |
| 355 | cerr << e.what() << endl; |
| 356 | exit(1); |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | vector<Vector<2>> makeGrid(int gx, int gy, double cellSize) |
| 361 | { |
| 362 | vector<Vector<2>> grid; |
| 363 | Vector<2> center = makeVector(gx, gy); |
| 364 | center *= cellSize / 2.0; |
| 365 | for(int y = 0; y <= gy; y++) |
| 366 | { |
| 367 | for(int x = 0; x <= gx; x++) |
| 368 | { |
| 369 | grid.push_back(Vector<2>(makeVector(x, y)) * cellSize - center); |
| 370 | } |
| 371 | } |
| 372 | return grid; |
| 373 | } |
| 374 | |
| 375 | template <class CM> |
| 376 | void drawPoints(const vector<Vector<2>>& points, const SE3<>& pose, CM& cm) |
| 377 | { |
| 378 | glColor3f(0, 1, 0); |
| 379 | for(size_t i = 0; i < points.size(); i++) |
| 380 | { |
| 381 | Vector<3> x = unproject(points[i]); |
| 382 | Vector<2> plane = project(pose * x); |
| 383 | Vector<2> im = cm.project(plane); |
| 384 | drawCross(im, 6); |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | struct MeasurementSet |
| 389 | { |
| 390 | vector<Vector<2>> im; |
| 391 | vector<Vector<3>> world; |
| 392 | }; |
| 393 | |
| 394 | template <class CM> |
| 395 | double getReprojectionError(const vector<MeasurementSet>& ms, const vector<SE3<>>& poses, CM& cm) |
| 396 | { |
| 397 | double error = 0; |
| 398 | for(size_t i = 0; i < ms.size(); i++) |
| 399 | { |
| 400 | for(size_t j = 0; j < ms[i].im.size(); j++) |
| 401 | { |
| 402 | Vector<3> camFrame = poses[i] * ms[i].world[j]; |
| 403 | Vector<2> im = cm.project(project(camFrame)); |
| 404 | Vector<2> v = ms[i].im[j] - im; |
| 405 | error += v * v; |
| 406 | } |
| 407 | } |
| 408 | return error; |
| 409 | } |
| 410 | |
| 411 | template <class CM> |
| 412 | pair<double, double> getReprojectionError(const vector<MeasurementSet>& ms, const vector<SE3<>>& poses, CM& cm, |
| 413 | vector<pair<Vector<2>, Vector<2>>>& v) |
| 414 | { |
| 415 | double error = 0, maxError = 0; |
| 416 | for(size_t i = 0; i < ms.size(); i++) |
| 417 | { |
| 418 | for(size_t j = 0; j < ms[i].im.size(); j++) |
| 419 | { |
| 420 | Vector<3> camFrame = poses[i] * ms[i].world[j]; |
| 421 | Vector<2> im = cm.project(project(camFrame)); |
| 422 | Vector<2> err = ms[i].im[j] - im; |
| 423 | v.push_back(make_pair(im, err)); |
| 424 | double thisError = err * err; |
| 425 | maxError = std::max(maxError, thisError); |
| 426 | error += thisError; |
| 427 | } |
| 428 | } |
| 429 | return make_pair(error, maxError); |
| 430 | } |
| 431 | |
| 432 | template <class CM> |
| 433 | double getReprojectionError(const vector<MeasurementSet>& ms, const vector<vector<Vector<2>>>& plane, CM& cm) |
| 434 | { |
| 435 | assert(plane.size() == ms.size()); |
| 436 | double error = 0; |
| 437 | for(size_t i = 0; i < ms.size(); i++) |
| 438 | { |
| 439 | for(size_t j = 0; j < plane[i].size(); j++) |
| 440 | { |
| 441 | Vector<2> im = cm.project(plane[i][j]); |
| 442 | Vector<2> v = ms[i].im[j] - im; |
| 443 | error += v * v; |
| 444 | } |
| 445 | } |
| 446 | return error; |
| 447 | } |
| 448 | |
| 449 | template <class CM> |
| 450 | void improveLM(vector<MeasurementSet>& ms, vector<SE3<>>& pose, CM& cm, double lambda) |
| 451 | { |
| 452 | Matrix<> JTJ(CM::num_parameters + ms.size() * 6, CM::num_parameters + ms.size() * 6); |
| 453 | Vector<> JTe(JTJ.num_rows()); |
| 454 | |
| 455 | JTJ = Zeros; |
| 456 | Vector<CM::num_parameters> JTep = Zeros; |
| 457 | |
| 458 | for(size_t i = 0; i < ms.size(); i++) |
| 459 | { |
| 460 | Matrix<6> poseBlock = Zeros; |
| 461 | Matrix<CM::num_parameters> paramBlock = Zeros; |
| 462 | Matrix<CM::num_parameters, 6> offDiag = Zeros; |
| 463 | |
| 464 | Vector<6> JTei = Zeros; |
| 465 | |
| 466 | for(size_t j = 0; j < ms[i].im.size(); j++) |
| 467 | { |
| 468 | Matrix<2, 3> J_x; |
| 469 | Matrix<2, 6> J_pose; |
| 470 | Vector<2> v = ms[i].im[j] - cm.project(transform_and_project(pose[i], ms[i].world[j], J_x, J_pose)); |
| 471 | //Vector<2> im = cm.project(project(camFrame)); |
| 472 | //Vector<2> v = ms[i].im[j] - im; |
| 473 | //makeProjectionParameterJacobian(camFrame, /*pose[i],*/ J_pose); |
| 474 | J_pose = cm.get_derivative() * J_pose; |
| 475 | Matrix<2, CM::num_parameters> J_param = cm.get_parameter_derivs().T(); |
| 476 | poseBlock += J_pose.T() * J_pose; |
| 477 | paramBlock += J_param.T() * J_param; |
| 478 | offDiag += J_param.T() * J_pose; |
| 479 | JTei += J_pose.T() * v; |
| 480 | JTep += J_param.T() * v; |
| 481 | } |
| 482 | JTe.slice(CM::num_parameters + i * 6, 6) = JTei; |
| 483 | JTJ.slice(CM::num_parameters + i * 6, CM::num_parameters + i * 6, 6, 6) = poseBlock; |
| 484 | JTJ.slice(0, 0, CM::num_parameters, CM::num_parameters) += paramBlock; |
| 485 | JTJ.slice(0, CM::num_parameters + i * 6, CM::num_parameters, 6) = offDiag; |
| 486 | JTJ.slice(CM::num_parameters + i * 6, 0, 6, CM::num_parameters) = offDiag.T(); |
| 487 | } |
| 488 | JTe.slice(0, CM::num_parameters) = JTep; |
| 489 | |
| 490 | for(int i = 0; i < JTJ.num_rows(); i++) |
| 491 | JTJ[i][i] += lambda; |
| 492 | Vector<> delta = Cholesky<>(JTJ).backsub(JTe); |
| 493 | cm.get_parameters() += delta.template slice<0, CM::num_parameters>(); |
| 494 | for(size_t i = 0; i < pose.size(); i++) |
| 495 | { |
| 496 | pose[i].left_multiply_by(SE3<>::exp(delta.slice(CM::num_parameters + i * 6, 6))); |
| 497 | } |
| 498 | } |
| 499 | |
| 500 | template <class CM> |
| 501 | void getUncertainty(const vector<MeasurementSet>& ms, const vector<SE3<>>&, CM& cm, Matrix<CM::num_parameters>& C) |
| 502 | { |
| 503 | Matrix<> JTJ(CM::num_parameters + ms.size() * 6, CM::num_parameters + ms.size() * 6); |
| 504 | JTJ = Zeros; |
| 505 | for(size_t i = 0; i < ms.size(); i++) |
| 506 | { |
| 507 | Matrix<6> poseBlock = Zeros; |
| 508 | Matrix<CM::num_parameters> paramBlock = Zeros; |
| 509 | Matrix<CM::num_parameters, 6> offDiag = Zeros; |
| 510 | for(size_t j = 0; j < ms[i].im.size(); j++) |
| 511 | { |
| 512 | Matrix<2, 3> J_x; |
| 513 | Matrix<2, 6> J_pose; |
| 514 | |
| 515 | J_pose = cm.get_derivative() * J_pose; |
| 516 | Matrix<2, CM::num_parameters> J_param = cm.get_parameter_derivs().T(); |
| 517 | poseBlock += J_pose.T() * J_pose; |
| 518 | paramBlock += J_param.T() * J_param; |
| 519 | offDiag += J_param.T() * J_pose; |
| 520 | } |
| 521 | JTJ.slice(CM::num_parameters + i * 6, CM::num_parameters + i * 6, 6, 6) = poseBlock; |
| 522 | JTJ.slice(0, 0, CM::num_parameters, CM::num_parameters) = JTJ.slice(0, 0, CM::num_parameters, CM::num_parameters) + paramBlock; |
| 523 | JTJ.slice(0, CM::num_parameters + i * 6, CM::num_parameters, 6) = offDiag; |
| 524 | JTJ.slice(CM::num_parameters + i * 6, 0, 6, CM::num_parameters) = offDiag.T(); |
| 525 | } |
| 526 | Cholesky<> chol(JTJ); |
| 527 | Vector<> v(JTJ.num_cols()); |
| 528 | v = Zeros; |
| 529 | |
| 530 | for(int i = 0; i < CM::num_parameters; ++i) |
| 531 | { |
| 532 | v[i] = 1; |
| 533 | Vector<> Cv = chol.backsub(v); |
| 534 | v[i] = 0; |
| 535 | C.T()[i] = Cv.template slice<0, CM::num_parameters>(); |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | inline Vector<2> imagePoint(const Vector<2>& inPoint, const SE3<>& pose, CameraModel& cm, const double& factor) |
| 540 | { |
| 541 | Vector<3> point3D = unproject(inPoint); |
| 542 | Vector<2> plane = project(pose * point3D); |
| 543 | Vector<2> im = cm.project(plane) / factor; |
| 544 | |
| 545 | return im; |
| 546 | } |
| 547 | |
| 548 | inline float imageVal(image_interpolate<Interpolate::Bilinear, float>& imgInter, const Vector<2>& inPoint, const SE3<>& pose, |
| 549 | CameraModel& cm, const double& factor, const bool& boundsCheck) |
| 550 | { |
| 551 | Vector<2> imageVec = imagePoint(inPoint, pose, cm, factor); |
| 552 | if(!boundsCheck) //Slight speed-up |
| 553 | return imgInter[imageVec]; |
| 554 | |
| 555 | if(imgInter.in_image(imageVec)) |
| 556 | return imgInter[imageVec]; |
| 557 | else |
| 558 | return -1; |
| 559 | } |
| 560 | |
| 561 | //l,t,r,b |
| 562 | inline bool inSquareX(const Vector<2>& inPoint, const Vector<4>& calibSquare) |
| 563 | { |
| 564 | if(inPoint[0] < calibSquare[0]) |
| 565 | return false; |
| 566 | if(inPoint[0] > calibSquare[2]) |
| 567 | return false; |
| 568 | |
| 569 | return true; |
| 570 | } |
| 571 | //l,t,r,b |
| 572 | inline bool inSquareY(const Vector<2>& inPoint, const Vector<4>& calibSquare) |
| 573 | { |
| 574 | if(inPoint[1] > calibSquare[1]) |
| 575 | return false; |
| 576 | if(inPoint[1] < calibSquare[3]) |
| 577 | return false; |
| 578 | |
| 579 | return true; |
| 580 | } |
| 581 | |
| 582 | inline float minMargin(const Vector<2>& imagePoint, const Vector<2>& minCoord, const Vector<2>& maxCoord) |
| 583 | { |
| 584 | return std::min(imagePoint[0] - minCoord[0], |
| 585 | std::min(imagePoint[1] - minCoord[1], |
| 586 | std::min(maxCoord[0] - imagePoint[0], maxCoord[1] - imagePoint[1]))); |
| 587 | } |
| 588 | |
| 589 | inline float minMarginSquare(const Vector<2>& inPoint, image_interpolate<Interpolate::Bilinear, float>& imgInter, const SE3<>& pose, |
| 590 | CameraModel& cm, double factor, float cellSize) |
| 591 | { |
| 592 | Vector<2> posVec = makeVector(cellSize / 2, cellSize / 2); |
| 593 | Vector<2> negVec = makeVector(cellSize / 2, -cellSize / 2); |
| 594 | |
| 595 | Vector<2> minCoord = imgInter.min(); |
| 596 | Vector<2> maxCoord = imgInter.max(); |
| 597 | |
| 598 | float minVal = minMargin(imagePoint(inPoint, pose, cm, factor), minCoord, maxCoord); |
| 599 | minVal = std::min(minVal, minMargin(imagePoint(inPoint - negVec, pose, cm, factor), minCoord, maxCoord)); //top-left |
| 600 | minVal = std::min(minVal, minMargin(imagePoint(inPoint + posVec, pose, cm, factor), minCoord, maxCoord)); //top-right |
| 601 | minVal = std::min(minVal, minMargin(imagePoint(inPoint - posVec, pose, cm, factor), minCoord, maxCoord)); //bottom-left |
| 602 | minVal = std::min(minVal, minMargin(imagePoint(inPoint + negVec, pose, cm, factor), minCoord, maxCoord)); //bottom-right |
| 603 | |
| 604 | return minVal; |
| 605 | } |
| 606 | |
| 607 | bool sanityCheck(const Vector<2>& inPoint, image_interpolate<Interpolate::Bilinear, float>& imgInter, const SE3<>& pose, |
| 608 | CameraModel& cm, double factor, bool blWhite, float cellSize) |
| 609 | { |
| 610 | Vector<2> posVec = makeVector(cellSize / 2, cellSize / 2); |
| 611 | Vector<2> negVec = makeVector(cellSize / 2, -cellSize / 2); |
| 612 | |
| 613 | // Don't need to bounds check these as it's done after the minMarginSquare > 0 check |
| 614 | float midVal = imageVal(imgInter, inPoint, pose, cm, factor, false); |
| 615 | float tlVal = imageVal(imgInter, inPoint - negVec, pose, cm, factor, false); |
| 616 | float trVal = imageVal(imgInter, inPoint + posVec, pose, cm, factor, false); |
| 617 | float blVal = imageVal(imgInter, inPoint - posVec, pose, cm, factor, false); |
| 618 | float brVal = imageVal(imgInter, inPoint + negVec, pose, cm, factor, false); |
| 619 | |
| 620 | if(blWhite) |
| 621 | { |
| 622 | if(midVal - tlVal < 0.02) |
| 623 | return false; |
| 624 | if(trVal - midVal < 0.02) |
| 625 | return false; |
| 626 | if(blVal - midVal < 0.02) |
| 627 | return false; |
| 628 | if(midVal - brVal < 0.02) |
| 629 | return false; |
| 630 | } |
| 631 | else |
| 632 | { |
| 633 | if(tlVal - midVal < 0.02) |
| 634 | return false; |
| 635 | if(midVal - trVal < 0.02) |
| 636 | return false; |
| 637 | if(midVal - blVal < 0.02) |
| 638 | return false; |
| 639 | if(brVal - midVal < 0.02) |
| 640 | return false; |
| 641 | } |
| 642 | |
| 643 | return true; |
| 644 | } |
| 645 | |
| 646 | bool findInitialIntersectionEstimate(image_interpolate<Interpolate::Bilinear, float>& imgInter, Vector<2>& initialPoint, |
| 647 | const SE3<>& pose, CameraModel& cm, double factor, |
| 648 | bool boundsCheck, const Vector<4>& likelySquare, double cellSize) |
| 649 | { |
| 650 | bool looksOK = true; |
| 651 | |
| 652 | //very roughly find a sensible starting place |
| 653 | Vector<2> testPoint = makeVector(likelySquare[0], likelySquare[1]); |
| 654 | float startPx = imageVal(imgInter, testPoint, pose, cm, factor, boundsCheck); |
| 655 | while(looksOK && fabs(imageVal(imgInter, testPoint, pose, cm, factor, boundsCheck) - startPx) < 0.1) |
| 656 | { |
| 657 | testPoint[0] += cellSize / 10; |
| 658 | if(testPoint[0] > likelySquare[2]) |
| 659 | looksOK = false; |
| 660 | } |
| 661 | if(looksOK) |
| 662 | initialPoint[0] = testPoint[0]; |
| 663 | |
| 664 | testPoint[0] = likelySquare[0]; |
| 665 | while(looksOK && fabs(imageVal(imgInter, testPoint, pose, cm, factor, boundsCheck) - startPx) < 0.1) |
| 666 | { |
| 667 | testPoint[1] -= cellSize / 10; |
| 668 | if(testPoint[1] < likelySquare[3]) |
| 669 | looksOK = false; |
| 670 | } |
| 671 | if(looksOK) |
| 672 | initialPoint[1] = testPoint[1]; |
| 673 | |
| 674 | return looksOK; |
| 675 | } |
| 676 | |
| 677 | bool optimiseIntersection(image_interpolate<Interpolate::Bilinear, float>& imgInter, Vector<2>& inPoint, |
| 678 | const SE3<>& pose, CameraModel& cm, double factor, bool boundsCheck, |
| 679 | const Vector<4>& likelySquare, double cellSize, bool blWhite) |
| 680 | { |
| 681 | Vector<2> largeX = makeVector(0.004, 0); |
| 682 | Vector<2> largeY = makeVector(0, 0.004); |
| 683 | Vector<2> smallX = makeVector(cellSize / 10, 0); |
| 684 | Vector<2> smallY = makeVector(0, cellSize / 10); |
| 685 | |
| 686 | float aboveVal = imageVal(imgInter, inPoint + largeY, pose, cm, factor, boundsCheck); |
| 687 | float belowVal = imageVal(imgInter, inPoint - largeY, pose, cm, factor, boundsCheck); |
| 688 | float leftVal = imageVal(imgInter, inPoint - largeX, pose, cm, factor, boundsCheck); |
| 689 | float rightVal = imageVal(imgInter, inPoint + largeX, pose, cm, factor, boundsCheck); |
| 690 | |
| 691 | while(fabs(aboveVal - belowVal) > 0.2 || fabs(leftVal - rightVal) > 0.2) |
| 692 | { |
| 693 | //reduce step size |
| 694 | smallY = smallY / 2; |
| 695 | smallX = smallX / 2; |
| 696 | |
| 697 | while(belowVal < aboveVal) |
| 698 | { |
| 699 | //lighter above - move left if bottom-left white, otherwise right |
| 700 | blWhite ? inPoint -= smallX : inPoint += smallX; |
| 701 | if(!inSquareX(inPoint, likelySquare)) |
| 702 | break; |
| 703 | aboveVal = imageVal(imgInter, inPoint + largeY, pose, cm, factor, boundsCheck); |
| 704 | belowVal = imageVal(imgInter, inPoint - largeY, pose, cm, factor, boundsCheck); |
| 705 | } |
| 706 | while(belowVal > aboveVal) |
| 707 | { |
| 708 | //darker above - move right if bottom-left white, otherwise left |
| 709 | blWhite ? inPoint += smallX : inPoint -= smallX; |
| 710 | if(!inSquareX(inPoint, likelySquare)) |
| 711 | break; |
| 712 | aboveVal = imageVal(imgInter, inPoint + largeY, pose, cm, factor, boundsCheck); |
| 713 | belowVal = imageVal(imgInter, inPoint - largeY, pose, cm, factor, boundsCheck); |
| 714 | } |
| 715 | |
| 716 | while(rightVal > leftVal) |
| 717 | { |
| 718 | //darker on left - move down if bottom-left white, otherwise up |
| 719 | blWhite ? inPoint -= smallY : inPoint += smallY; |
| 720 | if(!inSquareY(inPoint, likelySquare)) |
| 721 | break; |
| 722 | leftVal = imageVal(imgInter, inPoint - largeX, pose, cm, factor, boundsCheck); |
| 723 | rightVal = imageVal(imgInter, inPoint + largeX, pose, cm, factor, boundsCheck); |
| 724 | } |
| 725 | while(rightVal < leftVal) |
| 726 | { |
| 727 | //lighter on left - move up if bottom-left white, otherwise down |
| 728 | blWhite ? inPoint += smallY : inPoint -= smallY; |
| 729 | if(!inSquareY(inPoint, likelySquare)) |
| 730 | break; |
| 731 | leftVal = imageVal(imgInter, inPoint - largeX, pose, cm, factor, boundsCheck); |
| 732 | rightVal = imageVal(imgInter, inPoint + largeX, pose, cm, factor, boundsCheck); |
| 733 | } |
| 734 | |
| 735 | if(!(inSquareX(inPoint, likelySquare) && inSquareY(inPoint, likelySquare))) |
| 736 | break; |
| 737 | |
| 738 | if(smallX[0] < 0.000002) |
| 739 | break; //prevents infinite loop with certain patterns |
| 740 | } |
| 741 | |
| 742 | return (fabs(aboveVal - belowVal) < 1 && fabs(leftVal - rightVal) < 1); |
| 743 | } |
| 744 | |
| 745 | mt19937 engine; |
| 746 | normal_distribution<double> gaussian; |
| 747 | |
| 748 | double rand_g() |
| 749 | { |
| 750 | return gaussian(engine); |
| 751 | } |
| 752 | |
| 753 | int main(int argc, char* argv[]) |
| 754 | { |
| 755 | getOptions(argc, argv); |
| 756 | cvd_timer timer; |
| 757 | |
| 758 | string titlePrefix = "Calibrate: Align grid ([ and ] to resize)"; |
| 759 | GLWindow disp(videoBuffer->size(), titlePrefix); |
| 760 | GLWindow::EventSummary events; |
| 761 | //VideoDisplay disp (0.0, 0.0, 640.0, 480.0); |
| 762 | CameraModel cameraModel; |
| 763 | double factor = 1.0; |
| 764 | vector<MeasurementSet> measurementSets; |
| 765 | vector<SE3<>> poses; |
| 766 | ImageRef imageSize; |
| 767 | |
| 768 | if(cameraParameters[0] == -1) |
| 769 | { |
| 770 | cameraParameters = Zeros; |
| 771 | cameraParameters[0] = 500; |
| 772 | cameraParameters[1] = 500; |
| 773 | cameraParameters[2] = videoBuffer->size().x / 2; |
| 774 | cameraParameters[3] = videoBuffer->size().y / 2; |
| 775 | } |
| 776 | |
| 777 | //XEvent e; |
| 778 | //disp.select_events(KeyPressMask); |
| 779 | bool doParams = true; |
| 780 | int stage = 2; // 2 is init, 1 record, 0 done |
| 781 | |
| 782 | disp.set_title(titlePrefix); |
| 783 | |
| 784 | imageSize = videoBuffer->size(); |
| 785 | |
| 786 | cameraModel.get_parameters() = cameraParameters; |
| 787 | factor = 1.0 / std::max(imageSize.x, imageSize.y); |
| 788 | cameraModel.get_parameters().slice<0, 4>() *= factor; |
| 789 | |
| 790 | vector<Vector<2>> grid = makeGrid(gridx, gridy, cellSize); |
| 791 | vector<Vector<3>> grid3d(grid.size()); |
| 792 | for(size_t i = 0; i < grid.size(); i++) |
| 793 | grid3d[i] = unproject(grid[i]); |
| 794 | |
| 795 | SE3<> pose; |
| 796 | pose.get_translation()[2] = -0.7; |
| 797 | const SE3<> init_pose = pose; |
| 798 | |
| 799 | glPixelStorei(GL_UNPACK_ALIGNMENT, 1); |
| 800 | glDrawBuffer(GL_BACK); |
| 801 | glEnable(GL_BLEND); |
| 802 | glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); |
| 803 | |
| 804 | double lastMeasure = timer.get_time(); |
| 805 | bool prevFrameTracked = false; |
| 806 | while(stage) |
| 807 | { |
| 808 | |
| 809 | events.clear(); |
| 810 | disp.get_events(events); |
| 811 | |
| 812 | for(GLWindow::EventSummary::key_iterator it = events.key_down.begin(); it != events.key_down.end(); ++it) |
| 813 | { |
| 814 | switch(it->first) |
| 815 | { |
| 816 | case XK_Home: |
| 817 | pose = init_pose; |
| 818 | break; |
| 819 | case XK_bracketleft: |
| 820 | pose.get_translation()[2] += 0.02; |
| 821 | break; |
| 822 | case XK_bracketright: |
| 823 | pose.get_translation()[2] -= 0.02; |
| 824 | break; |
| 825 | case XK_Escape: |
| 826 | case XK_q: |
| 827 | case XK_Q: |
| 828 | exit(0); |
| 829 | break; |
| 830 | case XK_space: |
| 831 | if(stage == 1) |
| 832 | { |
| 833 | stage = 0; |
| 834 | titlePrefix = "Calibrate: Calculating Camera Parameters"; |
| 835 | disp.set_title(titlePrefix); |
| 836 | } |
| 837 | break; |
| 838 | case XK_p: |
| 839 | doParams = !doParams; |
| 840 | if(stage == 1) |
| 841 | { |
| 842 | if(doParams) |
| 843 | titlePrefix = "Calibrate: Tracking Pose and Internal Params"; |
| 844 | else |
| 845 | titlePrefix = "Calibrate: Tracking Pose"; |
| 846 | } |
| 847 | break; |
| 848 | } |
| 849 | } |
| 850 | |
| 851 | //videoBuffer->flush(); |
| 852 | VideoFrame<CAMERA_PIXEL>* vframe = videoBuffer->get_frame(); |
| 853 | |
| 854 | // leave this in, we cannot assume that vframe has a datatype that can be |
| 855 | // directly used in the glTexImage call later on (e.g. its yuv422 on OSX) |
| 856 | Image<byte> temp = convert_image(*vframe); |
| 857 | Image<float> gray = convert_image(temp); |
| 858 | videoBuffer->put_frame(vframe); |
| 859 | |
| 860 | glDisable(GL_BLEND); |
| 861 | GLenum texTarget; |
| 862 | #ifdef GL_TEXTURE_RECTANGLE_ARB |
| 863 | texTarget = GL_TEXTURE_RECTANGLE_ARB; |
| 864 | #elif defined GL_TEXTURE_RECTANGLE_NV |
| 865 | texTarget = GL_TEXTURE_RECTANGLE_NV; |
| 866 | #else |
| 867 | texTarget = GL_TEXTURE_RECTANGLE_EXT; |
| 868 | #endif |
| 869 | glEnable(texTarget); |
| 870 | glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); |
| 871 | glTexParameterf(texTarget, GL_TEXTURE_MIN_FILTER, GL_NEAREST); |
| 872 | glTexParameterf(texTarget, GL_TEXTURE_MAG_FILTER, GL_NEAREST); |
| 873 | glPixelStorei(GL_UNPACK_ALIGNMENT, 1); |
| 874 | glTexImage2D(temp, 0, texTarget); |
| 875 | glBegin(GL_QUADS); |
| 876 | glTexCoord2i(0, 0); |
| 877 | glVertex2i(0, 0); |
| 878 | glTexCoord2i(temp.size().x, 0); |
| 879 | glVertex2i(disp.size().x, 0); |
| 880 | glTexCoord2i(temp.size().x, temp.size().y); |
| 881 | glVertex2i(disp.size().x, disp.size().y); |
| 882 | glTexCoord2i(0, temp.size().y); |
| 883 | glVertex2i(0, disp.size().y); |
| 884 | glEnd(); |
| 885 | glDisable(texTarget); |
| 886 | |
| 887 | glEnable(GL_BLEND); |
| 888 | |
| 889 | //this is the bit that does the calibrating |
| 890 | vector<pair<size_t, Vector<2>>> measurements; |
| 891 | vector<Vector<2>> failedPoints; |
| 892 | |
| 893 | //smooth and prepare image for interpolation |
| 894 | convolveGaussian(gray, 0.5); |
| 895 | image_interpolate<Interpolate::Bilinear, float> imgInter = image_interpolate<Interpolate::Bilinear, float>(gray); |
| 896 | |
| 897 | int guessCount = 0; |
| 898 | int totalPass = 0, totalFail = 0; |
| 899 | SE3<> guessPose = pose; |
| 900 | bool correctPose = false; |
| 901 | |
| 902 | do |
| 903 | { |
| 904 | measurements.clear(); |
| 905 | failedPoints.clear(); |
| 906 | |
| 907 | int rowPass[gridy + 1]; |
| 908 | for(int i = 0; i < gridy + 1; i++) |
| 909 | rowPass[i] = 0; |
| 910 | int rowFail[gridy + 1]; |
| 911 | for(int i = 0; i < gridy + 1; i++) |
| 912 | rowFail[i] = 0; |
| 913 | int colPass[gridx + 1]; |
| 914 | for(int i = 0; i < gridx + 1; i++) |
| 915 | colPass[i] = 0; |
| 916 | int colFail[gridx + 1]; |
| 917 | for(int i = 0; i < gridx + 1; i++) |
| 918 | colFail[i] = 0; |
| 919 | |
| 920 | totalPass = 0; |
| 921 | totalFail = 0; |
| 922 | |
| 923 | for(size_t i = 0; i < grid.size(); i++) |
| 924 | { |
| 925 | int yNo = i / (gridx + 1); |
| 926 | int xNo = i % (gridx + 1); |
| 927 | bool blWhite = (xNo + yNo) % 2; |
| 928 | if(bottomLeftWhite) |
| 929 | blWhite = !blWhite; |
| 930 | |
| 931 | Vector<2> inPoint = makeVector(xNo * cellSize - gridx * cellSize / 2, yNo * cellSize - gridy * cellSize / 2); |
| 932 | Vector<4> likelySquare = makeVector(inPoint[0] - cellSize / 2, inPoint[1] + cellSize / 2, |
| 933 | inPoint[0] + cellSize / 2, inPoint[1] - cellSize / 2); //l,t,r,b |
| 934 | |
| 935 | float minMarginDist = minMarginSquare(inPoint, imgInter, guessPose, cameraModel, factor, cellSize); |
| 936 | if(minMarginDist > 0) |
| 937 | { |
| 938 | bool boundsCheck = (minMarginDist < 40) ? true : false; |
| 939 | |
| 940 | bool okEst = findInitialIntersectionEstimate(imgInter, inPoint, guessPose, cameraModel, |
| 941 | factor, boundsCheck, likelySquare, cellSize); |
| 942 | |
| 943 | bool fail = true; |
| 944 | |
| 945 | if(okEst) |
| 946 | { |
| 947 | //Find the accurate intersection |
| 948 | bool converged = optimiseIntersection(imgInter, inPoint, guessPose, cameraModel, factor, |
| 949 | boundsCheck, likelySquare, cellSize, blWhite); |
| 950 | |
| 951 | //Check the found position - inside the image bounds? |
| 952 | if(minMarginSquare(inPoint, imgInter, guessPose, cameraModel, factor, cellSize) > 0) |
| 953 | { |
| 954 | //In expected square? |
| 955 | if(inSquareX(inPoint, likelySquare) && inSquareY(inPoint, likelySquare)) |
| 956 | { |
| 957 | //Optimisation suitably converged? |
| 958 | if(converged) |
| 959 | { |
| 960 | //Sensible difference between the black and white squares? |
| 961 | if(sanityCheck(inPoint, imgInter, guessPose, cameraModel, factor, blWhite, cellSize)) |
| 962 | { |
| 963 | fail = false; |
| 964 | rowPass[yNo]++; |
| 965 | colPass[xNo]++; |
| 966 | totalPass++; |
| 967 | |
| 968 | //add to the list of points to be used to optimise the pose |
| 969 | measurements.push_back(make_pair(i, imagePoint(inPoint, guessPose, cameraModel, factor) * factor)); |
| 970 | } |
| 971 | } |
| 972 | } |
| 973 | } |
| 974 | else |
| 975 | fail = false; //Points outside the image haven't really failed |
| 976 | } |
| 977 | |
| 978 | if(fail) |
| 979 | { |
| 980 | rowFail[yNo]++; |
| 981 | colFail[xNo]++; |
| 982 | totalFail++; |
| 983 | |
| 984 | failedPoints.push_back(imagePoint(inPoint, pose, cameraModel, factor)); |
| 985 | } |
| 986 | } |
| 987 | } |
| 988 | |
| 989 | //If previous frame tracked OK, decision on next one is based on no. of failures |
| 990 | //Otherwise base on no. of passes - this means if tracking is going OK it will track |
| 991 | //even when not all points are visible. However if tracking is lost, it will not |
| 992 | //lock on again until it passes suitably on all rows |
| 993 | if(prevFrameTracked) |
| 994 | { |
| 995 | int worstRow = rowFail[0]; |
| 996 | for(int i = 0; i < gridy + 1; i++) |
| 997 | if(rowFail[i] > worstRow) |
| 998 | worstRow = rowFail[i]; |
| 999 | |
| 1000 | int worstCol = colFail[0]; |
| 1001 | for(int i = 0; i < gridx + 1; i++) |
| 1002 | if(colFail[i] > worstCol) |
| 1003 | worstCol = colFail[i]; |
| 1004 | |
| 1005 | //allow half of the worst column or row to fail, as long as overall 5x more points pass than fail |
| 1006 | if(worstCol <= gridx / 2 && worstRow <= gridy / 2 && static_cast<float>(totalFail) / totalPass < 0.2) |
| 1007 | correctPose = true; |
| 1008 | } |
| 1009 | else |
| 1010 | { |
| 1011 | int worstRow = rowPass[0]; |
| 1012 | for(int i = 0; i < gridy + 1; i++) |
| 1013 | if(rowPass[i] < worstRow) |
| 1014 | worstRow = rowPass[i]; |
| 1015 | |
| 1016 | int worstCol = colPass[0]; |
| 1017 | for(int i = 0; i < gridx + 1; i++) |
| 1018 | if(colPass[i] < worstCol) |
| 1019 | worstCol = colPass[i]; |
| 1020 | |
| 1021 | //If tracking failed, apply more restrictive matching constraints: |
| 1022 | //Need at least half the worst/row column to be OK, and 10x more points to pass than fail |
| 1023 | if(worstCol >= (gridx + 1) / 2 && worstRow >= (gridy + 1) / 2 && static_cast<float>(totalFail) / totalPass < 0.1) |
| 1024 | correctPose = true; |
| 1025 | } |
| 1026 | |
| 1027 | if(correctPose) |
| 1028 | { |
| 1029 | //This pose worked - let's use it |
| 1030 | pose = guessPose; |
| 1031 | } |
| 1032 | else |
| 1033 | { |
| 1034 | //Didn't track correctly - let's guess! - just change the pose a bit |
| 1035 | guessCount++; |
| 1036 | guessPose = SE3<>::exp(makeVector(rand_g() / 300, rand_g() / 300, rand_g() / 40, rand_g() / 10, rand_g() / 10, rand_g() / 10)); |
| 1037 | //Apply the change in grid coordinates |
| 1038 | //Grid coordinates actually centred on (0,0,1) in 3D, so need to shift before and after |
| 1039 | guessPose = SE3<>::exp(makeVector(0, 0, 1, 0, 0, 0)) * guessPose * SE3<>::exp(makeVector(0, 0, -1, 0, 0, 0)); |
| 1040 | guessPose = pose * guessPose; |
| 1041 | } |
| 1042 | |
| 1043 | } while((!correctPose) && (!videoBuffer->frame_pending())); |
| 1044 | |
| 1045 | if(correctPose) |
| 1046 | { |
| 1047 | if(stage == 2) |
| 1048 | { |
| 1049 | stage = 1; |
| 1050 | if(doParams) |
| 1051 | titlePrefix = "Calibrate: Tracking Pose and Internal Params"; |
| 1052 | else |
| 1053 | titlePrefix = "Calibrate: Tracking Pose"; |
| 1054 | } |
| 1055 | |
| 1056 | if(doParams) |
| 1057 | pose = find_pose_and_params(pose, grid3d, measurements, cameraModel, factor * factor); |
| 1058 | else |
| 1059 | pose = find_pose(pose, grid3d, measurements, cameraModel, factor * factor); |
| 1060 | |
| 1061 | double now = timer.get_time(); |
| 1062 | if(now - lastMeasure > interval) |
| 1063 | { |
| 1064 | lastMeasure = now; |
| 1065 | MeasurementSet ms; |
| 1066 | for(size_t i = 0; i < measurements.size(); i++) |
| 1067 | { |
| 1068 | ms.im.push_back(measurements[i].second); |
| 1069 | ms.world.push_back(grid3d[measurements[i].first]); |
| 1070 | } |
| 1071 | measurementSets.push_back(ms); |
| 1072 | poses.push_back(pose); |
| 1073 | char buf[50]; |
| 1074 | sprintf(buf, " (%u views)", (unsigned int)measurementSets.size()); |
| 1075 | disp.set_title(titlePrefix + buf); |
| 1076 | } |
| 1077 | prevFrameTracked = true; |
| 1078 | } |
| 1079 | else |
| 1080 | prevFrameTracked = false; |
| 1081 | |
| 1082 | //Draw the grid of estimated pose, and the points used to come up with it |
| 1083 | vector<Vector<2>> img_grid(grid.size()); |
| 1084 | for(size_t i = 0; i < grid.size(); i++) |
| 1085 | { |
| 1086 | Vector<2> plane = project(pose * grid3d[i]); |
| 1087 | img_grid[i] = cameraModel.project(plane) / factor; |
| 1088 | } |
| 1089 | if(correctPose) |
| 1090 | { |
| 1091 | glColor3f(1, 1, 1); |
| 1092 | drawGrid(img_grid, gridx, gridy); |
| 1093 | //plot the points used to estimate this pose |
| 1094 | glColor3f(0, 1, 0); |
| 1095 | for(size_t i = 0; i < measurements.size(); i++) |
| 1096 | drawCross(measurements[i].second / factor, 8); |
| 1097 | glColor3f(1, 0, 0); |
| 1098 | for(size_t i = 0; i < failedPoints.size(); i++) |
| 1099 | drawCross(failedPoints[i], 8); |
| 1100 | } |
| 1101 | else |
| 1102 | { |
| 1103 | glColor3f(1, 0.2, 0.2); |
| 1104 | drawGrid(img_grid, gridx, gridy); |
| 1105 | } |
| 1106 | |
| 1107 | //Coloured box to signify stage - init, record or calc |
| 1108 | switch(stage) |
| 1109 | { |
| 1110 | case 0: |
| 1111 | glColor4f(0, 1, 0, 0.5); |
| 1112 | break; |
| 1113 | case 1: |
| 1114 | glColor4f(1, 0, 0, 0.5); |
| 1115 | break; |
| 1116 | case 2: |
| 1117 | glColor4f(1, 1, 0, 0.5); |
| 1118 | break; |
| 1119 | } |
| 1120 | glBegin(GL_QUADS); |
| 1121 | glVertex2i(15, 450); |
| 1122 | glVertex2i(30, 450); |
| 1123 | glVertex2i(30, 465); |
| 1124 | glVertex2i(15, 465); |
| 1125 | glEnd(); |
| 1126 | disp.swap_buffers(); |
| 1127 | } |
| 1128 | |
| 1129 | size_t numMeasurements = 0; |
| 1130 | for(size_t i = 0; i < measurementSets.size(); i++) |
| 1131 | numMeasurements += measurementSets[i].im.size(); |
| 1132 | |
| 1133 | cout.precision(10); |
| 1134 | cerr.precision(10); |
| 1135 | size_t numPoints = 0; |
| 1136 | for(size_t i = 0; i < measurementSets.size(); i++) |
| 1137 | { |
| 1138 | numPoints += measurementSets[i].im.size(); |
| 1139 | } |
| 1140 | cerr << measurementSets.size() << " sets of measurements, " << numPoints << " total points" << endl; |
| 1141 | |
| 1142 | double minError = getReprojectionError(measurementSets, poses, cameraModel); |
| 1143 | cerr << sqrt(minError / numPoints) / factor << " initial reprojection error" << endl; |
| 1144 | |
| 1145 | cerr << "Optimizing with Levenberg-Marquardt..." << endl; |
| 1146 | double lambda = 1; |
| 1147 | while(lambda < 1e12) |
| 1148 | { |
| 1149 | Vector<NumCameraParams> params = cameraModel.get_parameters(); |
| 1150 | vector<SE3<>> oldposes = poses; |
| 1151 | improveLM(measurementSets, poses, cameraModel, lambda); |
| 1152 | double error = getReprojectionError(measurementSets, poses, cameraModel); |
| 1153 | if(minError - error > 1e-19) |
| 1154 | { |
| 1155 | minError = error; |
| 1156 | lambda *= 0.5; |
| 1157 | cerr << "rms reprojection error = " << sqrt(minError / numPoints) / factor << " pixels" << endl; |
| 1158 | } |
| 1159 | else |
| 1160 | { |
| 1161 | poses = oldposes; |
| 1162 | cameraModel.get_parameters() = params; |
| 1163 | lambda *= 10; |
| 1164 | } |
| 1165 | //Vector<6> v = cameraModel.get_parameters(); |
| 1166 | //v.slice<0,4>() /= factor; |
| 1167 | //cerr << v << endl; |
| 1168 | } |
| 1169 | |
| 1170 | vector<pair<Vector<2>, Vector<2>>> errors; |
| 1171 | pair<double, double> rperr = getReprojectionError(measurementSets, poses, cameraModel, errors); |
| 1172 | |
| 1173 | if(generateErrorImage) |
| 1174 | { |
| 1175 | cerr << "Generating errors.pgm..." << endl; |
| 1176 | Image<float> errorImage(imageSize); |
| 1177 | errorImage.zero(); |
| 1178 | for(size_t i = 0; i < errors.size(); i++) |
| 1179 | { |
| 1180 | ImageRef p = ir_rounded(errors[i].first / factor); |
| 1181 | double mag = sqrt(errors[i].second * errors[i].second / rperr.second); |
| 1182 | errorImage[p] = mag; |
| 1183 | } |
| 1184 | img_save(errorImage, "errors.pgm"); |
| 1185 | } |
| 1186 | |
| 1187 | cerr << "Estimating uncertainty..." << endl; |
| 1188 | Matrix<NumCameraParams> Cov; |
| 1189 | getUncertainty(measurementSets, poses, cameraModel, Cov); |
| 1190 | static const int NumRadialParams = NumCameraParams - 4; |
| 1191 | Cov.slice<4, 4, NumRadialParams, NumRadialParams>() *= factor * factor; |
| 1192 | Cov.slice<0, 4, 4, NumRadialParams>() *= factor; |
| 1193 | Cov.slice<4, 0, NumRadialParams, 4>() *= factor; |
| 1194 | |
| 1195 | Vector<NumCameraParams> uncertainty; |
| 1196 | for(int i = 0; i < NumCameraParams; i++) |
| 1197 | uncertainty[i] = 3 * sqrt(Cov[i][i]); |
| 1198 | |
| 1199 | cameraModel.get_parameters().slice<0, 4>() /= factor; |
| 1200 | |
| 1201 | cout.precision(14); |
| 1202 | cout << sqrt(rperr.first / numPoints) / factor << " average reprojection error" << endl; |
| 1203 | cout << "Three sigma uncertainties: " << endl; |
| 1204 | cout << uncertainty << endl |
| 1205 | << endl; |
| 1206 | cout << "Parameters:" << endl; |
| 1207 | cout << cameraModel.get_parameters() << endl |
| 1208 | << endl; |
| 1209 | cout << "Covariance:" << endl; |
| 1210 | cout << endl |
| 1211 | << Cov << endl |
| 1212 | << endl; |
| 1213 | |
| 1214 | cout << "Camera Model:" << endl; |
| 1215 | cameraModel.save(cout); |
| 1216 | cout << endl |
| 1217 | << endl; |
| 1218 | |
| 1219 | if(output.length()) |
| 1220 | { |
| 1221 | ofstream fout(output.c_str()); |
| 1222 | fout.precision(19); |
| 1223 | cameraModel.save(fout); |
| 1224 | } |
| 1225 | |
| 1226 | return 0; |
| 1227 | } |