Easy3D 3.0.0
Loading...
Searching...
No Matches
Tutorial_405_VirtualScanner

Simulating a 3D scanner: capturing the currently visible surface of a model as a point cloud.

Overview

This tutorial turns the viewer into a virtual range scanner. The user navigates to a viewpoint and presses 'space'; everything visible from that viewpoint (and only that) is captured as a new PointCloud and added to the scene. Repeating this from different viewpoints mimics acquiring multiple scans of a real object, the raw input of a typical 3D reconstruction pipeline. An optional Gaussian noise mode imitates sensor noise.

The technique

A range scanner (LiDAR, structured light, depth camera) measures the distance to the nearest surface along many viewing directions. Rendering already computes exactly that: the depth buffer stores, for every pixel, the nearest visible surface point — hidden surfaces are removed by the depth test. So a virtual scan is simply: render the scene, read back the depth buffer, and back-project each valid pixel into world space. The math is the inverse of the usual rendering pipeline: a pixel (x, y) with depth d is mapped to normalized device coordinates (2(x+0.5)/w - 1, 1 - 2(y+0.5)/h, 2d - 1), multiplied by the inverse model-view-projection matrix, and divided by the resulting homogeneous w. The half-pixel offsets sample pixel centers. Pixels with no geometry (background) are skipped, so the scan contains only visible surface samples — one point per pixel, like a depth image. Adding zero-mean Gaussian noise with a small standard deviation simulates the measurement error of a real scanner.

Easy3D API

Running it

Navigate with the mouse as usual. Press 'space' to capture a scan from the current view (a new model named "Virtual scan" appears); press 'n' to toggle Gaussian noise on the captured points. Scan from several viewpoints to build up multi-view coverage.

1
27#include "viewer.h"
28#include <easy3d/core/model.h>
29#include <easy3d/renderer/renderer.h>
30#include <easy3d/renderer/drawable_points.h>
31#include <easy3d/util/resource.h>
32#include <easy3d/util/initializer.h>
33
87using namespace easy3d;
88
89int main(int argc, char **argv) {
90 // Bootstrap Easy3D (logging, resource directory, ...). Must come first.
91 initialize();
92
93 // Our custom viewer: a Viewer subclass that captures a scan when 'space' is pressed.
94 TutorialVirtualScanner viewer(EXAMPLE_TITLE);
95
96 // The model to scan. add_model() centers and scales it to fit the scene (second argument).
97 const std::string file_name = resource::directory() + "/data/house/house.obj";
98 auto model = viewer.add_model(file_name, true);
99 if (!model) {
100 std::cerr << "failed to load model. Please make sure the file exists and format is correct" << std::endl;
101 return EXIT_FAILURE;
102 }
103
104 // "locks" is an auxiliary points drawable marking locked vertices (if the mesh has any).
105 // Hide it so such markers are not captured as part of the scanned surface.
106 auto d = model->renderer()->get_points_drawable("locks");
107 if (d)
108 d->set_visible(false);
109
110 // Enter the interactive loop (returns when the window is closed).
111 return viewer.run();
112}
Definition collider.cpp:182

The header file of the viewer class:

1
27#ifndef EASY3D_TUTORIAL_VIRTUAL_SCANNER_H
28#define EASY3D_TUTORIAL_VIRTUAL_SCANNER_H
29
30#include <easy3d/viewer/viewer.h>
31
40class TutorialVirtualScanner : public easy3d::Viewer {
41public:
42 // Installs the usage manual/hint and fixes the camera's up direction.
43 explicit TutorialVirtualScanner(const std::string &title = "VirtualScanner");
44
45protected:
46 // Handles 'space' (capture a scan) and 'n' (toggle noise); forwards other keys to Viewer.
47 bool key_press_event(int key, int modifiers) override;
48
49private:
50 bool add_noise_ = false;
51};
52
53#endif // EASY3D_TUTORIAL_VIRTUAL_SCANNER_H
The default viewer implementation for both OpenGL and Vulkan backends.
Definition viewer.h:143

The source file of the viewer class:

