提交 787f5236 编写于 作者: A Alexander Alekhin

viz: move to opencv_contrib

上级 b17e1531
if(NOT HAVE_VTK)
ocv_module_disable(viz)
endif()
set(the_description "Viz")
include(${VTK_USE_FILE})
if(NOT BUILD_SHARED_LIBS)
# We observed conflict between builtin 3rdparty libraries and
# system-wide similar libraries (but with different versions) from VTK dependencies
set(_conflicts "")
foreach(dep ${VTK_LIBRARIES})
if(("${dep}" MATCHES "libz\\." AND BUILD_ZLIB)
OR ("${dep}" MATCHES "libjpeg\\." AND BUILD_JPEG)
OR ("${dep}" MATCHES "libpng\\." AND BUILD_PNG)
OR ("${dep}" MATCHES "libtiff\\." AND BUILD_TIFF)
)
list(APPEND _conflicts "${dep}")
endif()
endforeach()
if(_conflicts)
message(STATUS "Disabling VIZ module due to conflicts with VTK dependencies: ${_conflicts}")
ocv_module_disable(viz)
endif()
endif()
ocv_warnings_disable(CMAKE_CXX_FLAGS -Winconsistent-missing-override -Wsuggest-override)
ocv_define_module(viz opencv_core WRAP python)
ocv_target_link_libraries(${the_module} LINK_PRIVATE ${VTK_LIBRARIES})
if(APPLE AND BUILD_opencv_viz)
ocv_target_link_libraries(${the_module} LINK_PRIVATE "-framework Cocoa")
endif()
if(TARGET opencv_test_viz)
set_target_properties(opencv_test_viz PROPERTIES MACOSX_BUNDLE TRUE)
endif()
此差异由.gitattributes 抑制。
此差异由.gitattributes 抑制。
此差异由.gitattributes 抑制。
此差异由.gitattributes 抑制。
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
// Authors:
// * Ozan Tonkal, ozantonkal@gmail.com
// * Anatoly Baksheev, Itseez Inc. myname.mysurname <> mycompany.com
//
//M*/
#ifndef OPENCV_VIZ_HPP
#define OPENCV_VIZ_HPP
#include <opencv2/viz/types.hpp>
#include <opencv2/viz/widgets.hpp>
#include <opencv2/viz/viz3d.hpp>
#include <opencv2/viz/vizcore.hpp>
/**
@defgroup viz 3D Visualizer
This section describes 3D visualization window as well as classes and methods that are used to
interact with it.
3D visualization window (see Viz3d) is used to display widgets (see Widget), and it provides several
methods to interact with scene and widgets.
@{
@defgroup viz_widget Widget
In this section, the widget framework is explained. Widgets represent 2D or 3D objects, varying from
simple ones such as lines to complex ones such as point clouds and meshes.
Widgets are **implicitly shared**. Therefore, one can add a widget to the scene, and modify the
widget without re-adding the widget.
@code
// Create a cloud widget
viz::WCloud cw(cloud, viz::Color::red());
// Display it in a window
myWindow.showWidget("CloudWidget1", cw);
// Modify it, and it will be modified in the window.
cw.setColor(viz::Color::yellow());
@endcode
@}
*/
#endif /* OPENCV_VIZ_HPP */
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
// Authors:
// * Ozan Tonkal, ozantonkal@gmail.com
// * Anatoly Baksheev, Itseez Inc. myname.mysurname <> mycompany.com
//
//M*/
#ifndef OPENCV_VIZ_TYPES_HPP
#define OPENCV_VIZ_TYPES_HPP
#include <string>
#include <opencv2/core.hpp>
#include <opencv2/core/affine.hpp>
namespace cv
{
namespace viz
{
//! @addtogroup viz
//! @{
/** @brief This class represents color in BGR order.
*/
class Color : public Scalar
{
public:
Color();
//! The three channels will have the same value equal to gray.
Color(double gray);
Color(double blue, double green, double red);
Color(const Scalar& color);
operator Vec3b() const;
static Color black();
static Color blue();
static Color green();
static Color cyan();
static Color red();
static Color magenta();
static Color yellow();
static Color white();
static Color gray();
static Color mlab();
static Color navy();
static Color olive();
static Color maroon();
static Color teal();
static Color rose();
static Color azure();
static Color lime();
static Color gold();
static Color brown();
static Color orange();
static Color chartreuse();
static Color orange_red();
static Color purple();
static Color indigo();
static Color pink();
static Color cherry();
static Color bluberry();
static Color raspberry();
static Color silver();
static Color violet();
static Color apricot();
static Color turquoise();
static Color celestial_blue();
static Color amethyst();
static Color not_set();
};
/** @brief This class wraps mesh attributes, and it can load a mesh from a ply file. :
*/
class CV_EXPORTS Mesh
{
public:
enum {
LOAD_AUTO = 0,
LOAD_PLY = 1,
LOAD_OBJ = 2
};
Mat cloud; //!< point coordinates of type CV_32FC3 or CV_64FC3 with only 1 row
Mat colors; //!< point color of type CV_8UC3 or CV_8UC4 with only 1 row
Mat normals; //!< point normals of type CV_32FC3, CV_32FC4, CV_64FC3 or CV_64FC4 with only 1 row
//! Raw integer list of the form: (n,id1,id2,...,idn, n,id1,id2,...,idn, ...)
//! where n is the number of points in the polygon, and id is a zero-offset index into an associated cloud.
Mat polygons; //!< CV_32SC1 with only 1 row
Mat texture;
Mat tcoords; //!< CV_32FC2 or CV_64FC2 with only 1 row
/** @brief Loads a mesh from a ply or a obj file.
@param file File name
@param type File type (for now only PLY and OBJ are supported)
**File type** can be one of the following:
- **LOAD_PLY**
- **LOAD_OBJ**
*/
static Mesh load(const String& file, int type = LOAD_PLY);
};
/** @brief This class wraps intrinsic parameters of a camera.
It provides several constructors that can extract the intrinsic parameters from field of
view, intrinsic matrix and projection matrix. :
*/
class CV_EXPORTS Camera
{
public:
/** @brief Constructs a Camera.
@param fx Horizontal focal length.
@param fy Vertical focal length.
@param cx x coordinate of the principal point.
@param cy y coordinate of the principal point.
@param window_size Size of the window. This together with focal length and principal
point determines the field of view.
*/
Camera(double fx, double fy, double cx, double cy, const Size &window_size);
/** @overload
@param fov Field of view (horizontal, vertical)
@param window_size Size of the window. Principal point is at the center of the window
by default.
*/
Camera(const Vec2d &fov, const Size &window_size);
/** @overload
@param K Intrinsic matrix of the camera with the following form
\f[
\begin{bmatrix}
f_x & 0 & c_x\\
0 & f_y & c_y\\
0 & 0 & 1\\
\end{bmatrix}
\f]
@param window_size Size of the window. This together with intrinsic matrix determines
the field of view.
*/
Camera(const Matx33d &K, const Size &window_size);
/** @overload
@param proj Projection matrix of the camera with the following form
\f[
\begin{bmatrix}
\frac{2n}{r-l} & 0 & \frac{r+l}{r-l} & 0\\
0 & \frac{2n}{t-b} & \frac{t+b}{t-b} & 0\\
0 & 0 & -\frac{f+n}{f-n} & -\frac{2fn}{f-n}\\
0 & 0 & -1 & 0\\
\end{bmatrix}
\f]
@param window_size Size of the window. This together with projection matrix determines
the field of view.
*/
explicit Camera(const Matx44d &proj, const Size &window_size);
const Vec2d & getClip() const { return clip_; }
void setClip(const Vec2d &clip) { clip_ = clip; }
const Size & getWindowSize() const { return window_size_; }
void setWindowSize(const Size &window_size);
const Vec2d& getFov() const { return fov_; }
void setFov(const Vec2d& fov) { fov_ = fov; }
const Vec2d& getPrincipalPoint() const { return principal_point_; }
const Vec2d& getFocalLength() const { return focal_; }
/** @brief Computes projection matrix using intrinsic parameters of the camera.
@param proj Output projection matrix with the following form
\f[
\begin{bmatrix}
\frac{2n}{r-l} & 0 & \frac{r+l}{r-l} & 0\\
0 & \frac{2n}{t-b} & \frac{t+b}{t-b} & 0\\
0 & 0 & -\frac{f+n}{f-n} & -\frac{2fn}{f-n}\\
0 & 0 & -1 & 0\\
\end{bmatrix}
\f]
*/
void computeProjectionMatrix(Matx44d &proj) const;
/** @brief Creates a Kinect Camera with
- fx = fy = 525
- cx = 320
- cy = 240
@param window_size Size of the window. This together with intrinsic matrix of a Kinect Camera
determines the field of view.
*/
static Camera KinectCamera(const Size &window_size);
private:
void init(double fx, double fy, double cx, double cy, const Size &window_size);
/** The near plane and the far plane.
* - clip_[0]: the near plane; default value is 0.01
* - clip_[1]: the far plane; default value is 1000.01
*/
Vec2d clip_;
/**
* Field of view.
* - fov_[0]: horizontal(x-axis) field of view in radians
* - fov_[1]: vertical(y-axis) field of view in radians
*/
Vec2d fov_;
/** Window size.*/
Size window_size_;
/**
* Principal point.
* - principal_point_[0]: cx
* - principal_point_[1]: cy
*/
Vec2d principal_point_;
/**
* Focal length.
* - focal_[0]: fx
* - focal_[1]: fy
*/
Vec2d focal_;
};
/** @brief This class represents a keyboard event.
*/
class CV_EXPORTS KeyboardEvent
{
public:
enum { NONE = 0, ALT = 1, CTRL = 2, SHIFT = 4 };
enum Action { KEY_UP = 0, KEY_DOWN = 1 };
/** @brief Constructs a KeyboardEvent.
@param action Signals if key is pressed or released.
@param symbol Name of the key.
@param code Code of the key.
@param modifiers Signals if alt, ctrl or shift are pressed or their combination.
*/
KeyboardEvent(Action action, const String& symbol, unsigned char code, int modifiers);
Action action;
String symbol;
unsigned char code;
int modifiers;
};
/** @brief This class represents a mouse event.
*/
class CV_EXPORTS MouseEvent
{
public:
enum Type { MouseMove = 1, MouseButtonPress, MouseButtonRelease, MouseScrollDown, MouseScrollUp, MouseDblClick } ;
enum MouseButton { NoButton = 0, LeftButton, MiddleButton, RightButton, VScroll } ;
/** @brief Constructs a MouseEvent.
@param type Type of the event. This can be **MouseMove**, **MouseButtonPress**,
**MouseButtonRelease**, **MouseScrollDown**, **MouseScrollUp**, **MouseDblClick**.
@param button Mouse button. This can be **NoButton**, **LeftButton**, **MiddleButton**,
**RightButton**, **VScroll**.
@param pointer Position of the event.
@param modifiers Signals if alt, ctrl or shift are pressed or their combination.
*/
MouseEvent(const Type& type, const MouseButton& button, const Point& pointer, int modifiers);
Type type;
MouseButton button;
Point pointer;
int modifiers;
};
//! @} viz
} /* namespace viz */
} /* namespace cv */
//! @cond IGNORED
//////////////////////////////////////////////////////////////////////////////////////////////////////
/// cv::viz::Color
inline cv::viz::Color::Color() : Scalar(0, 0, 0) {}
inline cv::viz::Color::Color(double _gray) : Scalar(_gray, _gray, _gray) {}
inline cv::viz::Color::Color(double _blue, double _green, double _red) : Scalar(_blue, _green, _red) {}
inline cv::viz::Color::Color(const Scalar& color) : Scalar(color) {}
inline cv::viz::Color::operator cv::Vec3b() const { return cv::Vec3d(val); }
inline cv::viz::Color cv::viz::Color::black() { return Color( 0, 0, 0); }
inline cv::viz::Color cv::viz::Color::green() { return Color( 0, 255, 0); }
inline cv::viz::Color cv::viz::Color::blue() { return Color(255, 0, 0); }
inline cv::viz::Color cv::viz::Color::cyan() { return Color(255, 255, 0); }
inline cv::viz::Color cv::viz::Color::red() { return Color( 0, 0, 255); }
inline cv::viz::Color cv::viz::Color::yellow() { return Color( 0, 255, 255); }
inline cv::viz::Color cv::viz::Color::magenta() { return Color(255, 0, 255); }
inline cv::viz::Color cv::viz::Color::white() { return Color(255, 255, 255); }
inline cv::viz::Color cv::viz::Color::gray() { return Color(128, 128, 128); }
inline cv::viz::Color cv::viz::Color::mlab() { return Color(255, 128, 128); }
inline cv::viz::Color cv::viz::Color::navy() { return Color(0, 0, 128); }
inline cv::viz::Color cv::viz::Color::olive() { return Color(0, 128, 128); }
inline cv::viz::Color cv::viz::Color::maroon() { return Color(0, 0, 128); }
inline cv::viz::Color cv::viz::Color::teal() { return Color(128, 128, 0); }
inline cv::viz::Color cv::viz::Color::rose() { return Color(128, 0, 255); }
inline cv::viz::Color cv::viz::Color::azure() { return Color(255, 128, 0); }
inline cv::viz::Color cv::viz::Color::lime() { return Color(0, 255, 191); }
inline cv::viz::Color cv::viz::Color::gold() { return Color(0, 215, 255); }
inline cv::viz::Color cv::viz::Color::brown() { return Color(42, 42, 165); }
inline cv::viz::Color cv::viz::Color::orange() { return Color(0, 165, 255); }
inline cv::viz::Color cv::viz::Color::chartreuse() { return Color(0, 255, 128); }
inline cv::viz::Color cv::viz::Color::orange_red() { return Color(0, 69, 255); }
inline cv::viz::Color cv::viz::Color::purple() { return Color(128, 0, 128); }
inline cv::viz::Color cv::viz::Color::indigo() { return Color(130, 0, 75); }
inline cv::viz::Color cv::viz::Color::pink() { return Color(203, 192, 255); }
inline cv::viz::Color cv::viz::Color::cherry() { return Color( 99, 29, 222); }
inline cv::viz::Color cv::viz::Color::bluberry() { return Color(247, 134, 79); }
inline cv::viz::Color cv::viz::Color::raspberry() { return Color( 92, 11, 227); }
inline cv::viz::Color cv::viz::Color::silver() { return Color(192, 192, 192); }
inline cv::viz::Color cv::viz::Color::violet() { return Color(226, 43, 138); }
inline cv::viz::Color cv::viz::Color::apricot() { return Color(177, 206, 251); }
inline cv::viz::Color cv::viz::Color::turquoise() { return Color(208, 224, 64); }
inline cv::viz::Color cv::viz::Color::celestial_blue() { return Color(208, 151, 73); }
inline cv::viz::Color cv::viz::Color::amethyst() { return Color(204, 102, 153); }
inline cv::viz::Color cv::viz::Color::not_set() { return Color(-1, -1, -1); }
//! @endcond
#endif
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
// Authors:
// * Ozan Tonkal, ozantonkal@gmail.com
// * Anatoly Baksheev, Itseez Inc. myname.mysurname <> mycompany.com
//
//M*/
#ifndef OPENCV_VIZ_VIZ3D_HPP
#define OPENCV_VIZ_VIZ3D_HPP
#if !defined YES_I_AGREE_THAT_VIZ_API_IS_NOT_STABLE_NOW_AND_BINARY_COMPARTIBILITY_WONT_BE_SUPPORTED && !defined CVAPI_EXPORTS
//#error "Viz is in beta state now. Please define macro above to use it"
#endif
#include <opencv2/core.hpp>
#include <opencv2/viz/types.hpp>
#include <opencv2/viz/widgets.hpp>
namespace cv
{
namespace viz
{
//! @addtogroup viz
//! @{
/** @brief The Viz3d class represents a 3D visualizer window. This class is implicitly shared.
*/
class CV_EXPORTS Viz3d
{
public:
typedef cv::viz::Color Color;
typedef void (*KeyboardCallback)(const KeyboardEvent&, void*);
typedef void (*MouseCallback)(const MouseEvent&, void*);
/** @brief The constructors.
@param window_name Name of the window.
*/
Viz3d(const String& window_name = String());
Viz3d(const Viz3d&);
Viz3d& operator=(const Viz3d&);
~Viz3d();
/** @brief Shows a widget in the window.
@param id A unique id for the widget. @param widget The widget to be displayed in the window.
@param pose Pose of the widget.
*/
void showWidget(const String &id, const Widget &widget, const Affine3d &pose = Affine3d::Identity());
/** @brief Removes a widget from the window.
@param id The id of the widget that will be removed.
*/
void removeWidget(const String &id);
/** @brief Retrieves a widget from the window.
A widget is implicitly shared; that is, if the returned widget is modified, the changes
will be immediately visible in the window.
@param id The id of the widget that will be returned.
*/
Widget getWidget(const String &id) const;
/** @brief Removes all widgets from the window.
*/
void removeAllWidgets();
/** @brief Removed all widgets and displays image scaled to whole window area.
@param image Image to be displayed.
@param window_size Size of Viz3d window. Default value means no change.
*/
void showImage(InputArray image, const Size& window_size = Size(-1, -1));
/** @brief Sets pose of a widget in the window.
@param id The id of the widget whose pose will be set. @param pose The new pose of the widget.
*/
void setWidgetPose(const String &id, const Affine3d &pose);
/** @brief Updates pose of a widget in the window by pre-multiplying its current pose.
@param id The id of the widget whose pose will be updated. @param pose The pose that the current
pose of the widget will be pre-multiplied by.
*/
void updateWidgetPose(const String &id, const Affine3d &pose);
/** @brief Returns the current pose of a widget in the window.
@param id The id of the widget whose pose will be returned.
*/
Affine3d getWidgetPose(const String &id) const;
/** @brief Sets the intrinsic parameters of the viewer using Camera.
@param camera Camera object wrapping intrinsic parameters.
*/
void setCamera(const Camera &camera);
/** @brief Returns a camera object that contains intrinsic parameters of the current viewer.
*/
Camera getCamera() const;
/** @brief Returns the current pose of the viewer.
*/
Affine3d getViewerPose() const;
/** @brief Sets pose of the viewer.
@param pose The new pose of the viewer.
*/
void setViewerPose(const Affine3d &pose);
/** @brief Resets camera viewpoint to a 3D widget in the scene.
@param id Id of a 3D widget.
*/
void resetCameraViewpoint(const String &id);
/** @brief Resets camera.
*/
void resetCamera();
/** @brief Transforms a point in world coordinate system to window coordinate system.
@param pt Point in world coordinate system.
@param window_coord Output point in window coordinate system.
*/
void convertToWindowCoordinates(const Point3d &pt, Point3d &window_coord);
/** @brief Transforms a point in window coordinate system to a 3D ray in world coordinate system.
@param window_coord Point in window coordinate system. @param origin Output origin of the ray.
@param direction Output direction of the ray.
*/
void converTo3DRay(const Point3d &window_coord, Point3d &origin, Vec3d &direction);
/** @brief Returns the current size of the window.
*/
Size getWindowSize() const;
/** @brief Sets the size of the window.
@param window_size New size of the window.
*/
void setWindowSize(const Size &window_size);
/** @brief Returns the name of the window which has been set in the constructor.
* `Viz - ` is prepended to the name if necessary.
*/
String getWindowName() const;
/** @brief Returns the Mat screenshot of the current scene.
*/
cv::Mat getScreenshot() const;
/** @brief Saves screenshot of the current scene.
@param file Name of the file.
*/
void saveScreenshot(const String &file);
/** @brief Sets the position of the window in the screen.
@param window_position coordinates of the window
*/
void setWindowPosition(const Point& window_position);
/** @brief Sets or unsets full-screen rendering mode.
@param mode If true, window will use full-screen mode.
*/
void setFullScreen(bool mode = true);
/** @brief Sets background color.
*/
void setBackgroundColor(const Color& color = Color::black(), const Color& color2 = Color::not_set());
void setBackgroundTexture(InputArray image = noArray());
void setBackgroundMeshLab();
/** @brief The window renders and starts the event loop.
*/
void spin();
/** @brief Starts the event loop for a given time.
@param time Amount of time in milliseconds for the event loop to keep running.
@param force_redraw If true, window renders.
*/
void spinOnce(int time = 1, bool force_redraw = false);
/** @brief Create a window in memory instead of on the screen.
*/
void setOffScreenRendering();
/** @brief Remove all lights from the current scene.
*/
void removeAllLights();
/** @brief Add a light in the scene.
@param position The position of the light.
@param focalPoint The point at which the light is shining
@param color The color of the light
@param diffuseColor The diffuse color of the light
@param ambientColor The ambient color of the light
@param specularColor The specular color of the light
*/
void addLight(const Vec3d &position, const Vec3d &focalPoint = Vec3d(0, 0, 0), const Color &color = Color::white(),
const Color &diffuseColor = Color::white(), const Color &ambientColor = Color::black(),
const Color &specularColor = Color::white());
/** @brief Returns whether the event loop has been stopped.
*/
bool wasStopped() const;
void close();
/** @brief Sets keyboard handler.
@param callback Keyboard callback (void (\*KeyboardCallbackFunction(const
KeyboardEvent&, void\*)).
@param cookie The optional parameter passed to the callback.
*/
void registerKeyboardCallback(KeyboardCallback callback, void* cookie = 0);
/** @brief Sets mouse handler.
@param callback Mouse callback (void (\*MouseCallback)(const MouseEvent&, void\*)).
@param cookie The optional parameter passed to the callback.
*/
void registerMouseCallback(MouseCallback callback, void* cookie = 0);
/** @brief Sets rendering property of a widget.
@param id Id of the widget.
@param property Property that will be modified.
@param value The new value of the property.
Rendering property can be one of the following:
- **POINT_SIZE**
- **OPACITY**
- **LINE_WIDTH**
- **FONT_SIZE**
REPRESENTATION: Expected values are
- **REPRESENTATION_POINTS**
- **REPRESENTATION_WIREFRAME**
- **REPRESENTATION_SURFACE**
IMMEDIATE_RENDERING:
- Turn on immediate rendering by setting the value to 1.
- Turn off immediate rendering by setting the value to 0.
SHADING: Expected values are
- **SHADING_FLAT**
- **SHADING_GOURAUD**
- **SHADING_PHONG**
*/
void setRenderingProperty(const String &id, int property, double value);
/** @brief Returns rendering property of a widget.
@param id Id of the widget.
@param property Property.
Rendering property can be one of the following:
- **POINT_SIZE**
- **OPACITY**
- **LINE_WIDTH**
- **FONT_SIZE**
REPRESENTATION: Expected values are
- **REPRESENTATION_POINTS**
- **REPRESENTATION_WIREFRAME**
- **REPRESENTATION_SURFACE**
IMMEDIATE_RENDERING:
- Turn on immediate rendering by setting the value to 1.
- Turn off immediate rendering by setting the value to 0.
SHADING: Expected values are
- **SHADING_FLAT**
- **SHADING_GOURAUD**
- **SHADING_PHONG**
*/
double getRenderingProperty(const String &id, int property);
/** @brief Sets geometry representation of the widgets to surface, wireframe or points.
@param representation Geometry representation which can be one of the following:
- **REPRESENTATION_POINTS**
- **REPRESENTATION_WIREFRAME**
- **REPRESENTATION_SURFACE**
*/
void setRepresentation(int representation);
void setGlobalWarnings(bool enabled = false);
private:
struct VizImpl;
VizImpl* impl_;
void create(const String &window_name);
void release();
friend class VizStorage;
};
//! @}
} /* namespace viz */
} /* namespace cv */
#endif
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
// Authors:
// * Ozan Tonkal, ozantonkal@gmail.com
// * Anatoly Baksheev, Itseez Inc. myname.mysurname <> mycompany.com
//
//M*/
#ifndef OPENCV_VIZCORE_HPP
#define OPENCV_VIZCORE_HPP
#include <opencv2/viz/types.hpp>
#include <opencv2/viz/widgets.hpp>
#include <opencv2/viz/viz3d.hpp>
namespace cv
{
namespace viz
{
//! @addtogroup viz
//! @{
/** @brief Takes coordinate frame data and builds transform to global coordinate frame.
@param axis_x X axis vector in global coordinate frame.
@param axis_y Y axis vector in global coordinate frame.
@param axis_z Z axis vector in global coordinate frame.
@param origin Origin of the coordinate frame in global coordinate frame.
@return An affine transform that describes transformation between global coordinate frame
and a given coordinate frame.
The returned transforms can transform a point in the given coordinate frame to the global
coordinate frame.
*/
CV_EXPORTS Affine3d makeTransformToGlobal(const Vec3d& axis_x, const Vec3d& axis_y, const Vec3d& axis_z, const Vec3d& origin = Vec3d::all(0));
/** @brief Constructs camera pose from position, focal_point and up_vector (see gluLookAt() for more
information).
@param position Position of the camera in global coordinate frame.
@param focal_point Focal point of the camera in global coordinate frame.
@param y_dir Up vector of the camera in global coordinate frame.
This function returns pose of the camera in global coordinate frame.
*/
CV_EXPORTS Affine3d makeCameraPose(const Vec3d& position, const Vec3d& focal_point, const Vec3d& y_dir);
/** @brief Retrieves a window by its name.
@param window_name Name of the window that is to be retrieved.
This function returns a Viz3d object with the given name.
@note If the window with that name already exists, that window is returned. Otherwise, new window is
created with the given name, and it is returned.
@note Window names are automatically prefixed by "Viz - " if it is not done by the user.
@code
/// window and window_2 are the same windows.
viz::Viz3d window = viz::getWindowByName("myWindow");
viz::Viz3d window_2 = viz::getWindowByName("Viz - myWindow");
@endcode
*/
CV_EXPORTS Viz3d getWindowByName(const String &window_name);
//! Unregisters all Viz windows from internal database. After it 'getWindowByName()' will create new windows instead of getting existing from the database.
CV_EXPORTS void unregisterAllWindows();
//! Displays image in specified window
CV_EXPORTS Viz3d imshow(const String& window_name, InputArray image, const Size& window_size = Size(-1, -1));
/** @brief Checks **float/double** value for nan.
@param x return true if nan.
*/
inline bool isNan(float x)
{
unsigned int *u = reinterpret_cast<unsigned int *>(&x);
return ((u[0] & 0x7f800000) == 0x7f800000) && (u[0] & 0x007fffff);
}
/** @brief Checks **float/double** value for nan.
@param x return true if nan.
*/
inline bool isNan(double x)
{
unsigned int *u = reinterpret_cast<unsigned int *>(&x);
return (u[1] & 0x7ff00000) == 0x7ff00000 && (u[0] != 0 || (u[1] & 0x000fffff) != 0);
}
/** @brief Checks **float/double** value for nan.
@param v return true if **any** of the elements of the vector is *nan*.
*/
template<typename _Tp, int cn> inline bool isNan(const Vec<_Tp, cn>& v)
{ return isNan(v.val[0]) || isNan(v.val[1]) || isNan(v.val[2]); }
/** @brief Checks **float/double** value for nan.
@param p return true if **any** of the elements of the point is *nan*.
*/
template<typename _Tp> inline bool isNan(const Point3_<_Tp>& p)
{ return isNan(p.x) || isNan(p.y) || isNan(p.z); }
///////////////////////////////////////////////////////////////////////////////////////////////
/// Read/write clouds. Supported formats: ply, xyz, obj and stl (readonly)
/**
* @param file Filename with extension. Supported formats: PLY, XYZ and OBJ.
* @param cloud Supported depths: CV_32F and CV_64F. Supported channels: 3 and 4.
* @param colors Used by PLY format only. Supported depth: CV_8U. Supported channels: 1, 3 and 4.
* @param normals Used by PLY and OBJ format only. Supported depths: CV_32F and CV_64F.
* Supported channels: 3 and 4.
* @param binary Used only for PLY format.
*/
CV_EXPORTS void writeCloud(const String& file, InputArray cloud, InputArray colors = noArray(), InputArray normals = noArray(), bool binary = false);
/**
* @param file Filename with extension. Supported formats: PLY, XYZ, OBJ and STL.
* @param colors Used by PLY and STL formats only.
* @param normals Used by PLY, OBJ and STL formats only.
* @return A mat containing the point coordinates with depth CV_32F or CV_64F and number of
* channels 3 or 4 with only 1 row.
*/
CV_EXPORTS Mat readCloud (const String& file, OutputArray colors = noArray(), OutputArray normals = noArray());
///////////////////////////////////////////////////////////////////////////////////////////////
/// Reads mesh. Only ply format is supported now and no texture load support
CV_EXPORTS Mesh readMesh(const String& file);
///////////////////////////////////////////////////////////////////////////////////////////////
/// Read/write poses and trajectories
/**
* @param file Filename of type supported by cv::FileStorage.
* @param pose Output matrix.
* @param tag Name of the pose in the file.
*/
CV_EXPORTS bool readPose(const String& file, Affine3d& pose, const String& tag = "pose");
/**
* @param file Filename.
* @param pose Input matrix.
* @param tag Name of the pose to be saved into the given file.
*/
CV_EXPORTS void writePose(const String& file, const Affine3d& pose, const String& tag = "pose");
/** takes vector<Affine3<T>> with T = float/dobule and writes to a sequence of files with given filename format
* @param traj Trajectory containing a list of poses. It can be
* - std::vector<cv::Mat>, each cv::Mat is of type CV_32F16 or CV_64FC16
* - std::vector<cv::Affine3f>, std::vector<cv::Affine3d>
* - cv::Mat of type CV_32FC16 OR CV_64F16
* @param files_format Format specifier string for constructing filenames.
* The only placeholder in the string should support `int`.
* @param start The initial counter for files_format.
* @param tag Name of the matrix in the file.
*/
CV_EXPORTS void writeTrajectory(InputArray traj, const String& files_format = "pose%05d.xml", int start = 0, const String& tag = "pose");
/** takes vector<Affine3<T>> with T = float/dobule and loads poses from sequence of files
*
* @param traj Output array containing a lists of poses. It can be
* - std::vector<cv::Affine3f>, std::vector<cv::Affine3d>
* - cv::Mat
* @param files_format Format specifier string for constructing filenames.
* The only placeholder in the string should support `int`.
* @param start The initial counter for files_format. It must be greater than or equal to 0.
* @param end The final counter for files_format.
* @param tag Name of the matrix in the file.
*/
CV_EXPORTS void readTrajectory(OutputArray traj, const String& files_format = "pose%05d.xml", int start = 0, int end = INT_MAX, const String& tag = "pose");
///////////////////////////////////////////////////////////////////////////////////////////////
/** Computing normals for mesh
* @param mesh Input mesh.
* @param normals Normals at very point in the mesh of type CV_64FC3.
*/
CV_EXPORTS void computeNormals(const Mesh& mesh, OutputArray normals);
//! @}
} /* namespace viz */
} /* namespace cv */
#endif /* OPENCV_VIZCORE_HPP */
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
// Authors:
// * Ozan Tonkal, ozantonkal@gmail.com
// * Anatoly Baksheev, Itseez Inc. myname.mysurname <> mycompany.com
//
//M*/
#ifndef OPENCV_VIZ_WIDGET_ACCESSOR_HPP
#define OPENCV_VIZ_WIDGET_ACCESSOR_HPP
#include <opencv2/core/cvdef.h>
#include <vtkSmartPointer.h>
#include <vtkProp.h>
namespace cv
{
namespace viz
{
//! @addtogroup viz_widget
//! @{
class Widget;
/** @brief This class is for users who want to develop their own widgets using VTK library API. :
*/
struct CV_EXPORTS WidgetAccessor
{
/** @brief Returns vtkProp of a given widget.
@param widget Widget whose vtkProp is to be returned.
@note vtkProp has to be down cast appropriately to be modified.
@code
vtkActor * actor = vtkActor::SafeDownCast(viz::WidgetAccessor::getProp(widget));
@endcode
*/
static vtkSmartPointer<vtkProp> getProp(const Widget &widget);
/** @brief Sets vtkProp of a given widget.
@param widget Widget whose vtkProp is to be set. @param prop A vtkProp.
*/
static void setProp(Widget &widget, vtkSmartPointer<vtkProp> prop);
};
//! @}
}
}
#endif
此差异已折叠。
此差异已折叠。
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
// Authors:
// * Ozan Tonkal, ozantonkal@gmail.com
// * Anatoly Baksheev, Itseez Inc. myname.mysurname <> mycompany.com
//
//M*/
#ifndef __OPENCV_VIZ_PRECOMP_HPP__
#define __OPENCV_VIZ_PRECOMP_HPP__
#include <map>
#include <ctime>
#include <list>
#include <vector>
#include <iomanip>
#include <limits>
#include <vtkAppendPolyData.h>
#include <vtkAssemblyPath.h>
#include <vtkCellData.h>
#include <vtkLineSource.h>
#include <vtkPropPicker.h>
#include <vtkSmartPointer.h>
#include <vtkDataSet.h>
#include <vtkPolygon.h>
#include <vtkUnstructuredGrid.h>
#include <vtkDiskSource.h>
#include <vtkPlaneSource.h>
#include <vtkSphereSource.h>
#include <vtkArrowSource.h>
#include <vtkOutlineSource.h>
#include <vtkTransform.h>
#include <vtkTransformPolyDataFilter.h>
#include <vtkTubeFilter.h>
#include <vtkCubeSource.h>
#include <vtkAxes.h>
#include <vtkFloatArray.h>
#include <vtkDoubleArray.h>
#include <vtkPointData.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkDataSetMapper.h>
#include <vtkCellArray.h>
#include <vtkCommand.h>
#include <vtkPLYReader.h>
#include <vtkPolyLine.h>
#include <vtkVectorText.h>
#include <vtkFollower.h>
#include <vtkInteractorStyle.h>
#include <vtkUnsignedCharArray.h>
#include <vtkRendererCollection.h>
#include <vtkPNGWriter.h>
#include <vtkWindowToImageFilter.h>
#include <vtkInteractorStyleTrackballCamera.h>
#include <vtkProperty.h>
#include <vtkCamera.h>
#include <vtkPlanes.h>
#include <vtkImageFlip.h>
#include <vtkRenderWindow.h>
#include <vtkTextProperty.h>
#include <vtkProperty2D.h>
#include <vtkLODActor.h>
#include <vtkActor.h>
#include <vtkTextActor.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkMath.h>
#include <vtkExtractEdges.h>
#include <vtkFrustumSource.h>
#include <vtkTexture.h>
#include <vtkTextureMapToPlane.h>
#include <vtkPolyDataNormals.h>
#include <vtkAlgorithmOutput.h>
#include <vtkImageMapper.h>
#include <vtkPoints.h>
#include <vtkInformation.h>
#include <vtkInformationVector.h>
#include <vtkObjectFactory.h>
#include <vtkPolyDataAlgorithm.h>
#include <vtkMergeFilter.h>
#include <vtkErrorCode.h>
#include <vtkPLYWriter.h>
#include <vtkSTLWriter.h>
#include <vtkPLYReader.h>
#include <vtkOBJReader.h>
#include <vtkSTLReader.h>
#include <vtkPNGReader.h>
#include <vtkOBJExporter.h>
#include <vtkVRMLExporter.h>
#include <vtkTensorGlyph.h>
#include <vtkImageAlgorithm.h>
#include <vtkTransformFilter.h>
#include <vtkConeSource.h>
#include <vtkElevationFilter.h>
#include <vtkColorTransferFunction.h>
#include <vtkStreamingDemandDrivenPipeline.h>
#include <vtkLight.h>
#include "vtkCallbackCommand.h"
#if !defined(_WIN32) || defined(__CYGWIN__)
# include <unistd.h> /* unlink */
#else
# include <io.h> /* unlink */
#endif
#include "vtk/vtkOBJWriter.h"
#include "vtk/vtkXYZWriter.h"
#include "vtk/vtkXYZReader.h"
#include "vtk/vtkCloudMatSink.h"
#include "vtk/vtkCloudMatSource.h"
#include "vtk/vtkTrajectorySource.h"
#include "vtk/vtkImageMatSource.h"
#include <opencv2/core.hpp>
#include <opencv2/viz.hpp>
#include <opencv2/viz/widget_accessor.hpp>
#include <opencv2/core/utility.hpp>
namespace cv
{
namespace viz
{
typedef std::map<String, vtkSmartPointer<vtkProp> > WidgetActorMap;
struct VizMap
{
typedef std::map<String, Viz3d> type;
typedef type::iterator iterator;
type m;
~VizMap();
void replace_clear();
};
class VizStorage
{
public:
static void unregisterAll();
//! window names automatically have Viz - prefix even though not provided by the users
static String generateWindowName(const String &window_name);
private:
VizStorage(); // Static
static void add(const Viz3d& window);
static Viz3d& get(const String &window_name);
static void remove(const String &window_name);
static bool windowExists(const String &window_name);
static void removeUnreferenced();
static VizMap storage;
friend class Viz3d;
static VizStorage init;
};
template<typename _Tp> inline _Tp normalized(const _Tp& v) { return v * 1/norm(v); }
template<typename _Tp> inline bool isNan(const _Tp* data)
{
return isNan(data[0]) || isNan(data[1]) || isNan(data[2]);
}
inline vtkSmartPointer<vtkActor> getActor(const Widget3D& widget)
{
return vtkActor::SafeDownCast(WidgetAccessor::getProp(widget));
}
inline vtkSmartPointer<vtkPolyData> getPolyData(const Widget3D& widget)
{
vtkSmartPointer<vtkMapper> mapper = getActor(widget)->GetMapper();
return vtkPolyData::SafeDownCast(mapper->GetInput());
}
inline vtkSmartPointer<vtkMatrix4x4> vtkmatrix(const cv::Matx44d &matrix)
{
vtkSmartPointer<vtkMatrix4x4> vtk_matrix = vtkSmartPointer<vtkMatrix4x4>::New();
vtk_matrix->DeepCopy(matrix.val);
return vtk_matrix;
}
inline Color vtkcolor(const Color& color)
{
Color scaled_color = color * (1.0/255.0);
std::swap(scaled_color[0], scaled_color[2]);
return scaled_color;
}
inline Vec3d get_random_vec(double from = -10.0, double to = 10.0)
{
RNG& rng = theRNG();
return Vec3d(rng.uniform(from, to), rng.uniform(from, to), rng.uniform(from, to));
}
struct VtkUtils
{
template<class Filter>
static void SetInputData(vtkSmartPointer<Filter> filter, vtkPolyData* polydata)
{
#if VTK_MAJOR_VERSION <= 5
filter->SetInput(polydata);
#else
filter->SetInputData(polydata);
#endif
}
template<class Filter>
static void SetSourceData(vtkSmartPointer<Filter> filter, vtkPolyData* polydata)
{
#if VTK_MAJOR_VERSION <= 5
filter->SetSource(polydata);
#else
filter->SetSourceData(polydata);
#endif
}
template<class Filter>
static void SetInputData(vtkSmartPointer<Filter> filter, vtkImageData* polydata)
{
#if VTK_MAJOR_VERSION <= 5
filter->SetInput(polydata);
#else
filter->SetInputData(polydata);
#endif
}
template<class Filter>
static void AddInputData(vtkSmartPointer<Filter> filter, vtkPolyData *polydata)
{
#if VTK_MAJOR_VERSION <= 5
filter->AddInput(polydata);
#else
filter->AddInputData(polydata);
#endif
}
static vtkSmartPointer<vtkUnsignedCharArray> FillScalars(size_t size, const Color& color)
{
Vec3b rgb = Vec3d(color[2], color[1], color[0]);
Vec3b* color_data = new Vec3b[size];
std::fill(color_data, color_data + size, rgb);
vtkSmartPointer<vtkUnsignedCharArray> scalars = vtkSmartPointer<vtkUnsignedCharArray>::New();
scalars->SetName("Colors");
scalars->SetNumberOfComponents(3);
scalars->SetNumberOfTuples((vtkIdType)size);
scalars->SetArray(color_data->val, (vtkIdType)(size * 3), 0, vtkUnsignedCharArray::VTK_DATA_ARRAY_DELETE);
return scalars;
}
static vtkSmartPointer<vtkPolyData> FillScalars(vtkSmartPointer<vtkPolyData> polydata, const Color& color)
{
return polydata->GetPointData()->SetScalars(FillScalars(polydata->GetNumberOfPoints(), color)), polydata;
}
static vtkSmartPointer<vtkPolyData> ComputeNormals(vtkSmartPointer<vtkPolyData> polydata)
{
vtkSmartPointer<vtkPolyDataNormals> normals_generator = vtkSmartPointer<vtkPolyDataNormals>::New();
normals_generator->ComputePointNormalsOn();
normals_generator->ComputeCellNormalsOff();
normals_generator->SetFeatureAngle(0.1);
normals_generator->SetSplitting(0);
normals_generator->SetConsistency(1);
normals_generator->SetAutoOrientNormals(0);
normals_generator->SetFlipNormals(0);
normals_generator->SetNonManifoldTraversal(1);
VtkUtils::SetInputData(normals_generator, polydata);
normals_generator->Update();
return normals_generator->GetOutput();
}
static vtkSmartPointer<vtkPolyData> TransformPolydata(vtkSmartPointer<vtkAlgorithmOutput> algorithm_output_port, const Affine3d& pose)
{
vtkSmartPointer<vtkTransform> transform = vtkSmartPointer<vtkTransform>::New();
transform->SetMatrix(vtkmatrix(pose.matrix));
vtkSmartPointer<vtkTransformPolyDataFilter> transform_filter = vtkSmartPointer<vtkTransformPolyDataFilter>::New();
transform_filter->SetTransform(transform);
transform_filter->SetInputConnection(algorithm_output_port);
transform_filter->Update();
return transform_filter->GetOutput();
}
static vtkSmartPointer<vtkPolyData> TransformPolydata(vtkSmartPointer<vtkPolyData> polydata, const Affine3d& pose)
{
vtkSmartPointer<vtkTransform> transform = vtkSmartPointer<vtkTransform>::New();
transform->SetMatrix(vtkmatrix(pose.matrix));
vtkSmartPointer<vtkTransformPolyDataFilter> transform_filter = vtkSmartPointer<vtkTransformPolyDataFilter>::New();
VtkUtils::SetInputData(transform_filter, polydata);
transform_filter->SetTransform(transform);
transform_filter->Update();
return transform_filter->GetOutput();
}
};
vtkSmartPointer<vtkRenderWindowInteractor> vtkCocoaRenderWindowInteractorNew();
}
}
#include "vtk/vtkVizInteractorStyle.hpp"
#include "vizimpl.hpp"
#endif
此差异已折叠。
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
// Authors:
// * Ozan Tonkal, ozantonkal@gmail.com
// * Anatoly Baksheev, Itseez Inc. myname.mysurname <> mycompany.com
//
//M*/
#include "precomp.hpp"
////////////////////////////////////////////////////////////////////
/// Events
cv::viz::KeyboardEvent::KeyboardEvent(Action _action, const String& _symbol, unsigned char _code, int _modifiers)
: action(_action), symbol(_symbol), code(_code), modifiers(_modifiers) {}
cv::viz::MouseEvent::MouseEvent(const Type& _type, const MouseButton& _button, const Point& _pointer, int _modifiers)
: type(_type), button(_button), pointer(_pointer), modifiers(_modifiers) {}
////////////////////////////////////////////////////////////////////
/// cv::viz::Mesh3d
cv::viz::Mesh cv::viz::Mesh::load(const String& file, int type)
{
vtkSmartPointer<vtkPolyDataAlgorithm> reader = vtkSmartPointer<vtkPolyDataAlgorithm>::New();
switch (type) {
case LOAD_AUTO:
{
CV_Error(Error::StsError, "cv::viz::Mesh::LOAD_AUTO: Not implemented yet");
}
case LOAD_PLY:
{
vtkSmartPointer<vtkPLYReader> ply_reader = vtkSmartPointer<vtkPLYReader>::New();
ply_reader->SetFileName(file.c_str());
ply_reader->Update();
reader = ply_reader;
break;
}
case LOAD_OBJ:
{
vtkSmartPointer<vtkOBJReader> obj_reader = vtkSmartPointer<vtkOBJReader>::New();
obj_reader->SetFileName(file.c_str());
obj_reader->Update();
reader = obj_reader;
break;
}
default:
CV_Error(Error::StsError, "cv::viz::Mesh::load: Unknown file type");
}
vtkSmartPointer<vtkPolyData> polydata = reader->GetOutput();
CV_Assert("File does not exist or file format is not supported." && polydata);
Mesh mesh;
vtkSmartPointer<vtkCloudMatSink> sink = vtkSmartPointer<vtkCloudMatSink>::New();
sink->SetOutput(mesh.cloud, mesh.colors, mesh.normals, mesh.tcoords);
sink->SetInputConnection(reader->GetOutputPort());
sink->Write();
// Now handle the polygons
vtkSmartPointer<vtkCellArray> polygons = polydata->GetPolys();
mesh.polygons.create(1, polygons->GetSize(), CV_32SC1);
int* poly_ptr = mesh.polygons.ptr<int>();
polygons->InitTraversal();
vtkIdType nr_cell_points, *cell_points;
while (polygons->GetNextCell(nr_cell_points, cell_points))
{
*poly_ptr++ = nr_cell_points;
for (vtkIdType i = 0; i < nr_cell_points; ++i)
*poly_ptr++ = (int)cell_points[i];
}
return mesh;
}
////////////////////////////////////////////////////////////////////
/// Camera implementation
cv::viz::Camera::Camera(double fx, double fy, double cx, double cy, const Size &window_size)
{
init(fx, fy, cx, cy, window_size);
}
cv::viz::Camera::Camera(const Vec2d &fov, const Size &window_size)
{
CV_Assert(window_size.width > 0 && window_size.height > 0);
setClip(Vec2d(0.01, 1000.01)); // Default clipping
setFov(fov);
window_size_ = window_size;
// Principal point at the center
principal_point_ = Vec2f(static_cast<float>(window_size.width)*0.5f, static_cast<float>(window_size.height)*0.5f);
focal_ = Vec2f(principal_point_[0] / tan(fov_[0]*0.5f), principal_point_[1] / tan(fov_[1]*0.5f));
}
cv::viz::Camera::Camera(const cv::Matx33d & K, const Size &window_size)
{
double f_x = K(0,0);
double f_y = K(1,1);
double c_x = K(0,2);
double c_y = K(1,2);
init(f_x, f_y, c_x, c_y, window_size);
}
cv::viz::Camera::Camera(const Matx44d &proj, const Size &window_size)
{
CV_Assert(window_size.width > 0 && window_size.height > 0);
double near = proj(2,3) / (proj(2,2) - 1.0);
double far = near * (proj(2,2) - 1.0) / (proj(2,2) + 1.0);
double left = near * (proj(0,2)-1) / proj(0,0);
double right = 2.0 * near / proj(0,0) + left;
double bottom = near * (proj(1,2)-1) / proj(1,1);
double top = 2.0 * near / proj(1,1) + bottom;
double epsilon = 2.2204460492503131e-16;
principal_point_[0] = fabs(left-right) < epsilon ? window_size.width * 0.5 : (left * window_size.width) / (left - right);
principal_point_[1] = fabs(top-bottom) < epsilon ? window_size.height * 0.5 : (top * window_size.height) / (top - bottom);
focal_[0] = -near * principal_point_[0] / left;
focal_[1] = near * principal_point_[1] / top;
setClip(Vec2d(near, far));
fov_[0] = atan2(principal_point_[0], focal_[0]) + atan2(window_size.width-principal_point_[0], focal_[0]);
fov_[1] = atan2(principal_point_[1], focal_[1]) + atan2(window_size.height-principal_point_[1], focal_[1]);
window_size_ = window_size;
}
void cv::viz::Camera::init(double fx, double fy, double cx, double cy, const Size &window_size)
{
CV_Assert(window_size.width > 0 && window_size.height > 0);
setClip(Vec2d(0.01, 1000.01));// Default clipping
fov_[0] = atan2(cx, fx) + atan2(window_size.width - cx, fx);
fov_[1] = atan2(cy, fy) + atan2(window_size.height - cy, fy);
principal_point_[0] = cx;
principal_point_[1] = cy;
focal_[0] = fx;
focal_[1] = fy;
window_size_ = window_size;
}
void cv::viz::Camera::setWindowSize(const Size &window_size)
{
CV_Assert(window_size.width > 0 && window_size.height > 0);
// Get the scale factor and update the principal points
float scalex = static_cast<float>(window_size.width) / static_cast<float>(window_size_.width);
float scaley = static_cast<float>(window_size.height) / static_cast<float>(window_size_.height);
principal_point_[0] *= scalex;
principal_point_[1] *= scaley;
focal_ *= scaley;
// Vertical field of view is fixed! Update horizontal field of view
fov_[0] = (atan2(principal_point_[0],focal_[0]) + atan2(window_size.width-principal_point_[0],focal_[0]));
window_size_ = window_size;
}
void cv::viz::Camera::computeProjectionMatrix(Matx44d &proj) const
{
double top = clip_[0] * principal_point_[1] / focal_[1];
double left = -clip_[0] * principal_point_[0] / focal_[0];
double right = clip_[0] * (window_size_.width - principal_point_[0]) / focal_[0];
double bottom = -clip_[0] * (window_size_.height - principal_point_[1]) / focal_[1];
double temp1 = 2.0 * clip_[0];
double temp2 = 1.0 / (right - left);
double temp3 = 1.0 / (top - bottom);
double temp4 = 1.0 / (clip_[0] - clip_[1]);
proj = Matx44d::zeros();
proj(0,0) = temp1 * temp2;
proj(1,1) = temp1 * temp3;
proj(0,2) = (right + left) * temp2;
proj(1,2) = (top + bottom) * temp3;
proj(2,2) = (clip_[1]+clip_[0]) * temp4;
proj(3,2) = -1.0;
proj(2,3) = (temp1 * clip_[1]) * temp4;
}
cv::viz::Camera cv::viz::Camera::KinectCamera(const Size &window_size)
{
Matx33d K(525.0, 0.0, 320.0, 0.0, 525.0, 240.0, 0.0, 0.0, 1.0);
return Camera(K, window_size);
}
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
// Authors:
// * Ozan Tonkal, ozantonkal@gmail.com
// * Anatoly Baksheev, Itseez Inc. myname.mysurname <> mycompany.com
//
//M*/
#include "precomp.hpp"
cv::viz::Viz3d::Viz3d(const String& window_name) : impl_(0) { create(window_name); }
cv::viz::Viz3d::Viz3d(const Viz3d& other) : impl_(other.impl_)
{
if (impl_)
CV_XADD(&impl_->ref_counter, 1);
}
cv::viz::Viz3d& cv::viz::Viz3d::operator=(const Viz3d& other)
{
if (this != &other)
{
release();
impl_ = other.impl_;
if (impl_)
CV_XADD(&impl_->ref_counter, 1);
}
return *this;
}
cv::viz::Viz3d::~Viz3d() { release(); }
void cv::viz::Viz3d::create(const String &window_name)
{
if (impl_)
release();
if (VizStorage::windowExists(window_name))
*this = VizStorage::get(window_name);
else
{
impl_ = new VizImpl(window_name);
impl_->ref_counter = 1;
// Register the window
VizStorage::add(*this);
}
}
void cv::viz::Viz3d::release()
{
if (impl_ && CV_XADD(&impl_->ref_counter, -1) == 1)
{
delete impl_;
impl_ = 0;
}
if (impl_ && impl_->ref_counter == 1)
VizStorage::removeUnreferenced();
impl_ = 0;
}
void cv::viz::Viz3d::spin() { impl_->spin(); }
void cv::viz::Viz3d::spinOnce(int time, bool force_redraw) { impl_->spinOnce(time, force_redraw); }
void cv::viz::Viz3d::setOffScreenRendering() { impl_->setOffScreenRendering(); }
void cv::viz::Viz3d::removeAllLights() { impl_->removeAllLights(); }
void cv::viz::Viz3d::addLight(const Vec3d &position, const Vec3d &focalPoint, const Color &color,
const Color &diffuseColor, const Color &ambientColor, const Color &specularColor)
{ impl_->addLight(position, focalPoint, color, diffuseColor, ambientColor, specularColor); }
bool cv::viz::Viz3d::wasStopped() const { return impl_->wasStopped(); }
void cv::viz::Viz3d::close() { impl_->close(); }
void cv::viz::Viz3d::registerKeyboardCallback(KeyboardCallback callback, void* cookie)
{ impl_->registerKeyboardCallback(callback, cookie); }
void cv::viz::Viz3d::registerMouseCallback(MouseCallback callback, void* cookie)
{ impl_->registerMouseCallback(callback, cookie); }
void cv::viz::Viz3d::showWidget(const String &id, const Widget &widget, const Affine3d &pose) { impl_->showWidget(id, widget, pose); }
void cv::viz::Viz3d::removeWidget(const String &id) { impl_->removeWidget(id); }
cv::viz::Widget cv::viz::Viz3d::getWidget(const String &id) const { return impl_->getWidget(id); }
void cv::viz::Viz3d::removeAllWidgets() { impl_->removeAllWidgets(); }
void cv::viz::Viz3d::showImage(InputArray image, const Size& window_size) { impl_->showImage(image, window_size); }
void cv::viz::Viz3d::setWidgetPose(const String &id, const Affine3d &pose) { impl_->setWidgetPose(id, pose); }
void cv::viz::Viz3d::updateWidgetPose(const String &id, const Affine3d &pose) { impl_->updateWidgetPose(id, pose); }
cv::Affine3d cv::viz::Viz3d::getWidgetPose(const String &id) const { return impl_->getWidgetPose(id); }
void cv::viz::Viz3d::setCamera(const Camera &camera) { impl_->setCamera(camera); }
cv::viz::Camera cv::viz::Viz3d::getCamera() const { return impl_->getCamera(); }
void cv::viz::Viz3d::setViewerPose(const Affine3d &pose) { impl_->setViewerPose(pose); }
cv::Affine3d cv::viz::Viz3d::getViewerPose() const { return impl_->getViewerPose(); }
void cv::viz::Viz3d::resetCameraViewpoint(const String &id) { impl_->resetCameraViewpoint(id); }
void cv::viz::Viz3d::resetCamera() { impl_->resetCamera(); }
void cv::viz::Viz3d::convertToWindowCoordinates(const Point3d &pt, Point3d &window_coord) { impl_->convertToWindowCoordinates(pt, window_coord); }
void cv::viz::Viz3d::converTo3DRay(const Point3d &window_coord, Point3d &origin, Vec3d &direction) { impl_->converTo3DRay(window_coord, origin, direction); }
cv::Size cv::viz::Viz3d::getWindowSize() const { return impl_->getWindowSize(); }
void cv::viz::Viz3d::setWindowSize(const Size &window_size) { impl_->setWindowSize(window_size); }
cv::String cv::viz::Viz3d::getWindowName() const { return impl_->getWindowName(); }
cv::Mat cv::viz::Viz3d::getScreenshot() const { return impl_->getScreenshot(); }
void cv::viz::Viz3d::saveScreenshot(const String &file) { impl_->saveScreenshot(file); }
void cv::viz::Viz3d::setWindowPosition(const Point& window_position) { impl_->setWindowPosition(window_position); }
void cv::viz::Viz3d::setFullScreen(bool mode) { impl_->setFullScreen(mode); }
void cv::viz::Viz3d::setBackgroundColor(const Color& color, const Color& color2) { impl_->setBackgroundColor(color, color2); }
void cv::viz::Viz3d::setBackgroundTexture(InputArray image) { impl_->setBackgroundTexture(image); }
void cv::viz::Viz3d::setBackgroundMeshLab() {impl_->setBackgroundMeshLab(); }
void cv::viz::Viz3d::setRenderingProperty(const String &id, int property, double value) { getWidget(id).setRenderingProperty(property, value); }
double cv::viz::Viz3d::getRenderingProperty(const String &id, int property) { return getWidget(id).getRenderingProperty(property); }
void cv::viz::Viz3d::setRepresentation(int representation) { impl_->setRepresentation(representation); }
void cv::viz::Viz3d::setGlobalWarnings(bool enabled) { vtkObject::SetGlobalWarningDisplay(enabled ? 1 : 0); }
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
// Authors:
// * Ozan Tonkal, ozantonkal@gmail.com
// * Anatoly Baksheev, Itseez Inc. myname.mysurname <> mycompany.com
//
//M*/
#include "precomp.hpp"
cv::Affine3d cv::viz::makeTransformToGlobal(const Vec3d& axis_x, const Vec3d& axis_y, const Vec3d& axis_z, const Vec3d& origin)
{
Affine3d::Mat3 R(axis_x[0], axis_y[0], axis_z[0],
axis_x[1], axis_y[1], axis_z[1],
axis_x[2], axis_y[2], axis_z[2]);
return Affine3d(R, origin);
}
cv::Affine3d cv::viz::makeCameraPose(const Vec3d& position, const Vec3d& focal_point, const Vec3d& y_dir)
{
// Compute the transformation matrix for drawing the camera frame in a scene
Vec3d n = normalize(focal_point - position);
Vec3d u = normalize(y_dir.cross(n));
Vec3d v = n.cross(u);
return makeTransformToGlobal(u, v, n, position);
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// VizStorage implementation
#if defined(_WIN32) && !defined(__CYGWIN__)
#include <windows.h>
static BOOL WINAPI ConsoleHandlerRoutine(DWORD /*dwCtrlType*/)
{
vtkObject::GlobalWarningDisplayOff();
return FALSE;
}
static void register_console_handler()
{
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO hOutInfo;
if (GetConsoleScreenBufferInfo(hOut, &hOutInfo))
SetConsoleCtrlHandler(ConsoleHandlerRoutine, TRUE);
}
#else
void register_console_handler();
void register_console_handler() {}
#endif
cv::viz::VizStorage cv::viz::VizStorage::init;
cv::viz::VizMap cv::viz::VizStorage::storage;
void cv::viz::VizMap::replace_clear() { type().swap(m); }
cv::viz::VizMap::~VizMap() { replace_clear(); }
cv::viz::VizStorage::VizStorage()
{
register_console_handler();
}
void cv::viz::VizStorage::unregisterAll() { storage.replace_clear(); }
cv::viz::Viz3d& cv::viz::VizStorage::get(const String &window_name)
{
String name = generateWindowName(window_name);
VizMap::iterator vm_itr = storage.m.find(name);
CV_Assert(vm_itr != storage.m.end());
return vm_itr->second;
}
void cv::viz::VizStorage::add(const Viz3d& window)
{
String window_name = window.getWindowName();
VizMap::iterator vm_itr = storage.m.find(window_name);
CV_Assert(vm_itr == storage.m.end());
storage.m.insert(std::make_pair(window_name, window));
}
bool cv::viz::VizStorage::windowExists(const String &window_name)
{
String name = generateWindowName(window_name);
return storage.m.find(name) != storage.m.end();
}
void cv::viz::VizStorage::removeUnreferenced()
{
for(VizMap::iterator pos = storage.m.begin(); pos != storage.m.end();)
if(pos->second.impl_->ref_counter == 1)
storage.m.erase(pos++);
else
++pos;
}
cv::String cv::viz::VizStorage::generateWindowName(const String &window_name)
{
String output = "Viz";
// Already is Viz
if (window_name == output)
return output;
String prefixed = output + " - ";
if (window_name.substr(0, prefixed.length()) == prefixed)
output = window_name; // Already has "Viz - "
else if (window_name.substr(0, output.length()) == output)
output = prefixed + window_name; // Doesn't have prefix
else
output = (window_name == "" ? output : prefixed + window_name);
return output;
}
cv::viz::Viz3d cv::viz::getWindowByName(const String &window_name) { return Viz3d (window_name); }
void cv::viz::unregisterAllWindows() { VizStorage::unregisterAll(); }
cv::viz::Viz3d cv::viz::imshow(const String& window_name, InputArray image, const Size& window_size)
{
Viz3d viz = getWindowByName(window_name);
viz.showImage(image, window_size);
return viz;
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Read/write clouds. Supported formats: ply, stl, xyz, obj
void cv::viz::writeCloud(const String& file, InputArray cloud, InputArray colors, InputArray normals, bool binary)
{
CV_Assert(file.size() > 4 && "Extension is required");
String extension = file.substr(file.size()-4);
vtkSmartPointer<vtkCloudMatSource> source = vtkSmartPointer<vtkCloudMatSource>::New();
source->SetColorCloudNormals(cloud, colors, normals);
vtkSmartPointer<vtkWriter> writer;
if (extension == ".xyz")
{
writer = vtkSmartPointer<vtkXYZWriter>::New();
vtkXYZWriter::SafeDownCast(writer)->SetFileName(file.c_str());
}
else if (extension == ".ply")
{
writer = vtkSmartPointer<vtkPLYWriter>::New();
vtkPLYWriter::SafeDownCast(writer)->SetFileName(file.c_str());
vtkPLYWriter::SafeDownCast(writer)->SetFileType(binary ? VTK_BINARY : VTK_ASCII);
vtkPLYWriter::SafeDownCast(writer)->SetArrayName("Colors");
}
else if (extension == ".obj")
{
writer = vtkSmartPointer<vtkOBJWriter>::New();
vtkOBJWriter::SafeDownCast(writer)->SetFileName(file.c_str());
}
else
CV_Error(Error::StsError, "Unsupported format");
writer->SetInputConnection(source->GetOutputPort());
writer->Write();
}
cv::Mat cv::viz::readCloud(const String& file, OutputArray colors, OutputArray normals)
{
CV_Assert(file.size() > 4 && "Extension is required");
String extension = file.substr(file.size()-4);
vtkSmartPointer<vtkPolyDataAlgorithm> reader;
if (extension == ".xyz")
{
reader = vtkSmartPointer<vtkXYZReader>::New();
vtkXYZReader::SafeDownCast(reader)->SetFileName(file.c_str());
}
else if (extension == ".ply")
{
reader = vtkSmartPointer<vtkPLYReader>::New();
CV_Assert(vtkPLYReader::CanReadFile(file.c_str()));
vtkPLYReader::SafeDownCast(reader)->SetFileName(file.c_str());
}
else if (extension == ".obj")
{
reader = vtkSmartPointer<vtkOBJReader>::New();
vtkOBJReader::SafeDownCast(reader)->SetFileName(file.c_str());
}
else if (extension == ".stl")
{
reader = vtkSmartPointer<vtkSTLReader>::New();
vtkSTLReader::SafeDownCast(reader)->SetFileName(file.c_str());
}
else
CV_Error(Error::StsError, "Unsupported format");
cv::Mat cloud;
vtkSmartPointer<vtkCloudMatSink> sink = vtkSmartPointer<vtkCloudMatSink>::New();
sink->SetInputConnection(reader->GetOutputPort());
sink->SetOutput(cloud, colors, normals);
sink->Write();
return cloud;
}
cv::viz::Mesh cv::viz::readMesh(const String& file) { return Mesh::load(file); }
///////////////////////////////////////////////////////////////////////////////////////////////
/// Read/write poses and trajectories
bool cv::viz::readPose(const String& file, Affine3d& pose, const String& tag)
{
FileStorage fs(file, FileStorage::READ);
if (!fs.isOpened())
return false;
Mat hdr(pose.matrix, false);
fs[tag] >> hdr;
if (hdr.empty() || hdr.cols != pose.matrix.cols || hdr.rows != pose.matrix.rows)
return false;
hdr.convertTo(pose.matrix, CV_64F);
return true;
}
void cv::viz::writePose(const String& file, const Affine3d& pose, const String& tag)
{
FileStorage fs(file, FileStorage::WRITE);
fs << tag << Mat(pose.matrix, false);
}
void cv::viz::readTrajectory(OutputArray _traj, const String& files_format, int start, int end, const String& tag)
{
CV_Assert(_traj.kind() == _InputArray::STD_VECTOR || _traj.kind() == _InputArray::MAT);
start = max(0, std::min(start, end));
end = std::max(start, end);
std::vector<Affine3d> traj;
for(int i = start; i < end; ++i)
{
Affine3d affine;
bool ok = readPose(cv::format(files_format.c_str(), i), affine, tag);
if (!ok)
break;
traj.push_back(affine);
}
Mat(traj).convertTo(_traj, _traj.depth());
}
void cv::viz::writeTrajectory(InputArray _traj, const String& files_format, int start, const String& tag)
{
if (_traj.kind() == _InputArray::STD_VECTOR_MAT)
{
#if CV_MAJOR_VERSION < 3
std::vector<Mat>& v = *(std::vector<Mat>*)_traj.obj;
#else
std::vector<Mat>& v = *(std::vector<Mat>*)_traj.getObj();
#endif
for(size_t i = 0, index = max(0, start); i < v.size(); ++i, ++index)
{
Affine3d affine;
Mat pose = v[i];
CV_Assert(pose.type() == CV_32FC(16) || pose.type() == CV_64FC(16));
pose.copyTo(affine.matrix);
writePose(cv::format(files_format.c_str(), index), affine, tag);
}
return;
}
if (_traj.kind() == _InputArray::STD_VECTOR || _traj.kind() == _InputArray::MAT)
{
CV_Assert(_traj.type() == CV_32FC(16) || _traj.type() == CV_64FC(16));
Mat traj = _traj.getMat();
if (traj.depth() == CV_32F)
for(size_t i = 0, index = max(0, start); i < traj.total(); ++i, ++index)
writePose(cv::format(files_format.c_str(), index), traj.at<Affine3f>((int)i), tag);
if (traj.depth() == CV_64F)
for(size_t i = 0, index = max(0, start); i < traj.total(); ++i, ++index)
writePose(cv::format(files_format.c_str(), index), traj.at<Affine3d>((int)i), tag);
return;
}
CV_Error(Error::StsError, "Unsupported array kind");
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Computing normals for mesh
void cv::viz::computeNormals(const Mesh& mesh, OutputArray _normals)
{
vtkSmartPointer<vtkPolyData> polydata = getPolyData(WMesh(mesh));
vtkSmartPointer<vtkPolyData> with_normals = VtkUtils::ComputeNormals(polydata);
vtkSmartPointer<vtkDataArray> generic_normals = with_normals->GetPointData()->GetNormals();
if(generic_normals)
{
Mat normals(1, generic_normals->GetNumberOfTuples(), CV_64FC3);
Vec3d *optr = normals.ptr<Vec3d>();
for(int i = 0; i < generic_normals->GetNumberOfTuples(); ++i, ++optr)
generic_normals->GetTuple(i, optr->val);
normals.convertTo(_normals, mesh.cloud.type());
}
else
_normals.release();
}
此差异已折叠。
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
// Authors:
// * Ozan Tonkal, ozantonkal@gmail.com
// * Anatoly Baksheev, Itseez Inc. myname.mysurname <> mycompany.com
//
//M*/
#ifndef __OPENCV_VIZ_VIZ3D_IMPL_HPP__
#define __OPENCV_VIZ_VIZ3D_IMPL_HPP__
struct cv::viz::Viz3d::VizImpl
{
public:
typedef Viz3d::KeyboardCallback KeyboardCallback;
typedef Viz3d::MouseCallback MouseCallback;
int ref_counter;
VizImpl(const String &name);
virtual ~VizImpl();
bool wasStopped() const;
void close();
void spin();
void spinOnce(int time = 1, bool force_redraw = false);
void setOffScreenRendering();
void removeAllLights();
void addLight(Vec3d position, Vec3d focalPoint, const Color &color, const Color &diffuseColor,
const Color &ambientColor, const Color &specularColor);
void showWidget(const String &id, const Widget &widget, const Affine3d &pose = Affine3d::Identity());
void removeWidget(const String &id);
Widget getWidget(const String &id) const;
void removeAllWidgets();
void showImage(InputArray image, const Size& window_size);
void setWidgetPose(const String &id, const Affine3d &pose);
void updateWidgetPose(const String &id, const Affine3d &pose);
Affine3d getWidgetPose(const String &id) const;
void setRepresentation(int representation);
void setCamera(const Camera &camera);
Camera getCamera() const;
/** \brief Reset the camera to a given widget */
void resetCameraViewpoint(const String& id);
void resetCamera();
void setViewerPose(const Affine3d &pose);
Affine3d getViewerPose() const;
void convertToWindowCoordinates(const Point3d &pt, Point3d &window_coord);
void converTo3DRay(const Point3d &window_coord, Point3d &origin, Vec3d &direction);
Mat getScreenshot() const;
void saveScreenshot(const String &file);
void setWindowPosition(const Point& position);
Size getWindowSize() const;
void setWindowSize(const Size& window_size);
void setFullScreen(bool mode);
String getWindowName() const;
void setBackgroundColor(const Color& color, const Color& color2);
void setBackgroundTexture(InputArray image);
void setBackgroundMeshLab();
void registerKeyboardCallback(KeyboardCallback callback, void* cookie = 0);
void registerMouseCallback(MouseCallback callback, void* cookie = 0);
private:
struct TimerCallback : public vtkCommand
{
static TimerCallback* New() { return new TimerCallback; }
virtual void Execute(vtkObject* caller, unsigned long event_id, void* cookie);
int timer_id;
};
struct ExitCallback : public vtkCommand
{
static ExitCallback* New() { return new ExitCallback; }
virtual void Execute(vtkObject*, unsigned long event_id, void*);
VizImpl* viz;
};
mutable bool spin_once_state_;
vtkSmartPointer<vtkRenderWindowInteractor> interactor_;
vtkSmartPointer<vtkRenderWindow> window_;
String window_name_;
Vec2i window_position_;
vtkSmartPointer<TimerCallback> timer_callback_;
vtkSmartPointer<ExitCallback> exit_callback_;
vtkSmartPointer<vtkRenderer> renderer_;
vtkSmartPointer<vtkVizInteractorStyle> style_;
Ptr<WidgetActorMap> widget_actor_map_;
bool offScreenMode_;
bool removeActorFromRenderer(vtkSmartPointer<vtkProp> actor);
void recreateRenderWindow();
};
#endif
此差异已折叠。
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
// Authors:
// * Anatoly Baksheev, Itseez Inc. myname.mysurname <> mycompany.com
//
//M*/
#ifndef __vtkCloudMatSink_h
#define __vtkCloudMatSink_h
#include <opencv2/core.hpp>
#include <vtkWriter.h>
namespace cv
{
namespace viz
{
class vtkCloudMatSink : public vtkWriter
{
public:
static vtkCloudMatSink *New();
vtkTypeMacro(vtkCloudMatSink,vtkWriter)
void PrintSelf(ostream& os, vtkIndent indent);
void SetOutput(OutputArray cloud, OutputArray colors = noArray(), OutputArray normals = noArray(), OutputArray tcoords = noArray());
// Description:
// Get the input to this writer.
vtkPolyData* GetInput();
vtkPolyData* GetInput(int port);
protected:
vtkCloudMatSink();
~vtkCloudMatSink();
void WriteData();
int FillInputPortInformation(int port, vtkInformation *info);
_OutputArray cloud; //!< point coordinates of type CV_32FC3 or CV_64FC3 with only 1 row
_OutputArray colors; //!< point color of type CV_8UC3 or CV_8UC4 with only 1 row
_OutputArray normals; //!< point normal of type CV_32FC3, CV_32FC4, CV_64FC3 or CV_64FC4 with only 1 row
_OutputArray tcoords; //!< texture coordinates of type CV_32FC2 or CV_64FC2 with only 1 row
private:
vtkCloudMatSink(const vtkCloudMatSink&); // Not implemented.
void operator=(const vtkCloudMatSink&); // Not implemented.
};
} // end namespace viz
} // end namespace cv
#endif
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#include "test_precomp.hpp"
CV_TEST_MAIN("viz")
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#include "opencv2/ts.hpp"
#include "test_common.hpp"
namespace opencv_test
{
using namespace cv::viz;
}
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册