viz3d_impl.hpp 17.3 KB
Newer Older
1 2
#pragma once

Anatoly Baksheev's avatar
Anatoly Baksheev committed
3
#include <opencv2/viz.hpp>
Anatoly Baksheev's avatar
Anatoly Baksheev committed
4 5 6
#include "interactor_style.h"
#include "viz_types.h"
#include "common.h"
7

Anatoly Baksheev's avatar
Anatoly Baksheev committed
8
struct cv::viz::Viz3d::VizImpl
9 10 11
{
public:
    typedef cv::Ptr<VizImpl> Ptr;
Anatoly Baksheev's avatar
Anatoly Baksheev committed
12 13
    typedef Viz3d::KeyboardCallback KeyboardCallback;
    typedef Viz3d::MouseCallback MouseCallback;
14 15
    
    int ref_counter;
16

Anatoly Baksheev's avatar
Anatoly Baksheev committed
17
    VizImpl (const String &name);
18 19 20
    virtual ~VizImpl ();


21 22 23 24 25 26 27 28







    //to refactor
29
    bool removePointCloud (const String& id = "cloud");
30
    inline bool removePolygonMesh (const String& id = "polygon") { return removePointCloud (id); }
31 32
    bool removeShape (const String& id = "cloud");
    bool removeText3D (const String& id = "cloud");
33 34
    bool removeAllPointClouds ();

35 36
    //create Viz3d::removeAllWidgets()
    bool removeAllShapes ();
37

38
    //to refactor
39 40 41
    bool addPolygonMesh (const Mesh3d& mesh, const cv::Mat& mask, const String& id = "polygon");
    bool updatePolygonMesh (const Mesh3d& mesh, const cv::Mat& mask, const String& id = "polygon");
    bool addPolylineFromPolygonMesh (const Mesh3d& mesh, const String& id = "polyline");
42

43
    // to refactor: Widget3D:: & Viz3d::
44 45 46
    bool setPointCloudRenderingProperties (int property, double value, const String& id = "cloud");
    bool getPointCloudRenderingProperties (int property, double &value, const String& id = "cloud");
    bool setShapeRenderingProperties (int property, double value, const String& id);
47 48 49 50 51

    /** \brief Set whether the point cloud is selected or not
         *  \param[in] selected whether the cloud is selected or not (true = selected)
         *  \param[in] id the point cloud object id (default: cloud)
         */
52
    // probably should just remove
53
    bool setPointCloudSelected (const bool selected, const String& id = "cloud" );
54

55 56 57 58 59 60 61







62 63 64 65 66 67 68 69 70 71
    /** \brief Returns true when the user tried to close the window */
    bool wasStopped () const { if (interactor_ != NULL) return (stopped_); else return true; }

    /** \brief Set the stopped flag back to false */
    void resetStoppedFlag () { if (interactor_ != NULL) stopped_ = false; }

    /** \brief Stop the interaction and close the visualizaton window. */
    void close ()
    {
        stopped_ = true;
72
        interactor_->TerminateApp (); // This tends to close the window...
73
    }
74 75 76 77 78 79 80 81 82 83










ozantonkal's avatar
ozantonkal committed
84
    
85
    // to refactor
86 87 88
    bool addPolygon(const cv::Mat& cloud, const Color& color, const String& id = "polygon");
    bool addArrow (const Point3f& pt1, const Point3f& pt2, const Color& color, bool display_length, const String& id = "arrow");
    bool addArrow (const Point3f& pt1, const Point3f& pt2, const Color& color_line, const Color& color_text, const String& id = "arrow");
89

90
    // Probably remove this
91 92
    bool addModelFromPolyData (vtkSmartPointer<vtkPolyData> polydata, const String& id = "PolyData");
    bool addModelFromPolyData (vtkSmartPointer<vtkPolyData> polydata, vtkSmartPointer<vtkTransform> transform, const String& id = "PolyData");
93 94

    // I think this should be moved to 'static Widget Widget::fromPlyFile(const String&)';
95 96
    bool addModelFromPLYFile (const String &filename, const String& id = "PLYModel");
    bool addModelFromPLYFile (const String &filename, vtkSmartPointer<vtkTransform> transform, const String& id = "PLYModel");
97 98


99 100 101 102 103 104
    // to implement in Viz3d with shorter name
    void setRepresentationToSurfaceForAllActors();
    void setRepresentationToPointsForAllActors();
    void setRepresentationToWireframeForAllActors();


105 106 107 108 109 110






111 112 113
    // ////////////////////////////////////////////////////////////////////////////////////
    // All camera methods to refactor into set/getViewwerPose, setCamera()
    // and 'Camera' class itself with various constructors/fields
114
    
115 116
    void setCamera(const Camera &camera);
    Camera getCamera() const;
117 118 119 120 121

    void initCameraParameters (); /** \brief Initialize camera parameters with some default values. */
    bool cameraParamsSet () const; /** \brief Checks whether the camera parameters were manually loaded from file.*/
    void updateCamera (); /** \brief Update camera parameters and render. */
    void resetCamera (); /** \brief Reset camera parameters and render. */
122 123

    /** \brief Reset the camera direction from {0, 0, 0} to the center_{x, y, z} of a given dataset.
124
      * \param[in] id the point cloud object id (default: cloud) */
125
    void resetCameraViewpoint (const String& id = "cloud");
126
    
127
    //to implement Viz3d set/getViewerPose()
128
    void setViewerPose(const Affine3f &pose);
129 130
    Affine3f getViewerPose();

131 132
    void convertToWindowCoordinates(const Point3d &pt, Point3d &window_coord);
    void converTo3DRay(const Point3d &window_coord, Point3d &origin, Vec3d &direction);
133 134 135 136 137 138 139 140







    //to implemnt in Viz3d
141
    void saveScreenshot (const String &file);
142
    void setWindowPosition (int x, int y);
143
    Size getWindowSize() const;
144 145 146
    void setWindowSize (int xw, int yw);
    void setFullScreen (bool mode);
    void setWindowName (const String &name);
147
    String getWindowName() const;
148
    void setBackgroundColor (const Color& color);
149

150 151
    void spin ();
    void spinOnce (int time = 1, bool force_redraw = false);
152

153 154 155 156 157 158 159 160 161 162 163
    void registerKeyboardCallback(KeyboardCallback callback, void* cookie = 0);
    void registerMouseCallback(MouseCallback callback, void* cookie = 0);








    //declare above (to move to up)
164
    void showWidget(const String &id, const Widget &widget, const Affine3f &pose = Affine3f::Identity());
165 166
    void removeWidget(const String &id);
    Widget getWidget(const String &id) const;
167
    
168 169
    void setWidgetPose(const String &id, const Affine3f &pose);
    void updateWidgetPose(const String &id, const Affine3f &pose);
Anatoly Baksheev's avatar
Anatoly Baksheev committed
170
    Affine3f getWidgetPose(const String &id) const; 
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236

private:
    vtkSmartPointer<vtkRenderWindowInteractor> interactor_;

    struct ExitMainLoopTimerCallback : public vtkCommand
    {
        static ExitMainLoopTimerCallback* New()
        {
            return new ExitMainLoopTimerCallback;
        }
        virtual void Execute(vtkObject* vtkNotUsed(caller), unsigned long event_id, void* call_data)
        {
            if (event_id != vtkCommand::TimerEvent)
                return;

            int timer_id = *reinterpret_cast<int*> (call_data);
            if (timer_id != right_timer_id)
                return;

            // Stop vtk loop and send notification to app to wake it up
            viz_->interactor_->TerminateApp ();
        }
        int right_timer_id;
        VizImpl* viz_;
    };

    struct ExitCallback : public vtkCommand
    {
        static ExitCallback* New ()
        {
            return new ExitCallback;
        }
        virtual void Execute (vtkObject*, unsigned long event_id, void*)
        {
            if (event_id == vtkCommand::ExitEvent)
            {
                viz_->stopped_ = true;
                viz_->interactor_->TerminateApp ();
            }
        }
        VizImpl* viz_;
    };

    /** \brief Set to false if the interaction loop is running. */
    bool stopped_;

    double s_lastDone_;

    /** \brief Global timer ID. Used in destructor only. */
    int timer_id_;

    /** \brief Callback object enabling us to leave the main loop, when a timer fires. */
    vtkSmartPointer<ExitMainLoopTimerCallback> exit_main_loop_timer_callback_;
    vtkSmartPointer<ExitCallback> exit_callback_;

    vtkSmartPointer<vtkRenderer> renderer_;
    vtkSmartPointer<vtkRenderWindow> window_;

    /** \brief The render window interactor style. */
    vtkSmartPointer<InteractorStyle> style_;

    /** \brief Internal list with actor pointers and name IDs for point clouds. */
    cv::Ptr<CloudActorMap> cloud_actor_map_;

    /** \brief Internal list with actor pointers and name IDs for shapes. */
    cv::Ptr<ShapeActorMap> shape_actor_map_;
237 238 239
    
    /** \brief Internal list with actor pointers and name IDs for all widget actors */
    cv::Ptr<WidgetActorMap> widget_actor_map_;
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272

    /** \brief Boolean that holds whether or not the camera parameters were manually initialized*/
    bool camera_set_;

    bool removeActorFromRenderer (const vtkSmartPointer<vtkLODActor> &actor);
    bool removeActorFromRenderer (const vtkSmartPointer<vtkActor> &actor);
    bool removeActorFromRenderer (const vtkSmartPointer<vtkProp> &actor);

    //void addActorToRenderer (const vtkSmartPointer<vtkProp> &actor);


    /** \brief Internal method. Creates a vtk actor from a vtk polydata object.
          * \param[in] data the vtk polydata object to create an actor for
          * \param[out] actor the resultant vtk actor object
          * \param[in] use_scalars set scalar properties to the mapper if it exists in the data. Default: true.
          */
    void createActorFromVTKDataSet (const vtkSmartPointer<vtkDataSet> &data, vtkSmartPointer<vtkLODActor> &actor, bool use_scalars = true);

    /** \brief Updates a set of cells (vtkIdTypeArray) if the number of points in a cloud changes
          * \param[out] cells the vtkIdTypeArray object (set of cells) to update
          * \param[out] initcells a previously saved set of cells. If the number of points in the current cloud is
          * higher than the number of cells in \a cells, and initcells contains enough data, then a copy from it
          * will be made instead of regenerating the entire array.
          * \param[in] nr_points the number of points in the new cloud. This dictates how many cells we need to
          * generate
          */
    void updateCells (vtkSmartPointer<vtkIdTypeArray> &cells, vtkSmartPointer<vtkIdTypeArray> &initcells, vtkIdType nr_points);

    void allocVtkPolyData (vtkSmartPointer<vtkAppendPolyData> &polydata);
    void allocVtkPolyData (vtkSmartPointer<vtkPolyData> &polydata);
    void allocVtkUnstructuredGrid (vtkSmartPointer<vtkUnstructuredGrid> &polydata);
};

