Commit 97a92e2d authored by Alexander Alekhin's avatar Alexander Alekhin

viz: move samples/tutorials to opencv_contrib

parent 4d2a81f3
......@@ -26,7 +26,15 @@ endif()
ocv_warnings_disable(CMAKE_CXX_FLAGS -Winconsistent-missing-override -Wsuggest-override)
ocv_define_module(viz opencv_core WRAP python)
ocv_add_module(viz opencv_core WRAP python)
ocv_glob_module_sources()
ocv_module_include_directories()
ocv_create_module()
ocv_add_accuracy_tests()
ocv_add_perf_tests()
ocv_add_samples(opencv_imgproc opencv_calib3d opencv_features2d opencv_flann)
ocv_target_link_libraries(${the_module} LINK_PRIVATE ${VTK_LIBRARIES})
if(APPLE AND BUILD_opencv_viz)
......
/**
* @file creating_widgets.cpp
* @brief Creating custom widgets using VTK
* @author Ozan Cagri Tonkal
*/
#ifndef USE_VTK
#include <iostream>
int main()
{
std::cout << "This sample requires direct compilation with VTK. Stop" << std::endl;
return 0;
}
#else
#include <opencv2/viz.hpp>
#include <opencv2/viz/widget_accessor.hpp>
#include <iostream>
#include <vtkPoints.h>
#include <vtkTriangle.h>
#include <vtkCellArray.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkIdList.h>
#include <vtkActor.h>
#include <vtkProp.h>
using namespace cv;
using namespace std;
/**
* @function help
* @brief Display instructions to use this tutorial program
*/
static void help()
{
cout
<< "--------------------------------------------------------------------------" << endl
<< "This program shows how to create a custom widget. You can create your own "
<< "widgets by extending Widget2D/Widget3D, and with the help of WidgetAccessor." << endl
<< "Usage:" << endl
<< "./creating_widgets" << endl
<< endl;
}
/**
* @class TriangleWidget
* @brief Defining our own 3D Triangle widget
*/
class WTriangle : public viz::Widget3D
{
public:
WTriangle(const Point3f &pt1, const Point3f &pt2, const Point3f &pt3, const viz::Color & color = viz::Color::white());
};
/**
* @function TriangleWidget::TriangleWidget
* @brief Constructor
*/
WTriangle::WTriangle(const Point3f &pt1, const Point3f &pt2, const Point3f &pt3, const viz::Color & color)
{
// Create a triangle
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
points->InsertNextPoint(pt1.x, pt1.y, pt1.z);
points->InsertNextPoint(pt2.x, pt2.y, pt2.z);
points->InsertNextPoint(pt3.x, pt3.y, pt3.z);
vtkSmartPointer<vtkTriangle> triangle = vtkSmartPointer<vtkTriangle>::New();
triangle->GetPointIds()->SetId(0,0);
triangle->GetPointIds()->SetId(1,1);
triangle->GetPointIds()->SetId(2,2);
vtkSmartPointer<vtkCellArray> cells = vtkSmartPointer<vtkCellArray>::New();
cells->InsertNextCell(triangle);
// Create a polydata object
vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New();
// Add the geometry and topology to the polydata
polyData->SetPoints(points);
polyData->SetPolys(cells);
// Create mapper and actor
vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
#if VTK_MAJOR_VERSION <= 5
mapper->SetInput(polyData);
#else
mapper->SetInputData(polyData);
#endif
vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
// Store this actor in the widget in order that visualizer can access it
viz::WidgetAccessor::setProp(*this, actor);
// Set the color of the widget. This has to be called after WidgetAccessor.
setColor(color);
}
/**
* @function main
*/
int main()
{
help();
/// Create a window
viz::Viz3d myWindow("Creating Widgets");
/// Create a triangle widget
WTriangle tw(Point3f(0.0,0.0,0.0), Point3f(1.0,1.0,1.0), Point3f(0.0,1.0,0.0), viz::Color::red());
/// Show widget in the visualizer window
myWindow.showWidget("TRIANGLE", tw);
/// Start event loop
myWindow.spin();
return 0;
}
#endif
This diff is collapsed.
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
using namespace std;
using namespace cv;
#ifdef HAVE_OPENCV_VIZ
#include <opencv2/viz.hpp>
const String keys =
"{Aide h usage ? help | | print this message }"
"{@arg1 | | Full path to color imag (3 channels)}"
;
struct Histo3DData {
Mat histogram;
int seuil;
double threshold;
Ptr<viz::Viz3d> fen3D;
int nbWidget;
bool status;
double maxH;
int code;
};
void DrawHistogram3D(Histo3DData &);
void AddSlidebar(String sliderName, String windowName, int sliderMin, int sliderMax, int valeurDefaut, int *sliderVal, void(*f)(int, void *), void *r);
void UpdateThreshold(int , void * r);
void KeyboardViz3d(const viz::KeyboardEvent &w, void *t);
void DrawHistogram3D(Histo3DData &h)
{
//! [get_cube_size]
int planSize = (int)h.histogram.step1(0);
int cols = (int)h.histogram.step1(1);
int rows = (int)planSize / cols;
int plans = (int)h.histogram.total() / planSize;
h.fen3D->removeAllWidgets();
h.nbWidget=0;
if (h.nbWidget==0)
h.fen3D->showWidget("Axis", viz::WCoordinateSystem(10));
//! [get_cube_size]
//! [get_cube_values]
for (int k = 0; k < plans; k++)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
double x = h.histogram.at<float>(k, i, j);
if (x >= h.threshold)
{
double r=std::max(x/h.maxH,0.1);
viz::WCube s(Point3d(k - r / 2, i - r / 2, j - r / 2), Point3d(k + r / 2, i + r / 2, j + r / 2), false, viz::Color(j / double(plans) * 255, i / double(rows) * 255, k / double(cols) * 255));
h.fen3D->showWidget(format("I3d%d", h.nbWidget++), s);
}
}
}
}
//! [get_cube_values]
h.status = false;
}
//! [viz_keyboard_callback]
void KeyboardViz3d(const viz::KeyboardEvent &w, void *t)
{
Histo3DData *x=(Histo3DData *)t;
if (w.action)
cout << "you pressed "<< w.symbol<< " in viz window "<<x->fen3D->getWindowName()<<"\n";
x->code= w.code;
switch (w.code) {
case '/':
x->status=true;
x->threshold *= 0.9;
break;
case '*':
x->status = true;
x->threshold *= 1.1;
break;
}
if (x->status)
{
cout << x->threshold << "\n";
DrawHistogram3D(*x);
}
}
//! [viz_keyboard_callback]
void AddSlidebar(String sliderName, String windowName, int sliderMin, int sliderMax, int defaultSlider, int *sliderVal, void(*f)(int, void *), void *r)
{
createTrackbar(sliderName, windowName, sliderVal, 1, f, r);
setTrackbarMin(sliderName, windowName, sliderMin);
setTrackbarMax(sliderName, windowName, sliderMax);
setTrackbarPos(sliderName, windowName, defaultSlider);
}
void UpdateThreshold(int , void * r)
{
Histo3DData *h = (Histo3DData *)r;
h->status=true;
h->threshold = h->seuil/1000000.0;
cout<<"Widget : "<<h->nbWidget<<","<< h->threshold<<"\n";
}
int main (int argc,char **argv)
{
//! [command_line_parser]
CommandLineParser parser(argc, argv, keys);
if (parser.has("help"))
{
parser.printMessage();
return 0;
}
String nomFic = parser.get<String>(0);
Mat img;
if (nomFic.length() != 0)
{
img = imread(nomFic, IMREAD_COLOR);
if (img.empty())
{
cout << "Image does not exist!";
return 0;
}
}
//! [command_line_parser]
//! [synthetic_image]
else
{
img = Mat(512,512,CV_8UC3);
parser.printMessage();
RNG r;
r.fill(img(Rect(0, 0, 256, 256)), RNG::NORMAL, Vec3b(60, 40, 50), Vec3b(10, 5, 20));
r.fill(img(Rect(256, 0, 256, 256)), RNG::NORMAL, Vec3b(160, 10, 50), Vec3b(20, 5, 10));
r.fill(img(Rect(0, 256, 256, 256)), RNG::NORMAL, Vec3b(90, 100, 50), Vec3b(10, 20, 20));
r.fill(img(Rect(256, 256, 256, 256)), RNG::NORMAL, Vec3b(100, 10, 150), Vec3b(10, 5, 40));
}
//! [synthetic_image]
//! [calchist_for_histo3d]
Histo3DData h;
h.status=true;
h.seuil=90;
h.threshold= h.seuil/1000000.0;
float hRange[] = { 0, 256 };
const float* etendu[] = { hRange, hRange,hRange };
int hBins = 32;
int histSize[] = { hBins, hBins , hBins };
int channel[] = { 2, 1,0 };
calcHist(&img, 1, channel, Mat(), h.histogram, 3, histSize, etendu, true, false);
normalize(h.histogram, h.histogram, 100.0/(img.total()), 0, NORM_MINMAX, -1, Mat());
minMaxIdx(h.histogram,NULL,&h.maxH,NULL,NULL);
//! [calchist_for_histo3d]
//! [slide_bar_for_thresh]
namedWindow("Image");
imshow("Image",img);
AddSlidebar("threshold","Image",0,100,h.seuil,&h.seuil, UpdateThreshold,&h);
waitKey(30);
//! [slide_bar_for_thresh]
//! [manage_viz_imshow_window]
h.fen3D = makePtr<viz::Viz3d>("3D Histogram");
h.nbWidget=0;
h.fen3D->registerKeyboardCallback(KeyboardViz3d,&h);
DrawHistogram3D(h);
while (h.code!=27)
{
h.fen3D->spinOnce(1);
if (h.status)
DrawHistogram3D(h);
if (h.code!=27)
h.code= waitKey(30);
}
//! [manage_viz_imshow_window]
return 0;
}
#else
int main(int argc, char **argv)
{
cout << " you need VIZ module\n";
return 0;
}
#endif
/**
* @file launching_viz.cpp
* @brief Launching visualization window
* @author Ozan Cagri Tonkal
*/
#include <opencv2/viz.hpp>
#include <iostream>
using namespace cv;
using namespace std;
/**
* @function help
* @brief Display instructions to use this tutorial program
*/
static void help()
{
cout
<< "--------------------------------------------------------------------------" << endl
<< "This program shows how to launch a 3D visualization window. You can stop event loop to continue executing. "
<< "You can access the same window via its name. You can run event loop for a given period of time. " << endl
<< "Usage:" << endl
<< "./launching_viz" << endl
<< endl;
}
/**
* @function main
*/
int main()
{
help();
/// Create a window
viz::Viz3d myWindow("Viz Demo");
/// Start event loop
myWindow.spin();
/// Event loop is over when pressed q, Q, e, E
cout << "First event loop is over" << endl;
/// Access window via its name
viz::Viz3d sameWindow = viz::getWindowByName("Viz Demo");
/// Start event loop
sameWindow.spin();
/// Event loop is over when pressed q, Q, e, E
cout << "Second event loop is over" << endl;
/// Event loop is over when pressed q, Q, e, E
/// Start event loop once for 1 millisecond
sameWindow.spinOnce(1, true);
while(!sameWindow.wasStopped())
{
/// Interact with window
/// Event loop for 1 millisecond
sameWindow.spinOnce(1, true);
}
/// Once more event loop is stopped
cout << "Last event loop is over" << endl;
return 0;
}
/**
* @file transformations.cpp
* @brief Visualizing cloud in different positions, coordinate frames, camera frustums
* @author Ozan Cagri Tonkal
*/
#include <opencv2/viz.hpp>
#include <iostream>
#include <fstream>
using namespace cv;
using namespace std;
/**
* @function help
* @brief Display instructions to use this tutorial program
*/
static void help()
{
cout
<< "--------------------------------------------------------------------------" << endl
<< "This program shows how to use makeTransformToGlobal() to compute required pose,"
<< "how to use makeCameraPose and Viz3d::setViewerPose. You can observe the scene "
<< "from camera point of view (C) or global point of view (G)" << endl
<< "Usage:" << endl
<< "./transformations [ G | C ]" << endl
<< endl;
}
/**
* @function cvcloud_load
* @brief load bunny.ply
*/
static Mat cvcloud_load()
{
Mat cloud(1, 1889, CV_32FC3);
ifstream ifs("bunny.ply");
string str;
for(size_t i = 0; i < 12; ++i)
getline(ifs, str);
Point3f* data = cloud.ptr<cv::Point3f>();
float dummy1, dummy2;
for(size_t i = 0; i < 1889; ++i)
ifs >> data[i].x >> data[i].y >> data[i].z >> dummy1 >> dummy2;
cloud *= 5.0f;
return cloud;
}
/**
* @function main
*/
int main(int argn, char **argv)
{
help();
if (argn < 2)
{
cout << "Missing arguments." << endl;
return 1;
}
bool camera_pov = (argv[1][0] == 'C');
/// Create a window
viz::Viz3d myWindow("Coordinate Frame");
/// Add coordinate axes
myWindow.showWidget("Coordinate Widget", viz::WCoordinateSystem());
/// Let's assume camera has the following properties
Vec3f cam_pos(3.0f,3.0f,3.0f), cam_focal_point(3.0f,3.0f,2.0f), cam_y_dir(-1.0f,0.0f,0.0f);
/// We can get the pose of the cam using makeCameraPose
Affine3f cam_pose = viz::makeCameraPose(cam_pos, cam_focal_point, cam_y_dir);
/// We can get the transformation matrix from camera coordinate system to global using
/// - makeTransformToGlobal. We need the axes of the camera
Affine3f transform = viz::makeTransformToGlobal(Vec3f(0.0f,-1.0f,0.0f), Vec3f(-1.0f,0.0f,0.0f), Vec3f(0.0f,0.0f,-1.0f), cam_pos);
/// Create a cloud widget.
Mat bunny_cloud = cvcloud_load();
viz::WCloud cloud_widget(bunny_cloud, viz::Color::green());
/// Pose of the widget in camera frame
Affine3f cloud_pose = Affine3f().translate(Vec3f(0.0f,0.0f,3.0f));
/// Pose of the widget in global frame
Affine3f cloud_pose_global = transform * cloud_pose;
/// Visualize camera frame
if (!camera_pov)
{
viz::WCameraPosition cpw(0.5); // Coordinate axes
viz::WCameraPosition cpw_frustum(Vec2f(0.889484, 0.523599)); // Camera frustum
myWindow.showWidget("CPW", cpw, cam_pose);
myWindow.showWidget("CPW_FRUSTUM", cpw_frustum, cam_pose);
}
/// Visualize widget
myWindow.showWidget("bunny", cloud_widget, cloud_pose_global);
/// Set the viewer pose to that of camera
if (camera_pov)
myWindow.setViewerPose(cam_pose);
/// Start event loop.
myWindow.spin();
return 0;
}
/**
* @file widget_pose.cpp
* @brief Setting pose of a widget
* @author Ozan Cagri Tonkal
*/
#include <opencv2/viz.hpp>
#include <opencv2/calib3d.hpp>
#include <iostream>
using namespace cv;
using namespace std;
/**
* @function help
* @brief Display instructions to use this tutorial program
*/
static void help()
{
cout
<< "--------------------------------------------------------------------------" << endl
<< "This program shows how to visualize a cube rotated around (1,1,1) and shifted "
<< "using Rodrigues vector." << endl
<< "Usage:" << endl
<< "./widget_pose" << endl
<< endl;
}
/**
* @function main
*/
int main()
{
help();
/// Create a window
viz::Viz3d myWindow("Coordinate Frame");
/// Add coordinate axes
myWindow.showWidget("Coordinate Widget", viz::WCoordinateSystem());
/// Add line to represent (1,1,1) axis
viz::WLine axis(Point3f(-1.0f,-1.0f,-1.0f), Point3f(1.0f,1.0f,1.0f));
axis.setRenderingProperty(viz::LINE_WIDTH, 4.0);
myWindow.showWidget("Line Widget", axis);
/// Construct a cube widget
viz::WCube cube_widget(Point3f(0.5,0.5,0.0), Point3f(0.0,0.0,-0.5), true, viz::Color::blue());
cube_widget.setRenderingProperty(viz::LINE_WIDTH, 4.0);
myWindow.showWidget("Cube Widget", cube_widget);
/// Rodrigues vector
Mat rot_vec = Mat::zeros(1,3,CV_32F);
float translation_phase = 0.0, translation = 0.0;
while(!myWindow.wasStopped())
{
/* Rotation using rodrigues */
/// Rotate around (1,1,1)
rot_vec.at<float>(0,0) += (float)CV_PI * 0.01f;
rot_vec.at<float>(0,1) += (float)CV_PI * 0.01f;
rot_vec.at<float>(0,2) += (float)CV_PI * 0.01f;
/// Shift on (1,1,1)
translation_phase += (float)CV_PI * 0.01f;
translation = sin(translation_phase);
Mat rot_mat;
Rodrigues(rot_vec, rot_mat);
/// Construct pose
Affine3f pose(rot_mat, Vec3f(translation, translation, translation));
myWindow.setWidgetPose("Cube Widget", pose);
myWindow.spinOnce(1, true);
}
return 0;
}
Creating Widgets {#tutorial_creating_widgets}
================
Goal
----
In this tutorial you will learn how to
- Create your own widgets using WidgetAccessor and VTK.
- Show your widget in the visualization window.
Code
----
You can download the code from [here ](https://github.com/opencv/opencv_contrib/tree/master/modules/viz/samples/creating_widgets.cpp).
@include viz/samples/creating_widgets.cpp
Explanation
-----------
Here is the general structure of the program:
- Extend Widget3D class to create a new 3D widget.
@code{.cpp}
class WTriangle : public viz::Widget3D
{
public:
WTriangle(const Point3f &pt1, const Point3f &pt2, const Point3f &pt3, const viz::Color & color = viz::Color::white());
};
@endcode
- Assign a VTK actor to the widget.
@code{.cpp}
// Store this actor in the widget in order that visualizer can access it
viz::WidgetAccessor::setProp(*this, actor);
@endcode
- Set color of the widget.
@code{.cpp}
// Set the color of the widget. This has to be called after WidgetAccessor.
setColor(color);
@endcode
- Construct a triangle widget and display it in the window.
@code{.cpp}
/// Create a triangle widget
WTriangle tw(Point3f(0.0,0.0,0.0), Point3f(1.0,1.0,1.0), Point3f(0.0,1.0,0.0), viz::Color::red());
/// Show widget in the visualizer window
myWindow.showWidget("TRIANGLE", tw);
@endcode
Results
-------
Here is the result of the program.
![](images/red_triangle.png)
Creating a 3D histogram {#tutorial_histo3D}
================
Goal
----
In this tutorial you will learn how to
- Create your own callback keyboard function for viz window.
- Show your 3D histogram in a viz window.
Code
----
You can download the code from [here ](https://github.com/opencv/opencv_contrib/tree/master/modules/viz/samples/histo3D.cpp).
@include viz/samples/histo3D.cpp
Explanation
-----------
Here is the general structure of the program:
- You can give full path to an image in command line
@snippet histo3D.cpp command_line_parser
or without path, a synthetic image is generated with pixel values are a gaussian distribution @ref cv::RNG::fill center(60+/-10,40+/-5,50+/-20) in first quadrant,
(160+/-20,10+/-5,50+/-10) in second quadrant, (90+/-10,100+/-20,50+/-20) in third quadrant, (100+/-10,10+/-5,150+/-40) in last quadrant.
@snippet histo3D.cpp synthetic_image
Image tridimensional histogram is calculated using opencv @ref cv::calcHist and @ref cv::normalize between 0 and 100.
@snippet histo3D.cpp calchist_for_histo3d
channel are 2, 1 and 0 to synchronise color with Viz axis color in objetc cv::viz::WCoordinateSystem.
A slidebar is inserted in image window. Init slidebar value is 90, it means that only histogram cell greater than 9/100000.0 (23 pixels for an 512X512 pixels) will be display.
@snippet histo3D.cpp slide_bar_for_thresh
We are ready to open a viz window with a callback function to capture keyboard event in viz window. Using @ref cv::viz::Viz3d::spinOnce enable keyboard event to be capture in @ref cv::imshow window too.
@snippet histo3D.cpp manage_viz_imshow_window
The function DrawHistogram3D processes histogram Mat to display it in a Viz window. Number of plan, row and column in [three dimensional Mat](@ref CVMat_Details ) can be found using this code :
@snippet histo3D.cpp get_cube_size
To get histogram value at a specific location we use @ref cv::Mat::at(int i0,int i1, int i2) method with three arguments k, i and j where k is plane number, i row number and j column number.
@snippet histo3D.cpp get_cube_values
- Callback function
Principle are as mouse callback function. Key code pressed is in field code of class @ref cv::viz::KeyboardEvent.
@snippet histo3D.cpp viz_keyboard_callback
Results
-------
Here is the result of the program with no argument and threshold equal to 50.
![](images/histo50.png)
Launching Viz {#tutorial_launching_viz}
=============
Goal
----
In this tutorial you will learn how to
- Open a visualization window.
- Access a window by its name.
- Start event loop.
- Start event loop for a given amount of time.
Code
----
You can download the code from [here ](https://github.com/opencv/opencv_contrib/tree/master/modules/viz/samples/launching_viz.cpp).
@include viz/samples/launching_viz.cpp
Explanation
-----------
Here is the general structure of the program:
- Create a window.
@code{.cpp}
/// Create a window
viz::Viz3d myWindow("Viz Demo");
@endcode
- Start event loop. This event loop will run until user terminates it by pressing **e**, **E**,
**q**, **Q**.
@code{.cpp}
/// Start event loop
myWindow.spin();
@endcode
- Access same window via its name. Since windows are implicitly shared, **sameWindow** is exactly
the same with **myWindow**. If the name does not exist, a new window is created.
@code{.cpp}
/// Access window via its name
viz::Viz3d sameWindow = viz::getWindowByName("Viz Demo");
@endcode
- Start a controlled event loop. Once it starts, **wasStopped** is set to false. Inside the while
loop, in each iteration, **spinOnce** is called to prevent event loop from completely stopping.
Inside the while loop, user can execute other statements including those which interact with the
window.
@code{.cpp}
/// Event loop is over when pressed q, Q, e, E
/// Start event loop once for 1 millisecond
sameWindow.spinOnce(1, true);
while(!sameWindow.wasStopped())
{
/// Interact with window
/// Event loop for 1 millisecond
sameWindow.spinOnce(1, true);
}
@endcode
Results
-------
Here is the result of the program.
![](images/window_demo.png)
OpenCV Viz {#tutorial_table_of_content_viz}
==========
- @subpage tutorial_launching_viz
*Compatibility:* \> OpenCV 3.0.0
*Author:* Ozan Tonkal
You will learn how to launch a viz window.
- @subpage tutorial_widget_pose
*Compatibility:* \> OpenCV 3.0.0
*Author:* Ozan Tonkal
You will learn how to change pose of a widget.
- @subpage tutorial_transformations
*Compatibility:* \> OpenCV 3.0.0
*Author:* Ozan Tonkal
You will learn how to transform between global and camera frames.
- @subpage tutorial_creating_widgets
*Compatibility:* \> OpenCV 3.0.0
*Author:* Ozan Tonkal
You will learn how to create your own widgets.
- @subpage tutorial_histo3D
*Compatibility:* \> OpenCV 3.0.0
*Author:* Laurent Berger
You will learn how to plot a 3D histogram.
Transformations {#tutorial_transformations}
===============
Goal
----
In this tutorial you will learn how to
- How to use makeTransformToGlobal to compute pose
- How to use makeCameraPose and Viz3d::setViewerPose
- How to visualize camera position by axes and by viewing frustum
Code
----
You can download the code from [here ](https://github.com/opencv/opencv_contrib/tree/master/modules/viz/samples/transformations.cpp).
@include viz/samples/transformations.cpp
Explanation
-----------
Here is the general structure of the program:
- Create a visualization window.
@code{.cpp}
/// Create a window
viz::Viz3d myWindow("Transformations");
@endcode
- Get camera pose from camera position, camera focal point and y direction.
@code{.cpp}
/// Let's assume camera has the following properties
Point3f cam_pos(3.0f,3.0f,3.0f), cam_focal_point(3.0f,3.0f,2.0f), cam_y_dir(-1.0f,0.0f,0.0f);
/// We can get the pose of the cam using makeCameraPose
Affine3f cam_pose = viz::makeCameraPose(cam_pos, cam_focal_point, cam_y_dir);
@endcode
- Obtain transform matrix knowing the axes of camera coordinate system.
@code{.cpp}
/// We can get the transformation matrix from camera coordinate system to global using
/// - makeTransformToGlobal. We need the axes of the camera
Affine3f transform = viz::makeTransformToGlobal(Vec3f(0.0f,-1.0f,0.0f), Vec3f(-1.0f,0.0f,0.0f), Vec3f(0.0f,0.0f,-1.0f), cam_pos);
@endcode
- Create a cloud widget from bunny.ply file
@code{.cpp}
/// Create a cloud widget.
Mat bunny_cloud = cvcloud_load();
viz::WCloud cloud_widget(bunny_cloud, viz::Color::green());
@endcode
- Given the pose in camera coordinate system, estimate the global pose.
@code{.cpp}
/// Pose of the widget in camera frame
Affine3f cloud_pose = Affine3f().translate(Vec3f(0.0f,0.0f,3.0f));
/// Pose of the widget in global frame
Affine3f cloud_pose_global = transform * cloud_pose;
@endcode
- If the view point is set to be global, visualize camera coordinate frame and viewing frustum.
@code{.cpp}
/// Visualize camera frame
if (!camera_pov)
{
viz::WCameraPosition cpw(0.5); // Coordinate axes
viz::WCameraPosition cpw_frustum(Vec2f(0.889484, 0.523599)); // Camera frustum
myWindow.showWidget("CPW", cpw, cam_pose);
myWindow.showWidget("CPW_FRUSTUM", cpw_frustum, cam_pose);
}
@endcode
- Visualize the cloud widget with the estimated global pose
@code{.cpp}
/// Visualize widget
myWindow.showWidget("bunny", cloud_widget, cloud_pose_global);
@endcode
- If the view point is set to be camera's, set viewer pose to **cam_pose**.
@code{.cpp}
/// Set the viewer pose to that of camera
if (camera_pov)
myWindow.setViewerPose(cam_pose);
@endcode
Results
-------
-# Here is the result from the camera point of view.
![](images/camera_view_point.png)
-# Here is the result from global point of view.
![](images/global_view_point.png)
Pose of a widget {#tutorial_widget_pose}
================
Goal
----
In this tutorial you will learn how to
- Add widgets to the visualization window
- Use Affine3 to set pose of a widget
- Rotating and translating a widget along an axis
Code
----
You can download the code from [here ](https://github.com/opencv/opencv_contrib/tree/master/modules/viz/samples/widget_pose.cpp).
@include viz/samples/widget_pose.cpp
Explanation
-----------
Here is the general structure of the program:
- Create a visualization window.
@code{.cpp}
/// Create a window
viz::Viz3d myWindow("Coordinate Frame");
@endcode
- Show coordinate axes in the window using CoordinateSystemWidget.
@code{.cpp}
/// Add coordinate axes
myWindow.showWidget("Coordinate Widget", viz::WCoordinateSystem());
@endcode
- Display a line representing the axis (1,1,1).
@code{.cpp}
/// Add line to represent (1,1,1) axis
viz::WLine axis(Point3f(-1.0f,-1.0f,-1.0f), Point3f(1.0f,1.0f,1.0f));
axis.setRenderingProperty(viz::LINE_WIDTH, 4.0);
myWindow.showWidget("Line Widget", axis);
@endcode
- Construct a cube.
@code{.cpp}
/// Construct a cube widget
viz::WCube cube_widget(Point3f(0.5,0.5,0.0), Point3f(0.0,0.0,-0.5), true, viz::Color::blue());
cube_widget.setRenderingProperty(viz::LINE_WIDTH, 4.0);
myWindow.showWidget("Cube Widget", cube_widget);
@endcode
- Create rotation matrix from rodrigues vector
@code{.cpp}
/// Rotate around (1,1,1)
rot_vec.at<float>(0,0) += CV_PI * 0.01f;
rot_vec.at<float>(0,1) += CV_PI * 0.01f;
rot_vec.at<float>(0,2) += CV_PI * 0.01f;
...
Mat rot_mat;
Rodrigues(rot_vec, rot_mat);
@endcode
- Use Affine3f to set pose of the cube.
@code{.cpp}
/// Construct pose
Affine3f pose(rot_mat, Vec3f(translation, translation, translation));
myWindow.setWidgetPose("Cube Widget", pose);
@endcode
- Animate the rotation using wasStopped and spinOnce
@code{.cpp}
while(!myWindow.wasStopped())
{
...
myWindow.spinOnce(1, true);
}
@endcode
Results
-------
Here is the result of the program.
\htmlonly
<div align="center">
<iframe width="420" height="315" src="https://www.youtube.com/embed/22HKMN657U0" frameborder="0" allowfullscreen></iframe>
</div>
\endhtmlonly
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment