Rendering a scene through a real calibrated camera and converting between pixels and 3D rays.
This tutorial reconstructs the viewpoint of a real photograph. Given camera parameters recovered by calibration or structure-from-motion (here read from a Bundler file), it places the Easy3D camera so the 3D point cloud is seen exactly as in the original image, shows that image as an overlay, and lets you move the cursor to project between image pixels and 3D rays/points. The viewer subclass (TutorialRealCamera, shown after this file) does all the work.
A pinhole camera is described by intrinsics K (focal length fx/fy, principal point cx/cy, skew) and extrinsics [R|t] (rotation and translation from world to camera coordinates). A 3D world point p projects to the image as x = K [R|t] p, with the result divided by its depth (the perspective divide). Inverting this maps an image pixel back to a 3D ray through the camera center. Two conventions must be reconciled: computer vision uses X right, Y down, Z forward, while OpenGL/Easy3D uses X right, Y up, Z toward the viewer, so Y and Z are flipped when converting. A common pitfall is treating t as the camera position; the true world-space camera center is C = -R^{-1} t = -R^T t. The vertical field of view follows from the focal length and image height: fov = 2 atan(h / (2 fy)). See Camera::set_from_calibration() and the helper functions in TutorialRealCamera for the exact math.
Press 'space' to cycle through the recovered views (the window resizes to each image's aspect ratio); '1'/'2' toggle calibration vs. ground-truth pose; 'h' shows/hides the camera frusta. Move the cursor over the overlaid photo to see the corresponding 3D ray; move it over the 3D scene to see where that point lands in the image.
29#include <easy3d/core/point_cloud.h>
30#include <easy3d/renderer/drawable_points.h>
31#include <easy3d/renderer/drawable_lines.h>
32#include <easy3d/renderer/camera.h>
33#include <easy3d/renderer/manipulated_camera_frame.h>
34#include <easy3d/renderer/shape.h>
35#include <easy3d/renderer/renderer.h>
36#include <easy3d/renderer/transform.h>
37#include <easy3d/util/string.h>
38#include <easy3d/util/file_system.h>
39#include <easy3d/util/resource.h>
40#include <easy3d/fileio/image_io.h>
47const float scale = 0.3f;
49TutorialRealCamera::TutorialRealCamera(
const std::string &title,
50 const std::string &bundler_file,
51 const std::string &cloud_file)
52 :
Viewer(title), current_view_(0), cameras_drawable_(nullptr), ray_drawable_(nullptr) {
54 if (add_model(cloud_file)) {
56 auto drawable = current_model()->renderer()->get_points_drawable(
"vertices");
57 drawable->set_point_size(2.0f);
60 if (read_bundler_file(bundler_file))
61 update_cameras_drawable(
true);
63 std::cerr <<
"failed to load bundler file" << std::endl;
66 camera()->set_up_vector(
vec3(0, 1, 0));
67 camera()->set_view_direction(
vec3(0, 0, -1));
68 camera()->show_entire_scene();
71 std::cerr <<
"failed to load point cloud" << std::endl;
75 "Press 'Space' to switch views \n"
76 "Press 'h' to show/hide the cameras \n"
77 "Move cursor on image to show corresponding 3D ray \n"
78 "Move cursor on scene to show corresponding image point";
81bool TutorialRealCamera::key_press_event(
int key,
int modifiers) {
84 ray_drawable_->set_visible(
false);
85 cross_visible_ =
false;
88 if (key == KEY_SPACE) {
89 if (!views_.empty()) {
91 current_view_ = (current_view_ + 1) %
static_cast<int>(views_.size());
92 const bool ground_truth =
true;
93 if (KRT_to_camera(current_view_, camera(), ground_truth)) {
94 update_cameras_drawable(ground_truth);
95 std::cout <<
"----- view " << current_view_ <<
": "
96 << (ground_truth ?
"ground truth view" :
"calibration view") << std::endl;
97 set_title(
"TutorialRealCamera: View_" + std::to_string(current_view_));
98 const CameraPara &c = views_[current_view_];
101 resize(
static_cast<int>(
static_cast<float>(c.w) * scale),
102 static_cast<int>(
static_cast<float>(c.h) * scale));
106 }
else if (key == KEY_1) {
107 if (!views_.empty()) {
109 const bool ground_truth =
false;
110 if (KRT_to_camera(current_view_, camera(), ground_truth)) {
111 update_cameras_drawable(ground_truth);
112 std::cout <<
"----- view " << current_view_ <<
": "
113 << (ground_truth ?
"ground truth view" :
"calibration view") << std::endl;
114 set_title(
"TutorialRealCamera: View_" + std::to_string(current_view_));
115 const CameraPara &c = views_[current_view_];
117 resize(
static_cast<int>(
static_cast<float>(c.w) * scale),
118 static_cast<int>(
static_cast<float>(c.h) * scale));
122 }
else if (key == KEY_2) {
123 if (!views_.empty()) {
125 const bool ground_truth =
true;
126 if (KRT_to_camera(current_view_, camera(), ground_truth)) {
127 update_cameras_drawable(ground_truth);
128 std::cout <<
"----- view " << current_view_ <<
": "
129 << (ground_truth ?
"ground truth view" :
"calibration view") << std::endl;
130 set_title(
"TutorialRealCamera: View_" + std::to_string(current_view_));
131 const CameraPara &c = views_[current_view_];
133 resize(
static_cast<int>(
static_cast<float>(c.w) * scale),
134 static_cast<int>(
static_cast<float>(c.h) * scale));
138 }
else if (key == KEY_H) {
140 if (cameras_drawable_) {
141 cameras_drawable_->set_visible(!cameras_drawable_->is_visible());
146 return Viewer::key_press_event(key, modifiers);
150void TutorialRealCamera::load_image() {
152 const std::string image_file =
153 resource::directory() +
"/data/fountain/images/" + string::to_string(current_view_, 4,
'0') +
".jpg";
154 if (image_view_ == current_view_)
157 image_view_ = current_view_;
158 int w = 0, h = 0, channels = 0;
159 std::vector<unsigned char> rgba;
160 if (file_system::is_file(image_file) && ImageIO::load(image_file, rgba, w, h, channels, 4,
false)) {
162 sampler.
filter = graphics::TextureFilter::linear;
163 image_ = std::make_shared<graphics::Image>(w, h, std::move(rgba), sampler);
170bool TutorialRealCamera::KRT_to_camera(
int view_index,
Camera *c,
bool ground_truth) {
171 if (view_index < 0 || view_index >= views_.size()) {
172 std::cerr <<
"Error: invalid view index (" << view_index <<
")" << std::endl;
176 const CameraPara &cam = views_[view_index];
186 const float proj11 = 2.0f * cam.fy /
static_cast<float>(cam.h);
187 const float fov = 2.0f * std::atan(1.0f / proj11);
202void TutorialRealCamera::update_cameras_drawable(
bool ground_truth) {
203 if (!cameras_drawable_) {
205 add_drawable(std::shared_ptr<LinesDrawable>(cameras_drawable_));
206 cameras_drawable_->set_uniform_coloring(
vec4(0, 0, 1, 1.0f));
207 cameras_drawable_->set_line_width(1.0f);
210 std::vector<vec3> vertices;
211 for (std::size_t i = 0; i < views_.size(); ++i) {
214 KRT_to_camera(
static_cast<int>(i), &c, ground_truth);
215 std::vector<vec3> points;
217 static_cast<float>(views_[i].h) /
static_cast<float>(views_[i].w));
220 for (
auto &p : points)
221 vertices.push_back(m * p);
224 cameras_drawable_->update_vertex_buffer(vertices);
229Rect TutorialRealCamera::calculate_image_rect()
const {
232 int tex_w = int(image_->width()), tex_h = int(image_->height());
233 const float image_as =
static_cast<float>(tex_w) /
static_cast<float>(tex_h);
235 framebuffer_size(fw, fh);
236 const float viewer_as =
static_cast<float>(fw) /
static_cast<float>(fh);
237 if (image_as < viewer_as) {
239 tex_h =
static_cast<int>(
static_cast<float>(fh) * scale);
240 tex_w =
static_cast<int>(
static_cast<float>(tex_h) * image_as);
243 tex_w =
static_cast<int>(
static_cast<float>(fw) * scale);
244 tex_h =
static_cast<int>(
static_cast<float>(tex_w) / image_as);
247 const float xmax =
static_cast<float>(fw) - 20 * dpi_scaling();
248 const float ymin = 22.5f * dpi_scaling();
250 xmax -
static_cast<float>(tex_w), xmax,
251 ymin, ymin +
static_cast<float>(tex_h)
255void TutorialRealCamera::post_resize(
int,
int) {
257 cross_visible_ =
false;
262void TutorialRealCamera::pre_draw() {
265 if (overlay_image_) {
267 image_commands_.clear();
268 overlay_image_ =
nullptr;
273 framebuffer_size(fw, fh);
274 const Rect rect = calculate_image_rect();
275 const bool changed = overlay_image_ != image_.get() || overlay_width_ != fw ||
276 overlay_height_ != fh || overlay_rect_.x_min() != rect.
x_min() ||
277 overlay_rect_.x_max() != rect.
x_max() || overlay_rect_.y_min() != rect.
y_min() ||
278 overlay_rect_.y_max() != rect.
y_max();
281 image_commands_ = {image, graphics::shape::draw_quad_wire(rect,
vec4(1, 0, 0, 1), fw, fh, dpi_scaling())};
282 overlay_image_ = image_.get();
283 overlay_rect_ = rect;
285 overlay_height_ = fh;
287 const bool visible = cross_visible_;
288 const bool cross_changed = visible != cross_overlay_visible_ || cross_geometry_dirty_ || changed;
289 if (visible && cross_changed) {
290 std::vector<vec2> segments;
291 for (
const auto &p : cross_points_)
292 segments.emplace_back(p.x, p.y);
293 cross_command_ = graphics::shape::draw_lines_2d(segments,
vec4(0, 1, 0, 1), fw, fh, 3 * dpi_scaling());
295 if (changed || cross_changed) {
296 auto commands = image_commands_;
298 commands.push_back(cross_command_);
299 set_overlays(std::move(commands));
300 cross_overlay_visible_ = visible;
301 cross_geometry_dirty_ =
false;
305bool TutorialRealCamera::mouse_free_move_event(
int x,
int y,
int dx,
int dy,
int modifiers) {
310 if (current_view_ < 0 || current_view_ >= views_.size()) {
311 std::cerr <<
"Error: invalid view index (" << current_view_ <<
")" << std::endl;
316 framebuffer_size(fw, fh);
319 const float pixel_x = float(x) * fw / w;
320 const float pixel_y = float(y) * fh / h;
321 const CameraPara &cam = views_[current_view_];
322 const Rect image_rect = calculate_image_rect();
323 cross_visible_ =
false;
325 if (pixel_x >= image_rect.
x_min() && pixel_x <= image_rect.
x_max() &&
326 pixel_y >= image_rect.
y_min() && pixel_y <= image_rect.
y_max()) {
327 const float image_x =
328 (pixel_x - image_rect.
x_min()) / image_rect.
width() *
static_cast<float>(cam.w);
329 const float image_y =
330 (pixel_y - image_rect.
y_min()) / image_rect.
height() *
static_cast<float>(cam.h);
331 if (!ray_drawable_) {
333 add_drawable(std::shared_ptr<LinesDrawable>(ray_drawable_));
334 ray_drawable_->set_uniform_coloring(
vec4(0, 1, 0, 1.0f));
335 ray_drawable_->set_line_width(3.0f);
338 const vec3 pos = camera_pos(cam.R, cam.t);
339 const vec3 dir = pixel_to_ray(
static_cast<int>(image_x),
static_cast<int>(image_y), cam.fx, cam.fy, 0, cam.cx,
340 cam.cy, cam.R, cam.t,
true);
341 const std::vector<vec3> points = {pos, pos + dir};
342 ray_drawable_->update_vertex_buffer(points);
343 ray_drawable_->set_visible(
true);
347 ray_drawable_->set_visible(
false);
350 const vec3 p = point_under_pixel(x, y, found);
352 const vec2 q = point_to_pixel(p, cam.fx, cam.fy, 0, cam.cx, cam.cy, cam.R, cam.t);
355 if (q.x >= 0 && q.x <=
static_cast<float>(cam.w) && q.y >= 0 && q.y <=
static_cast<float>(cam.h)) {
356 const float screen_x = q.x /
static_cast<float>(cam.w) * image_rect.
width() + image_rect.
x_min();
357 const float screen_y = q.y /
static_cast<float>(cam.h) * image_rect.
height() + image_rect.
y_min();
359 const float size = 10 * dpi_scaling();
360 const std::vector<vec3> points = {
361 vec3(screen_x - size, screen_y, 0.5f),
vec3(screen_x + size, screen_y, 0.5f),
362 vec3(screen_x, screen_y - size, 0.5f),
vec3(screen_x, screen_y + size, 0.5f)};
363 cross_points_ = points;
364 cross_geometry_dirty_ =
true;
365 cross_visible_ =
true;
368 cross_visible_ =
false;
377vec3 TutorialRealCamera::camera_pos(
const mat3 &R,
const vec3 &t) {
381vec3 TutorialRealCamera::pixel_to_ray(
int image_x,
391 mat3 K(fx, skew, cx, 0, fy, cy, 0, 0, 1);
394 vec3 P =
inverse(K) *
vec3(
static_cast<float>(image_x),
static_cast<float>(image_y), 1);
405 return P - camera_pos(R, t);
417 mat3 K(fx, skew, cx, 0, fy, cy, 0, 0, 1);
436 return vec2(q.x, q.y);
void set_field_of_view(float fov)
Set the field of view of the camera.
void set_from_calibration(float fx, float fy, float skew, float cx, float cy, const mat3 &R, const vec3 &t, bool convert=true)
Defines the position(), orientation() and field_of_view() of the camera from calibrated camera intrin...
float scene_radius() const
Returns the radius of the scene observed by the Camera.
Definition camera.h:648
void set_orientation(const quat &q) const
Set the orientation of the camera.
void set_position(const vec3 &pos) const
Set the position of the camera.
float field_of_view() const
Returns the vertical field of view of the camera (in radians).
Definition camera.h:433
ManipulatedCameraFrame * frame() const
Returns the ManipulatedCameraFrame attached to the Camera.
Definition camera.h:707
mat4 world_matrix() const
Returns the world transformation matrix of the Frame.
FT & x_min()
Returns the minimum x-coordinate.
Definition rect.h:79
FT height() const
Returns the height of the rectangle.
Definition rect.h:146
FT width() const
Returns the width of the rectangle.
Definition rect.h:141
FT & x_max()
Returns the maximum x-coordinate.
Definition rect.h:89
FT & y_min()
Returns the minimum y-coordinate.
Definition rect.h:84
FT & y_max()
Returns the maximum y-coordinate.
Definition rect.h:94
@ CYLINDER
The lines will be drawn as cylinders.
Definition drawable_lines.h:60
Base class for matrix types.
Definition mat.h:64
Vec< N, T > col(size_t col) const
Returns the specified column as a vector.
Definition mat.h:728
void set_col(size_t col, const Vec< vN, T > &v)
Sets the specified column from a vector.
Definition mat.h:751
Mat< M, N, T > transpose(const Mat< N, M, T > &m)
Transposes a matrix.
Definition mat.h:1126
Mat< N, N, T > inverse(const Mat< N, N, T > &m)
Returns the inverse of an N x N (square) matrix.
Definition mat.h:1210
Texture addressing and filtering configuration.
Definition render_device.h:165
TextureFilter filter
Interpolation used when sampling between texels.
Definition render_device.h:169