1+ #include " opencv_all.hpp"
2+
3+ #define Rx (rx ) (cv::Mat_<double >(3 , 3 ) << 1 , 0 , 0 , 0 , cos(rx), -sin(rx), 0 , sin(rx), cos(rx))
4+ #define Ry (ry ) (cv::Mat_<double >(3 , 3 ) << cos(ry), 0 , sin(ry), 0 , 1 , 0 , -sin(ry), 0 , cos(ry))
5+ #define Rz (rz ) (cv::Mat_<double >(3 , 3 ) << cos(rz), -sin(rz), 0 , sin(rz), cos(rz), 0 , 0 , 0 , 1 )
6+
7+ int main (void )
8+ {
9+ // The given camera configuration: focal length, principal point, image resolution, position, and orientation
10+ double camera_focal = 1000 ;
11+ cv::Point2d camera_center (320 , 240 );
12+ cv::Size camera_res (640 , 480 );
13+ cv::Point3d camera_pos[] = { cv::Point3d (0 , 0 , 0 ), cv::Point3d (-2 , -2 , 0 ), cv::Point3d (2 , 2 , 0 ) };
14+ cv::Point3d camera_ori[] = { cv::Point3d (0 , 0 , 0 ), cv::Point3d (-CV_PI / 12 , CV_PI / 12 , 0 ), cv::Point3d (CV_PI / 12 , -CV_PI / 12 , 0 ) };
15+
16+ // Load a point cloud in the homogeneous coordinate
17+ FILE* fin = fopen (" data/box.xyz" , " rt" );
18+ if (fin == NULL ) return -1 ;
19+ cv::Mat X;
20+ while (!feof (fin))
21+ {
22+ double x, y, z;
23+ if (fscanf (fin, " %lf %lf %lf" , &x, &y, &z) == 3 )
24+ {
25+ X.push_back <double >(x);
26+ X.push_back <double >(y);
27+ X.push_back <double >(z);
28+ X.push_back <double >(1 );
29+ }
30+ }
31+ fclose (fin);
32+ X = X.reshape (1 , X.rows / 4 ).t (); // Convert to a 4 x N matrix
33+
34+ cv::Mat K = (cv::Mat_<double >(3 , 3 ) << camera_focal, 0 , camera_center.x , 0 , camera_focal, camera_center.y , 0 , 0 , 1 );
35+ for (int i = 0 ; i < sizeof (camera_pos) / sizeof (cv::Point3d); i++)
36+ {
37+ // Derive a projection matrix
38+ cv::Mat Rc = Rz (camera_ori[i].z ) * Ry (camera_ori[i].y ) * Rx (camera_ori[i].x );
39+ cv::Mat tc = (cv::Mat_<double >(3 , 1 ) << camera_pos[i].x , camera_pos[i].y , camera_pos[i].z );
40+ cv::Mat Rt;
41+ cv::hconcat (Rc.t (), -Rc.t () * tc, Rt);
42+ cv::Mat P = K * Rt;
43+
44+ // Project the points (c.f. OpenCV provide 'cv::projectPoints' with consideration of distortion.)
45+ cv::Mat x = P * X;
46+ x.row (0 ) = x.row (0 ) / x.row (2 );
47+ x.row (1 ) = x.row (1 ) / x.row (2 );
48+ x.row (2 ) = 1 ;
49+
50+ // Show and store the points
51+ cv::Mat image = cv::Mat::zeros (camera_res, CV_8UC1);
52+ for (int c = 0 ; c < x.cols ; c++)
53+ {
54+ cv::Point p (x.at <double >(0 , c), x.at <double >(1 , c));
55+ if (p.x >= 0 && p.x < camera_res.width && p.y >= 0 && p.y < camera_res.height )
56+ cv::circle (image, p, 2 , 255 , -1 );
57+ }
58+ cv::imshow (cv::format (" camera_image%d" , i), image);
59+ cv::waitKey (0 );
60+
61+ std::ofstream fout (cv::format (" camera_points%d.csv" , i));
62+ fout << cv::format (x.t (), cv::Formatter::FMT_CSV);
63+ fout.close ();
64+ }
65+
66+ return 0 ;
67+ }
0 commit comments