Anatoly Baksheev's avatar
Anatoly Baksheev committed
273 274


Anatoly Baksheev's avatar
Anatoly Baksheev committed
275
namespace cv
Anatoly Baksheev's avatar
Anatoly Baksheev committed
276
{
Anatoly Baksheev's avatar
Anatoly Baksheev committed
277 278 279 280 281
    namespace viz
    {
        //void getTransformationMatrix (const Eigen::Vector4f &origin, const Eigen::Quaternionf& orientation, Eigen::Matrix4f &transformation);
        vtkSmartPointer<vtkMatrix4x4> convertToVtkMatrix (const cv::Matx44f &m);
        cv::Matx44f convertToMatx(const vtkSmartPointer<vtkMatrix4x4>& vtk_matrix);
282

Anatoly Baksheev's avatar
Anatoly Baksheev committed
283 284 285 286 287 288
        /** \brief Convert origin and orientation to vtkMatrix4x4
              * \param[in] origin the point cloud origin
              * \param[in] orientation the point cloud orientation
              * \param[out] vtk_matrix the resultant VTK 4x4 matrix
              */
        void convertToVtkMatrix (const Eigen::Vector4f &origin, const Eigen::Quaternion<float> &orientation, vtkSmartPointer<vtkMatrix4x4> &vtk_matrix);
289

Anatoly Baksheev's avatar
Anatoly Baksheev committed
290
        struct NanFilter
291
        {
Anatoly Baksheev's avatar
Anatoly Baksheev committed
292 293
            template<typename _Tp, typename _Msk>
            struct Impl
294
            {
Anatoly Baksheev's avatar
Anatoly Baksheev committed
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
                typedef Vec<_Tp, 3> _Out;

                static _Out* copy(const Mat& source, _Out* output, const Mat& nan_mask)
                {
                    CV_Assert(DataDepth<_Tp>::value == source.depth() && source.size() == nan_mask.size());
                    CV_Assert(nan_mask.channels() == 3 || nan_mask.channels() == 4);
                    CV_DbgAssert(DataDepth<_Msk>::value == nan_mask.depth());

                    int s_chs = source.channels();
                    int m_chs = nan_mask.channels();

                    for(int y = 0; y < source.rows; ++y)
                    {
                        const _Tp* srow = source.ptr<_Tp>(y);
                        const _Msk* mrow = nan_mask.ptr<_Msk>(y);

                        for(int x = 0; x < source.cols; ++x, srow += s_chs, mrow += m_chs)
                            if (!isNan(mrow[0]) && !isNan(mrow[1]) && !isNan(mrow[2]))
                                *output++ = _Out(srow);
                    }
                    return output;
                }
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
                
                static _Out* copyColor(const Mat& source, _Out* output, const Mat& nan_mask)
                {
                    CV_Assert(DataDepth<_Tp>::value == source.depth() && source.size() == nan_mask.size());
                    CV_Assert(nan_mask.channels() == 3 || nan_mask.channels() == 4);
                    CV_DbgAssert(DataDepth<_Msk>::value == nan_mask.depth());

                    int s_chs = source.channels();
                    int m_chs = nan_mask.channels();

                    for(int y = 0; y < source.rows; ++y)
                    {
                        const _Tp* srow = source.ptr<_Tp>(y);
                        const _Msk* mrow = nan_mask.ptr<_Msk>(y);

                        for(int x = 0; x < source.cols; ++x, srow += s_chs, mrow += m_chs)
                            if (!isNan(mrow[0]) && !isNan(mrow[1]) && !isNan(mrow[2]))
                            {
                                *output = _Out(srow);
                                std::swap((*output)[0], (*output)[2]); // BGR -> RGB
                                ++output;
                            }
                    }
                    return output;
                }
Anatoly Baksheev's avatar
Anatoly Baksheev committed
342 343 344 345 346 347
            };

            template<typename _Tp>
            static inline Vec<_Tp, 3>* copy(const Mat& source, Vec<_Tp, 3>* output, const Mat& nan_mask)
            {
                CV_Assert(nan_mask.depth() == CV_32F || nan_mask.depth() == CV_64F);
348

Anatoly Baksheev's avatar
Anatoly Baksheev committed
349 350
                typedef Vec<_Tp, 3>* (*copy_func)(const Mat&, Vec<_Tp, 3>*, const Mat&);
                const static copy_func table[2] = { &NanFilter::Impl<_Tp, float>::copy, &NanFilter::Impl<_Tp, double>::copy };
351

Anatoly Baksheev's avatar
Anatoly Baksheev committed
352 353
                return table[nan_mask.depth() - 5](source, output, nan_mask);
            }
354 355 356 357 358 359 360 361 362 363 364
            
            template<typename _Tp>
            static inline Vec<_Tp, 3>* copyColor(const Mat& source, Vec<_Tp, 3>* output, const Mat& nan_mask)
            {
                CV_Assert(nan_mask.depth() == CV_32F || nan_mask.depth() == CV_64F);

                typedef Vec<_Tp, 3>* (*copy_func)(const Mat&, Vec<_Tp, 3>*, const Mat&);
                const static copy_func table[2] = { &NanFilter::Impl<_Tp, float>::copyColor, &NanFilter::Impl<_Tp, double>::copyColor };

                return table[nan_mask.depth() - 5](source, output, nan_mask);
            }
Anatoly Baksheev's avatar
Anatoly Baksheev committed
365
        };
366

Anatoly Baksheev's avatar
Anatoly Baksheev committed
367 368 369 370
        struct ApplyAffine
        {
            const Affine3f& affine_;
            ApplyAffine(const Affine3f& affine) : affine_(affine) {}
371

Anatoly Baksheev's avatar
Anatoly Baksheev committed
372
            template<typename _Tp> Point3_<_Tp> operator()(const Point3_<_Tp>& p) const { return affine_ * p; }
373

Anatoly Baksheev's avatar
Anatoly Baksheev committed
374 375 376
            template<typename _Tp> Vec<_Tp, 3> operator()(const Vec<_Tp, 3>& v) const
            {
                const float* m = affine_.matrix.val;
377

Anatoly Baksheev's avatar
Anatoly Baksheev committed
378 379 380 381 382 383
                Vec<_Tp, 3> result;
                result[0] = (_Tp)(m[0] * v[0] + m[1] * v[1] + m[ 2] * v[2] + m[ 3]);
                result[1] = (_Tp)(m[4] * v[0] + m[5] * v[1] + m[ 6] * v[2] + m[ 7]);
                result[2] = (_Tp)(m[8] * v[0] + m[9] * v[1] + m[10] * v[2] + m[11]);
                return result;
            }
384

Anatoly Baksheev's avatar
Anatoly Baksheev committed
385 386 387 388
        private:
            ApplyAffine(const ApplyAffine&);
            ApplyAffine& operator=(const ApplyAffine&);
        };
Anatoly Baksheev's avatar
Anatoly Baksheev committed
389 390 391 392 393 394 395 396 397 398 399


        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 vtkpoint(const Point3f& point) { return Vec3d(point.x, point.y, point.z); }
        template<typename _Tp> inline _Tp normalized(const _Tp& v) { return v * 1/cv::norm(v); }
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
        
        struct ConvertToVtkImage
        {
            struct Impl
            {
                static void copyImageMultiChannel(const Mat &image, vtkSmartPointer<vtkImageData> output)
                {
                    int i_chs = image.channels();
            
                    for (int i = 0; i < image.rows; ++i)
                    {
                        const unsigned char * irows = image.ptr<unsigned char>(i);
                        for (int j = 0; j < image.cols; ++j, irows += i_chs)
                        {
                            unsigned char * vrows = static_cast<unsigned char *>(output->GetScalarPointer(j,i,0));
                            memcpy(vrows, irows, i_chs);
                            std::swap(vrows[0], vrows[2]); // BGR -> RGB
                        }
                    }
                    output->Modified();
                }
                
                static void copyImageSingleChannel(const Mat &image, vtkSmartPointer<vtkImageData> output)
                {
                    for (int i = 0; i < image.rows; ++i)
                    {
                        const unsigned char * irows = image.ptr<unsigned char>(i);
                        for (int j = 0; j < image.cols; ++j, ++irows)
                        {
                            unsigned char * vrows = static_cast<unsigned char *>(output->GetScalarPointer(j,i,0));
                            *vrows = *irows;
                        }
                    }
                    output->Modified();
                }
            };
            
            static void convert(const Mat &image, vtkSmartPointer<vtkImageData> output)
            {
                // Create the vtk image
                output->SetDimensions(image.cols, image.rows, 1);
                output->SetNumberOfScalarComponents(image.channels());
                output->SetScalarTypeToUnsignedChar();
                output->AllocateScalars();
                
                int i_chs = image.channels();
                if (i_chs > 1)
                {
                    // Multi channel images are handled differently because of BGR <-> RGB
                    Impl::copyImageMultiChannel(image, output);
                }
                else
                {
                    Impl::copyImageSingleChannel(image, output);
                }
            }
        };
457
    }
458

459 460
}