1
27#include "viewer.h"
28#include <easy3d/core/point_cloud.h>
29#include <easy3d/renderer/camera.h>
30#include <easy3d/renderer/manipulated_camera_frame.h>
31#include <easy3d/renderer/clipping_plane.h>
32#include <cmath>
33#include <easy3d/algo/gaussian_noise.h>
34
35using namespace easy3d;
36
37// \cond
38TutorialVirtualScanner::TutorialVirtualScanner(const std::string &title) : Viewer(title) {
39 // manual_ is the full help text (shown on demand); hint_ is the short HUD reminder.
40 manual_ =
41 "-------------- Virtual Scanner usage -------------- \n"
42 "- change the view using the mouse.\n"
43 "- press the 'Space' key to perform scanning. Everything (and only those) visible\n"
44 " will be captured in a point cloud.\n"
45 "- press 'n' to toggle Gaussian noise.\n"
46 "--------------------------------------------------- \n";
47 hint_ =
48 "press 'Space' to perform scanning\n"
49 "press 'n' to toggle Gaussian noise";
50 // Keep the world's "up" aligned with +Y so scans are captured in a natural orientation.
51 camera()->set_up_vector(easy3d::vec3(0, 1, 0));
52}
53
54// 'n' toggles sensor noise; 'space' performs the virtual scan. Other keys go to the base Viewer.
55bool TutorialVirtualScanner::key_press_event(int key, int modifiers) {
56 if (modifiers == 0 && key == KEY_N) {
57 add_noise_ = !add_noise_;
58 return true;
59 }
60 if (modifiers == 0 && key == KEY_SPACE) {
61 // The scan resolution equals the framebuffer resolution: one point per pixel.
62 int w, h;
63 framebuffer_size(w, h);
64 if (w <= 0 || h <= 0)
65 return true;
66 // Rendering maps world -> screen via the MVP; back-projection needs the inverse.
67 const auto inv = inverse(camera()->model_view_projection_matrix());
68 // Render the scene off screen and read back color, depth, and object IDs. The depth
69 // buffer already contains only the nearest (visible) surface — exactly what a range
70 // scanner measures. samples() requests the viewer's multisampling for the color.
71 const auto frame = capture(samples());
72 std::vector<vec3> points;
73 for (unsigned y = 0; y < frame.height; ++y)
74 for (unsigned x = 0; x < frame.width; ++x) {
75 const size_t pixel = size_t(y) * frame.width + x;
76 const float d = frame.depth[pixel];
77 // Skip background pixels (no object) and invalid/out-of-range depth values.
78 if (frame.ids[pixel].object == UINT32_MAX || !std::isfinite(d) || d < 0 || d >= 1)
79 continue;
80 // Back-project the pixel center: map (x, y, d) to normalized device
81 // coordinates in [-1, 1] (the +0.5 samples pixel centers; y is flipped
82 // because screen rows grow downward), then apply the inverse MVP.
83 const vec4 p = inv * vec4(2 * (float(x) + .5f) / frame.width - 1,
84 1 - 2 * (float(y) + .5f) / frame.height, 2 * d - 1, 1);
85 // Perspective division converts the homogeneous result to a world point.
86 if (std::isfinite(p.w) && p.w != 0)
87 points.emplace_back(p.x / p.w, p.y / p.w, p.z / p.w);
88 }
89 if (points.empty())
90 return true;
91 // Package the captured samples as a new point cloud model.
92 auto cloud = std::make_shared<easy3d::PointCloud>();
93 cloud->set_name("Virtual scan");
94 for (const auto &p : points)
95 cloud->add_vertex(p);
96 // Optionally imitate sensor noise: zero-mean Gaussian perturbation with a standard
97 // deviation scaled to the scene size, so it stays subtle regardless of model scale.
98 if (add_noise_)
99 easy3d::GaussianNoise::apply(cloud.get(), camera()->scene_radius() * .0001f);
100
101 add_model(cloud, true, false);
102 return true;
103 }
104 return Viewer::key_press_event(key, modifiers);
105}
106
107
108#if 0 // Do NOT delete!!! Will come back in a future release when APIs are ready.
109std::vector<vec3> Viewer::scan_visible_points(unsigned samples) const {
110 if (!samples || samples > 64 || (samples & (samples - 1))) // (samples & (samples - 1)) is a bitwise trick to check whether samples is a power of two
111 throw std::invalid_argument("invalid capture sample count");
112 Camera snapshot(*camera());
113 // Camera's copy constructor regenerates matrices from its parameters. Keep
114 // effective matrices too, including externally calibrated/custom cameras.
115 snapshot.frame()->set_pivot_point(camera()->pivot_point()); // do not re-adjust the copied ortho coefficient
116 snapshot.set_projection_matrix(camera()->projection_matrix());
117 snapshot.set_model_view_matrix(camera()->model_view_matrix());
118 const auto inv = transform::checked_inverse(snapshot.model_view_projection_matrix());
119 const auto frame = impl_->capture(snapshot, background_color(), unsigned(supported_sample_count(int(samples))),
120 framebuffer_width(), framebuffer_height());
121 std::vector<vec3> points;
122 points.reserve(std::count_if(frame.depth.begin(), frame.depth.end(), [](float d) { return d >= 0 && d < 1; }));
123 for (unsigned y = 0; y < frame.height; ++y)
124 for (unsigned x = 0; x < frame.width; ++x) {
125 const size_t pixel = size_t(y) * frame.width + x;
126 const float d = frame.depth[pixel];
127 if (frame.ids[pixel].object == UINT32_MAX || !std::isfinite(d) || d < 0 || d >= 1)
128 continue;
129 const int viewport[] = {0, 0, int(frame.width), int(frame.height)};
130 points.push_back(transform::unproject_inverse(vec3(x + .5f, y + .5f, d), inv, viewport, false));
131 }
132 return points;
133}
134#endif
135
136// \endcond
A perspective or orthographic camera.
Definition camera.h:142
static void apply(SurfaceMesh *mesh, float sigma, bool preserve_boundary=false)
Add Gaussian noise (that has a normal distribution) to the surface mesh.
Definition gaussian_noise.cpp:41
EASY3D_UTIL_EXPORT vec4 background_color
Background color of the viewer.
mat4 viewport(float w, float h)
Definition transform.cpp:130
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
See also
Viewer, PointCloud, Camera, GaussianNoise, Tutorial_403_PointSelection