diff --git a/Modules/AlgorithmsExt/include/mitkCovarianceMatrixCalculator.h b/Modules/AlgorithmsExt/include/mitkCovarianceMatrixCalculator.h index f169c576e2..671485285f 100644 --- a/Modules/AlgorithmsExt/include/mitkCovarianceMatrixCalculator.h +++ b/Modules/AlgorithmsExt/include/mitkCovarianceMatrixCalculator.h @@ -1,118 +1,118 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __MITK_COVARIANCEMATRIXCALCULATOR_H__ #define __MITK_COVARIANCEMATRIXCALCULATOR_H__ // exports #include "MitkAlgorithmsExtExports.h" #include #include #include #include namespace mitk { // forward declarations class Surface; struct CovarianceMatrixCalculatorData; /** * \ingroup AnisotropicRegistration * * @brief Class that computes the covariance matrices for every point in a * {@link Surface} used in the A-ICP algorithm. * * Computes a covariance matrix for every vertex in a given {@link Surface} * based on it's direct neighbours and saves them into a CovarianceMatrixList. * The Class implements the CM_PCA method presented by * L. Maier-Hein et al. in "Convergent Iterative Closest-Point Algorithm * to Accomodate Anisotropic and Inhomogenous Localization Error.", * IEEE T Pattern Anal 34 (8), 1520-1532, 2012. The algorithm needs * a clean Surface with non manifold edges and no duplicated vertices. To * ensure a clean Surface representation use vtkCleanPolyData. */ class MITKALGORITHMSEXT_EXPORT CovarianceMatrixCalculator : public itk::Object { private: /** Pimpl to hold private data.*/ CovarianceMatrixCalculatorData *d; protected: // local typedefs /** Definition of the covariance matrix.*/ typedef itk::Matrix CovarianceMatrix; /** Definition of a list of covariance matrices */ typedef std::vector CovarianceMatrixList; typedef double Vertex[3]; /** List that stores the computed covariance matrices. */ CovarianceMatrixList m_CovarianceMatrixList; /** This method projects all surrounding vertices of given vertex in a Surface * in the normal direction onto a plane and computes a primary component * analysis on the projected vertices. In the next step a orthonormal * system is created. * - * @param The index of the input Vertex in the Surface. - * @param The normal of the input Vertex. - * @param Output CovarianceMatrix of the principal component analysis. - * @param Output. Variances along the axes of the createt Orthonormal system. - * @param Output. The current Vertex in the surface + * @param index The index of the input Vertex in the Surface. + * @param normal The normal of the input Vertex. + * @param principalComponents CovarianceMatrix of the principal component analysis. + * @param variances Variances along the axes of the createt Orthonormal system. + * @param curVertex The current Vertex in the surface * */ void ComputeOrthonormalCoordinateSystem( const int index, Vertex normal, CovarianceMatrix &principalComponents, Vertex variances, Vertex curVertex); CovarianceMatrixCalculator(); ~CovarianceMatrixCalculator() override; public: mitkClassMacroItkParent(CovarianceMatrixCalculator, itk::Object); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** Sets the scaling factor for the voronoi area. * @param factor The scaling factor. */ void SetVoronoiScalingFator(const double factor); /** Enables/disables the covariance matrix normalization. * @param state Enables the covariance matrix normalization. */ void EnableNormalization(bool state); /** Returns the mean of variance of all computed covariance matrices. * @return The mean variance. */ double GetMeanVariance() const; /** Returns a reference to the CovarianceMatrixList with the computed covariance matrices. * @return A CovarianceMatrixList. */ const CovarianceMatrixList &GetCovarianceMatrices() const; /** Sets the input {@link Surface} for which the covariance matrices will be calculated. * @param input A {@link Surface}. */ void SetInputSurface(Surface *input); /** Method that computes the covariance matrices for the input surface. * @throws std::exception If the input surface is not set. */ void ComputeCovarianceMatrices(); }; } #endif diff --git a/Modules/AlgorithmsExt/include/mitkWeightedPointTransform.h b/Modules/AlgorithmsExt/include/mitkWeightedPointTransform.h index 61f43b27c5..3d8ce63fa1 100644 --- a/Modules/AlgorithmsExt/include/mitkWeightedPointTransform.h +++ b/Modules/AlgorithmsExt/include/mitkWeightedPointTransform.h @@ -1,248 +1,247 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __WEIGHTEDPOINTTRANSFORM_H__ #define __WEIGHTEDPOINTTRANSFORM_H__ // EXPORTS #include "MitkAlgorithmsExtExports.h" // ITK #include #include #include #include #include #include // forward declarations class vtkPoints; class vtkLandmarkTransform; namespace mitk { /** * \ingroup AnisotropicRegistration * * @brief This class implements an extension of the * weighted point based registration algorithm * from A. Danilchenko, R. Balachandran and J. M. Fitzpatrick. * * The class implements an extension of the weighted point based registration * from A. Danilchenko et al. * presented by L. Maier-Hein et al. in "Convergent Iterative Closest-Point Algorithm * to Accomodate Anisotropic and Inhomogenous Localization Error.", * IEEE T Pattern Anal 34 (8), 1520-1532, 2012. The extension computes, in order * to ensure the convergence of the algorithm, an isotropic estimation * by an unweighted point based registration algorithm as an initial estimate. * The implemantion was originally ported to C/C++ by A. Franz. * * \note Some methods are accelerated when OpenMP is enabled. * */ class MITKALGORITHMSEXT_EXPORT WeightedPointTransform : public itk::Object { /** Definition of a 3x3 matrix.*/ typedef itk::Matrix Matrix3x3; /** Definition of a 3x3 Weighting matrix.*/ typedef Matrix3x3 WeightMatrix; /** Definition of a Rotation matrix.*/ typedef Matrix3x3 Rotation; /** Definition of a translation vector.*/ typedef itk::Vector Translation; /** Definition of a weight matrix list.*/ typedef std::vector WeightMatrixList; /** Definition of a covariance matrix list.*/ typedef std::vector CovarianceMatrixList; public: mitkClassMacroItkParent(WeightedPointTransform, itk::Object); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** @brief Method which registers both point sets. */ void ComputeTransformation(); /** @brief Sets the threshold of the registration. Default value is 0.0001.*/ itkSetMacro(Threshold, double); /** @brief Sets the maximum number of iterations of the registration. * Default value is 1000. */ itkSetMacro(MaxIterations, double); /** @return Returns the number of iterations of the last run * of the registration algorithm. Returns -1 if there was no * run of the registration yet. */ itkGetMacro(Iterations, int); /** @return Returns the FRE of the last run of the registration algorithm. * Returns -1 if there was no run of the registration yet. */ itkGetMacro(FRE, double); /** @brief Sets the FRE normalization factor. Default value is 1.0. */ itkSetMacro(FRENormalizationFactor, double); /** @return Returns the current FRE normalization factor.*/ itkGetMacro(FRENormalizationFactor, double); /** Sets the moving point set used for the registration. * @param p The input point set. */ void SetMovingPointSet(vtkSmartPointer p); /** * Set the list of 3x3 covariance matrices belonging to the moving point set. * @param matrices List of covariance matrices. */ void SetCovarianceMatricesMoving(const CovarianceMatrixList &matrices); /** Sets the fixed point set used for the registration. * @param p The input point set. */ void SetFixedPointSet(vtkSmartPointer p); /** * Set the list of 3x3 covariance matrices belonging to the fixed point set. * @param matrices List of covariance matrices. */ void SetCovarianceMatricesFixed(const CovarianceMatrixList &matrices); /** * The translation vector computed by the algorithm. * @return 3x1 translation vector. */ const Translation &GetTransformT() const { return m_Translation; } /** * The rotation matrix computed by the algorithm. */ const Rotation &GetTransformR() const { return m_Rotation; } protected: WeightedPointTransform(); ~WeightedPointTransform() override; /** Threshold used to terminate the algorithm.*/ double m_Threshold; /** Max allowed iterations used by the algorithm.*/ int m_MaxIterations; /** The amount of iterations needed by the algorithm.*/ int m_Iterations; /** The fiducial registration error (FRE) used in the algorithm.*/ double m_FRE; /** Normalization factor for the FRE.*/ double m_FRENormalizationFactor; /** Isotropic point based registration used for initial estimate.*/ vtkSmartPointer m_LandmarkTransform; /** The fixed point set (Y).*/ vtkSmartPointer m_FixedPointSet; /** Moving point set (X).*/ vtkSmartPointer m_MovingPointSet; /** Covariance matrices of the moving point set (Sigma_X).*/ CovarianceMatrixList m_CovarianceMatricesMoving; /** Covariance matrices of the moving point set (Sigma_Y).*/ CovarianceMatrixList m_CovarianceMatricesFixed; /** 3x1 translation vector.*/ Translation m_Translation; /** 3x3 rotation matrix.*/ Rotation m_Rotation; /** * original matlab-function: * * Constructs the C matrix of the linear version of the registration * problem, Cq = e, where q = [delta_angle(1:3),delta_translation(1:3)] and * e is produced by e_maker(X,Y,W) * * Authors: JM Fitzpatrick and R Balachandran * Creation: February 2009 * * -------------------------------------------- * * converted to C++ by Alfred Franz in March/April 2010 */ void C_maker(vtkPoints *X, const WeightMatrixList &W, itk::VariableSizeMatrix &returnValue); /** * original matlab-function: * * Constructs the e vector of the linear version of the registration * problem, Cq = e, where q = [delta_angle(1:3),delta_translation(1:3)] and * C is produced by C_maker(X,W) * * Authors: JM Fitzpatrick and R Balachandran * Creation: February 2009 * * -------------------------------------------- * * converted to C++ by Alfred Franz in March/April 2010 */ void E_maker(vtkPoints *X, vtkPoints *Y, const WeightMatrixList &W, vnl_vector &returnValue); /** * This method computes the change in a root mean squared * sense between the previous and the actual iteration. * The computed value is used as a termination constraint of the algorithm and * compared against the threshold. * * @param X The moving point set in the previous iteration step. * @param X_new The moving point set in the actual step. * * @return The computed change between the two point sets. */ double CalculateConfigChange(vtkPoints *X, vtkPoints *X_new); /** * @brief This method performs a variant of the weighted point register algorithm presented by * A. Danilchenko, R. Balachandran and J. M. Fitzpatrick in January 2010. (Modified in January 2011) * converted to C++ by Alfred Franz in March/April 2010 * * @param X (input) the moving point set * @param Y (input) the fixed (static) point set * @param Sigma_X (input) a 3-by-3-by-N array, each page containing the weighting matrix for the Nth pair * of points in X * @param Sigma_Y (input) a 3-by-3-by-N array, each page containing the weighting matrix for the Nth pair * of points in Y * @param Threshold (input) the relative size of the change to the moving set above which the iteration * continues * @param MaxIterations (input) the maximum number of iterations allowed - * @param Threshold (input) the threshold used to terminate the algorithm * @param TransformationR (output) this variable will hold the computed rotation matrix * @param TransformationT (output) this variable will hold the computed translation vector * @param FRE (output) this variable will hold the computed rotation FRE of the transformation * @param n (output) this variable will hold the number of iterations used by the algorithm */ void WeightedPointRegister(vtkPoints *X, vtkPoints *Y, const CovarianceMatrixList &Sigma_X, const CovarianceMatrixList &Sigma_Y, double Threshold, int MaxIterations, Rotation &TransformationR, Translation &TransformationT, double &FRE, int &n); }; } #endif diff --git a/Modules/Annotation/include/mitkVtkAnnotation.h b/Modules/Annotation/include/mitkVtkAnnotation.h index 01c0765c3d..51545541b2 100644 --- a/Modules/Annotation/include/mitkVtkAnnotation.h +++ b/Modules/Annotation/include/mitkVtkAnnotation.h @@ -1,71 +1,71 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef VTKAnnotation_H #define VTKAnnotation_H #include "mitkAnnotation.h" #include #include class vtkProp; namespace mitk { /** * @brief The VtkAnnotation class is the base for all Annotation which are using the VTK framework to render *the elements. */ class MITKANNOTATION_EXPORT VtkAnnotation : public Annotation { public: mitkClassMacro(VtkAnnotation, Annotation); void Update(BaseRenderer *renderer) override; void AddToBaseRenderer(BaseRenderer *renderer) override; void AddToRenderer(BaseRenderer *renderer, vtkRenderer *vtkrenderer) override; void RemoveFromRenderer(BaseRenderer *renderer, vtkRenderer *vtkrenderer) override; void RemoveFromBaseRenderer(BaseRenderer *renderer) override; /** * \brief Paints the Annotation. * * This method forces a paint of the Annotation as it is configured at the moment. - * \warn Should only be used as alternative to the AnnotationManager mechanism + * \warning Should only be used as alternative to the AnnotationManager mechanism * in GL-Mappers. */ void Paint(BaseRenderer *renderer); protected: /** * @brief This method is implemented by the specific VTKAnnotation in order to create the element as a vtkProp * @param renderer * @return The element that was created by the subclasses as a vtkProp. */ virtual vtkProp *GetVtkProp(BaseRenderer *renderer) const = 0; virtual void UpdateVtkAnnotation(BaseRenderer *renderer) = 0; /** \brief explicit constructor which disallows implicit conversions */ explicit VtkAnnotation(); /** \brief virtual destructor in order to derive from this class */ ~VtkAnnotation() override; private: /** \brief copy constructor */ VtkAnnotation(const VtkAnnotation &); /** \brief assignment operator */ VtkAnnotation &operator=(const VtkAnnotation &); }; } // namespace mitk #endif // Annotation_H diff --git a/Modules/AppUtil/include/mitkBaseApplication.h b/Modules/AppUtil/include/mitkBaseApplication.h index 9b263db6d9..0321956252 100644 --- a/Modules/AppUtil/include/mitkBaseApplication.h +++ b/Modules/AppUtil/include/mitkBaseApplication.h @@ -1,317 +1,317 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkBaseApplication_h #define mitkBaseApplication_h #include #include #include #include class ctkPluginContext; class ctkPluginFramework; class QCoreApplication; class QTranslator; namespace mitk { /** * A utility class for starting BlueBerry applications. * * In the simplest case, create an instance of this class and call run(). * This will launch a CTK plugin framework instance and execute the * default application registered by a plug-in via the * org.blueberry.osgi.applications extension point. * * This class contains many convenience methods to: * - Put the application in \emph{safe mode} which catches unhandled * exceptions thrown in the Qt event loop and displays an error * message. * - Put the application in \emph{single mode} which by default * sends the command line arguments to an already running instance * of the same application instead of creating a second instance. * - Add a list of library names which should be pre-loaded at * application start-up, e.g. to speed up the initial launch during * the caching process of the plug-in meta-data. * - Set a custom provisioning file to start a specific set of CTK * plug-ins during application start-up. * - Set and get CTK plugin framework properties * * The behavior can further be customized by deriving from BaseApplication * and overriding specific methods, such as: * - initializeLibraryPaths() to add specific library / plugin search paths * - defineOptions(Poco::Util::OptionSet&) to define a custom set of * command line options * - getQApplication() to provide a custom QCoreApplication instance * * A simple but complete example: * * #include * * int main(int argc, char* argv[]) * { * mitk::BaseApplication app(argc, argv); * app.setApplicationName("MyApp"); * app.setOrganizationName("MyOrganization"); * * // Run the workbench * return app.run(); * } * */ class MITKAPPUTIL_EXPORT BaseApplication : public Poco::Util::Application { public: // Command line arguments static const QString ARG_APPLICATION; static const QString ARG_CLEAN; static const QString ARG_CONSOLELOG; static const QString ARG_DEBUG; static const QString ARG_FORCE_PLUGIN_INSTALL; static const QString ARG_HOME; static const QString ARG_NEWINSTANCE; static const QString ARG_NO_LAZY_REGISTRY_CACHE_LOADING; static const QString ARG_NO_REGISTRY_CACHE; static const QString ARG_PLUGIN_CACHE; static const QString ARG_PLUGIN_DIRS; static const QString ARG_PRELOAD_LIBRARY; static const QString ARG_PRODUCT; static const QString ARG_PROVISIONING; static const QString ARG_REGISTRY_MULTI_LANGUAGE; static const QString ARG_SPLASH_IMAGE; static const QString ARG_STORAGE_DIR; static const QString ARG_XARGS; // BlueBerry specific plugin framework properties static const QString PROP_APPLICATION; static const QString PROP_FORCE_PLUGIN_INSTALL; static const QString PROP_NEWINSTANCE; static const QString PROP_NO_LAZY_REGISTRY_CACHE_LOADING; static const QString PROP_NO_REGISTRY_CACHE; static const QString PROP_PRODUCT; static const QString PROP_REGISTRY_MULTI_LANGUAGE; BaseApplication(int argc, char **argv); ~BaseApplication() override; /** * Initialize the Qt library such that a QCoreApplication * instance is available and e.g. Qt widgets can be created. * * This is usually not called directly by the user. */ void initializeQt(); /** * Launches the BlueBerry framework and runs the default application * or the one specified in the PROP_APPLICATION framework property. * * @return The return code of the application after it was shut down. */ int run() override; void printHelp(const std::string &name, const std::string &value); /** * Set the application name. Same as QCoreApplication::setApplicationName. * @param name The application name. */ void setApplicationName(const QString &name); QString getApplicationName() const; /** * Set the organization name. Same as QCoreApplication::setOrganizationName. * @param name The organization name. */ void setOrganizationName(const QString &name); QString getOrganizationName() const; /** * Set the organization domain. Same as QCoreApplication::setOrganizationDomain. * @param name The organization domain. */ void setOrganizationDomain(const QString &name); QString getOrganizationDomain() const; /** * Put the application in single mode, which by default only allows * a single instance of the application to be created. * * Calling this method after run() has been called has no effect. * * @param singleMode */ void setSingleMode(bool singleMode); bool getSingleMode() const; /** * Put the application in safe mode, catching exceptions from the * Qt event loop. * * @param safeMode */ void setSafeMode(bool safeMode); bool getSafeMode() const; /** * Set a list of library names or absoulte file paths * which should be loaded at application start-up. The name * and file path may contain a library version appended at the * end and separated by a '$' charactger. * * For example liborg_mitk_gui_qt_common$1.0. * Platform specific suffixes are appended automatically. * * @param libraryBaseNames A list of library base names. */ void setPreloadLibraries(const QStringList &libraryBaseNames); /** * Get the list of library base names which should be pre-loaded. * * @return A list of pre-loaded libraries. */ QStringList getPreloadLibraries() const; /** * Set the path to the provisioning file. * * By default a provisioning file located in the same directory - * as the executable and named .provisioning + * as the executable and named \.provisioning * is loaded if it exists. To disable parsing of provisioning * files, use an empty string as the argument. Use a - * null QString (QString::null) to reset to the + * null QString (\c QString::null ) to reset to the * default behaviour. * * @param filePath An absolute file path to the provisioning file. */ void setProvisioningFilePath(const QString &filePath); /** * Get the file path to the provisioning file. * @return The provisioning file path. */ QString getProvisioningFilePath() const; void setProperty(const QString &property, const QVariant &value); QVariant getProperty(const QString &property) const; void installTranslator(QTranslator*); bool isRunning(); void sendMessage(const QByteArray); protected: void initialize(Poco::Util::Application &self) override; void uninitialize() override; int getArgc() const; char **getArgv() const; /** * Get the framework storage directory for the CTK plugin * framework. This method is called in the initialize(Poco::Util::Application&) * method. It must not be called without a QCoreApplications instance. * * @return The CTK Plugin Framework storage directory. */ virtual QString getCTKFrameworkStorageDir() const; /** * Initialize the CppMicroServices library. * * The default implementation set the CppMicroServices storage * path to the current ctkPluginConstants::FRAMEWORK_STORAGE property * value. * * This method is called in the initialize(Poco::Util::Application&) * after the CTK Plugin Framework storage directory property * was set. */ virtual void initializeCppMicroServices(); /** * Get the QCoreApplication object. * * This method is called in the initialize(Poco::Util::Application&) * method and must create a QCoreApplication instance if the * global qApp variable is not initialized yet. * * @return The current QCoreApplication instance. This method * never returns null. */ virtual QCoreApplication *getQApplication() const; /** * Add plugin library search paths to the CTK Plugin Framework. * * This method is called in the nitialize(Poco::Util::Application&) * method after getQApplication() was called. */ virtual void initializeLibraryPaths(); /** * Runs the application for which the platform was started. The platform * must be running. *

* The given argument is passed to the application being run. If it is an invalid QVariant * then the command line arguments used in starting the platform, and not consumed * by the platform code, are passed to the application as a QStringList. *

* @param argument the argument passed to the application. May be invalid * @return the result of running the application * @throws std::exception if anything goes wrong */ int main(const std::vector &args) override; /** * Define command line arguments * @param options */ void defineOptions(Poco::Util::OptionSet &options) override; QSharedPointer getFramework() const; ctkPluginContext *getFrameworkContext() const; /** * Get the initial properties for the CTK plugin framework. * * The returned map contains the initial framework properties for * initializing the CTK plugin framework. The value of specific * properties may change at runtime and differ from the initial * value. * * @return The initial CTK Plugin Framework properties. */ QHash getFrameworkProperties() const; /* * Initialize and display the splash screen if an image filename is given * */ void initializeSplashScreen(QCoreApplication * application) const; private: struct Impl; Impl* d; }; } #endif // MITKBASEAPPLICATION_H diff --git a/Modules/Classification/CLCore/include/mitkAbstractClassifier.h b/Modules/Classification/CLCore/include/mitkAbstractClassifier.h index d35f62d2b9..5e58b2bf8c 100644 --- a/Modules/Classification/CLCore/include/mitkAbstractClassifier.h +++ b/Modules/Classification/CLCore/include/mitkAbstractClassifier.h @@ -1,195 +1,195 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkAbstractClassifier_h #define mitkAbstractClassifier_h #include #include // Eigen #include // STD Includes // MITK includes #include namespace mitk { class MITKCLCORE_EXPORT AbstractClassifier : public BaseData { public: mitkClassMacro(AbstractClassifier,BaseData); /// /// @brief Build a forest of trees from the training set (X, y). - /// @param X, The training input samples. Matrix of shape = [n_samples, n_features] - /// @param Y, The target values (class labels in classification, real numbers in regression). Matrix of shape = [n_samples, 1] + /// @param X The training input samples. Matrix of shape = [n_samples, n_features] + /// @param Y The target values (class labels in classification, real numbers in regression). Matrix of shape = [n_samples, 1] /// virtual void Train(const Eigen::MatrixXd &X, const Eigen::MatrixXi &Y) = 0; /// /// @brief Predict class for X. - /// @param X, The input samples. + /// @param X The input samples. /// @return The predicted classes. Y matrix of shape = [n_samples, 1] /// virtual Eigen::MatrixXi Predict(const Eigen::MatrixXd &X) = 0; /// /// @brief GetPointWiseWeightCopy /// @return return label matrix of shape = [n_samples , 1] /// Eigen::MatrixXi & GetLabels() { return m_OutLabel; } protected: Eigen::MatrixXi m_OutLabel; public: // * --------------- * // PointWiseWeight // * --------------- * /// /// @brief SupportsPointWiseWeight /// @return True if the classifier supports pointwise weighting else false /// virtual bool SupportsPointWiseWeight() = 0; /// /// @brief GetPointWiseWeightCopy /// @return Create and return a copy of W /// virtual Eigen::MatrixXd & GetPointWiseWeight() { return m_PointWiseWeight; } /// /// @brief SetPointWiseWeight - /// @param W, The pointwise weights. W matrix of shape = [n_samples, 1] + /// @param W The pointwise weights. W matrix of shape = [n_samples, 1] /// virtual void SetPointWiseWeight(const Eigen::MatrixXd& W) { this->m_PointWiseWeight = W; } /// /// @brief UsePointWiseWeight - /// @param toggle weighting on/off + /// @param value weighting on/off /// virtual void UsePointWiseWeight(bool value) { this->m_IsUsingPointWiseWeight = value; } /// /// @brief IsUsingPointWiseWeight /// @return true if pointewise weighting is enabled. /// virtual bool IsUsingPointWiseWeight() { return this->m_IsUsingPointWiseWeight; } protected: Eigen::MatrixXd m_PointWiseWeight; bool m_IsUsingPointWiseWeight; // * --------------- * // PointWiseProbabilities // * --------------- * public: /// /// @brief SupportsPointWiseProbability /// @return True if the classifier supports pointwise class probability calculation else false /// virtual bool SupportsPointWiseProbability() = 0; /// /// @brief GetPointWiseWeightCopy /// @return return probability matrix /// virtual Eigen::MatrixXd & GetPointWiseProbabilities() { return m_OutProbability; } /// /// \brief UsePointWiseProbabilities /// \param value /// virtual void UsePointWiseProbability(bool value) { m_IsUsingPointWiseProbability = value; } /// /// \brief IsUsingPointWiseProbabilities /// \return /// virtual bool IsUsingPointWiseProbability() { return m_IsUsingPointWiseProbability; } protected: Eigen::MatrixXd m_OutProbability; bool m_IsUsingPointWiseProbability; private: void MethodForBuild(); public: void SetNthItems(const char *val, unsigned int idx); std::string GetNthItems(unsigned int idx) const; void SetItemList(std::vector); std::vector GetItemList() const; #ifndef DOXYGEN_SKIP void SetRequestedRegionToLargestPossibleRegion() override{} bool RequestedRegionIsOutsideOfTheBufferedRegion() override{return true;} bool VerifyRequestedRegion() override{return false;} void SetRequestedRegion(const itk::DataObject* /*data*/) override{} // Override bool IsEmpty() const override { if(IsInitialized() == false) return true; const TimeGeometry* timeGeometry = const_cast(this)->GetUpdatedTimeGeometry(); if(timeGeometry == nullptr) return true; return false; } #endif // Skip Doxygen }; } #endif //mitkAbstractClassifier_h diff --git a/Modules/Classification/CLCore/include/mitkAbstractGlobalImageFeature.h b/Modules/Classification/CLCore/include/mitkAbstractGlobalImageFeature.h index b55c3b17d8..af235b7825 100644 --- a/Modules/Classification/CLCore/include/mitkAbstractGlobalImageFeature.h +++ b/Modules/Classification/CLCore/include/mitkAbstractGlobalImageFeature.h @@ -1,338 +1,342 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkAbstractGlobalImageFeature_h #define mitkAbstractGlobalImageFeature_h #include #include #include #include #include // STD Includes // Eigen #include // MITK includes #include namespace mitk { /**Used as ID for features calculated by feature classes*/ struct MITKCLCORE_EXPORT FeatureID { /**Name of the feature*/ std::string name; /**Name of the feature class*/ std::string featureClass; /**ID for the setting that is represented by parameters and is specified by the feature class while calculating the features. It must be as unique as the parameters themself.*/ std::string settingID; /**Alternative name that containes the legacy naming of the feature that encodes the parametersetting directly in the string.*/ std::string legacyName; /**Version of the feature definition*/ std::string version = "1"; using ParametersType = std::map; ParametersType parameters; bool operator < (const FeatureID& rh) const; bool operator ==(const FeatureID& rh) const; }; /**Helper that takes a pass templateID clones it and populates it with the also passed informations befor returning it. * @param templateID reference ID that should be cloned. * @param name Name of the feature.*/ MITKCLCORE_EXPORT FeatureID CreateFeatureID(FeatureID templateID, std::string name); /** * * * ## Histogram Configuration ## * Most Feature Generation Classes that use histograms use the same parameters and * initialization logic. In general, all information can be passed either by the corresponding * Setter (which does not differenciate between global setting and feature specific setting) and * a parameter object which can be obtained from the command line arguments, for example. * * If the image values are used for the initializiation of the histogram, it can be defined * whether the whole image is used or only the masked areas to find minima and maxima. This is * done by the option SetIgnoreMask or the corrsponding options * -NAME::ignore-mask-for-histogram and -ignore-mask-for-histogram. If these are * true, the whole image is used for the calculation. * * Depending on the passed arguments, different initialization methods are used. The initialization * is in the following order: * - If Minimum Intensity, Maximum Intensity, and Binsize: The histogram is * initialized between the minimum and maximum intensity. the number of bins is determined by the * binsize. If the distance between minimum and maximum is not a multiple of the binsize, the maximum * is increase so that it is. * - Minimum Intensity, Bins, and Binsize: The histogram is initialized with the * given binsize, and the intensity range from the minimum to \f$maximum = minimum + binsize*bins\f$. * - Minimum Intensity, Maximum Intensity, and Bins: The histogram is initialized * between the given minimum and maximum intensity. The binsize is calculated so that the number * of bins is equal to the given number of bins. * - Binsize, and Minimum Intensity: The maximum is set to the maximum that * occur in the given image. Depending if the mask is considered or not, either only masked voxels or * the whole image is used for the calculation. The initialization is then equal as if the minimum * and maximum would have been given right from the beginning. * - Binsize, and Maximum Intensity: The minimum intensity is set to the minimum that * occur in the given image. Depending if the mask is considered or not, either only masked voxels or * the whole image is used for the calculation. The initialization is then equal as if the minimum * and maximum would have been given right from the beginning. * - Binsize: The maximum and the minimum intensity is set to the minimum and maximum that * occur in the given image. Depending if the mask is considered or not, either only masked voxels or * the whole image is used for the calculation. The initialization is then equal as if the minimum * and maximum would have been given right from the beginning. * - Bins, and Minimum Intensity: The maximum is calculated from the image. Depending * if the mask is considered or not, either only masked voxels or the whole image is used for the calculation. The histogram is * then initialized as if these values would have been given as minimum and maximum intensity. * - Bins, and Maximum Intensity: The minimum is calculated from the image. Depending * if the mask is considered or not, either only masked voxels or the whole image is used for the calculation. The histogram is * then initialized as if these values would have been given as minimum and maximum intensity. * - Bins: The minimum and the maximum is calculated from the image. Depending * if the mask is considered or not, either only masked voxels or * the whole image is used for the calculation. The histogram is * then initialized as if these values would have been given as minimum and maximum intensity. * - No Parameter given:The minimum and maximum intensity from the whole image or masked image is calculated and * the histogram then initialized to this with a standard number of bins (Is set by each filter on its own.) * * ### Remark about command line parameter#### * There are generally two options to set a parameter via the command line. A global one that works for * all filters that use histograms and a local one that set this parameter specific for this filter. The * local parameters start with the filter name (Indiciated by NAME) followed by two colons, for example * vol::min to set the minimum intensity for the volume filter. The global parameter is overwritten * by the local parameter, if it is specified. Otherwise, it is still valid. If this prevents the specification * of an histogram initialization method (for example, because the binsize is globally specified but the histogram * should be initialized using a fixed numbe of bins), the parameter NAME::ignore-global-histogram can be passed. * Then, all global histogram parameters are ignored and only local ones are used. * * The maximum intensity can be set by different command line parameters: global for all filters that use histograms * by -minimum-intensity and -minimum. Alternative it can be set only for this filter by * -NAME::minimum and -NAME::min. * * The minimum intensity can be set by different command line parameters: global for all filters that use histograms * by -maximum-intensity and -maximum. Alternative it can be set only for this filter by - * \NAME::maximum and NAME::max. + * -NAME::maximum and -NAME::max. * * The binsize can be set by different command line parameters: global for all filters that use histograms * by -binsize. Alternative it can be set only for this filter by - * \NAME::binsize. + * -NAME::binsize. * * The number of bins can be set by different command line parameters: global for all filters that use histograms * by -bins. Alternative it can be set only for this filter by - * \NAME::bins. + * -NAME::bins. * ### Note to the developers ### * All features are supposed to work the same way if a histogram is used somewhere in * the code. For this, each derived class that makes use of a histogram should use * the Quantifier object. In order to use this object correctly, the AddArguments-Function should * contain the line AddQuantifierArguments(parser);, the CalculateFeaturesUsingParameters function * should contain the line InitializeQuantifierFromParameters(feature, mask); and the CalculateFeatures function * sould contain the line InitializeQuantifier(image, mask);. These function * calls ensure that the necessary options are given to the configuration file, and that the initialization * of the quantifier is done correctly. This ensures an consistend behavior over all FeatureGeneration Classes. * */ class MITKCLCORE_EXPORT AbstractGlobalImageFeature : public BaseData { public: mitkClassMacro(AbstractGlobalImageFeature, BaseData); typedef std::vector< std::pair > FeatureListType; using ParametersType = FeatureID::ParametersType; /** * \brief Calculates the feature of this abstact interface. Does not necessarily considers the parameter settings. */ FeatureListType CalculateFeatures(const Image* image, const Image* mask); virtual FeatureListType CalculateFeatures(const Image* image, const Image* mask, const Image* maskNoNAN) = 0; /** * \brief Calculates the given feature Slice-wise. Might not be availble for an individual filter! */ FeatureListType CalculateFeaturesSlicewise(const Image::Pointer & image, const Image::Pointer &mask, int sliceID); /** * \brief Calculates the feature of this abstact interface. Does not necessarily considers the parameter settings. */ virtual void CalculateAndAppendFeaturesSliceWise(const Image::Pointer & image, const Image::Pointer &mask, int sliceID, FeatureListType &featureList, bool checkParameterActivation = true); /** * \brief Calculates the feature of this abstact interface. Does not necessarily considers the parameter settings. + * @param image + * @param mask + * @param maskNoNaN + * @param featureList * @param checkParameterActivation Indicates if the features should only be calculated and added if the FeatureClass is activated in the parameters. * True: only append if activated in the parametes. False: always and append it. */ void CalculateAndAppendFeatures(const Image* image, const Image* mask, const Image* maskNoNAN, FeatureListType &featureList, bool checkParameterActivation = true); itkSetMacro(Prefix, std::string); itkSetMacro(ShortName, std::string); itkSetMacro(LongName, std::string); itkSetMacro(FeatureClassName, std::string); itkSetMacro(Direction, int); void SetParameters(ParametersType param) { m_Parameters = param; this->ConfigureQuantifierSettingsByParameters(); this->ConfigureSettingsByParameters(param); this->Modified(); }; itkGetConstMacro(Prefix, std::string); itkGetConstMacro(ShortName, std::string); itkGetConstMacro(LongName, std::string); itkGetConstMacro(FeatureClassName, std::string); itkGetConstMacro(Parameters, ParametersType); itkGetMacro(Quantifier, IntensityQuantifier::Pointer); itkGetConstMacro(Direction, int); itkSetMacro(MinimumIntensity, double); itkSetMacro(UseMinimumIntensity, bool); itkSetMacro(MaximumIntensity, double); itkSetMacro(UseMaximumIntensity, bool); itkGetConstMacro(MinimumIntensity, double); itkGetConstMacro(UseMinimumIntensity, bool); itkGetConstMacro(MaximumIntensity, double); itkGetConstMacro(UseMaximumIntensity, bool); itkSetMacro(Binsize, double); itkSetMacro(UseBinsize, bool); itkGetConstMacro(Binsize, double); itkGetConstMacro(UseBinsize, bool); itkSetMacro(MorphMask, mitk::Image::Pointer); itkGetConstMacro(MorphMask, mitk::Image::Pointer); itkSetMacro(Bins, int); itkSetMacro(UseBins, bool); itkGetConstMacro(UseBins, bool); itkGetConstMacro(Bins, int); itkSetMacro(IgnoreMask, bool); itkGetConstMacro(IgnoreMask, bool); itkSetMacro(EncodeParametersInFeaturePrefix, bool); itkGetConstMacro(EncodeParametersInFeaturePrefix, bool); itkBooleanMacro(EncodeParametersInFeaturePrefix); std::string GetOptionPrefix() const { if (!m_Prefix.empty()) return m_Prefix + "::" + m_ShortName; return m_ShortName; } /** Can be called to add all relevant argument for configuring the feature instance to the passed parser instance. Must be implemented be derived classes. For adding the quantifier arguments use AddQuantifierArguments(...) as helper function.*/ virtual void AddArguments(mitkCommandLineParser &parser) const = 0; /** Helper function that generates the legacy feature name without encoding of parameters; as it is used e.g. in the unit tests.*/ static std::string GenerateLegacyFeatureNameWOEncoding(const FeatureID& id); protected: std::vector SplitDouble(std::string str, char delimiter); virtual FeatureListType DoCalculateFeatures(const Image* image, const Image* mask) = 0; void AddQuantifierArguments(mitkCommandLineParser& parser) const; /** Ensures that all quantifier relevant variables of the instance are set correctly given the information in m_Parameters.*/ void ConfigureQuantifierSettingsByParameters(); /** Ensures that the instance is configured according to the information given in the passed parameters. * This method will be called by SetParameters(...) after ConfigureQuantifierSettingsByParameters() was called.*/ virtual void ConfigureSettingsByParameters(const ParametersType& parameters); /**Initializes the quantifier gigen the quantifier relevant variables and the passed arguments.*/ void InitializeQuantifier(const Image* image, const Image* mask, unsigned int defaultBins = 256); /** Helper that encodes the quantifier parameters in a string (e.g. used for the legacy feature name)*/ std::string QuantifierParameterString() const; /* Creates a template feature id. * it will set the featureClass, the settingID (assuming that it is the featureClass with the passed suffix * and all parameters that are global or have the option prefix of the instance.*/ FeatureID CreateTemplateFeatureID(std::string settingsSuffix = "", FeatureID::ParametersType additionalParams = {}); /** Helper that generates the legacy feature names for a passed FeatureID. - * Format of the legacy feature name is: ::[::] + * Format of the legacy feature name is: \::[\::]\ * Overwrite GenerateLegacyFeatureNamePart and GenerateLegacyFeatureEncoding to change behavior in * derived classes. */ virtual std::string GenerateLegacyFeatureName(const FeatureID& id) const; virtual std::string GenerateLegacyFeatureNamePart(const FeatureID& id) const; virtual std::string GenerateLegacyFeatureEncoding(const FeatureID& id) const; public: //#ifndef DOXYGEN_SKIP void SetRequestedRegionToLargestPossibleRegion() override {}; bool RequestedRegionIsOutsideOfTheBufferedRegion() override { return true; }; bool VerifyRequestedRegion() override { return false; }; void SetRequestedRegion (const itk::DataObject * /*data*/) override {}; // Override bool IsEmpty() const override { if(IsInitialized() == false) return true; const TimeGeometry* timeGeometry = const_cast(this)->GetUpdatedTimeGeometry(); if(timeGeometry == nullptr) return true; return false; } private: std::string m_Prefix; // Prefix before all input parameters std::string m_ShortName; // Name of all variables std::string m_LongName; // Long version of the name (For turning on) std::string m_FeatureClassName; ParametersType m_Parameters; // Parameter setting mitk::Image::Pointer m_MorphMask = nullptr; IntensityQuantifier::Pointer m_Quantifier; //Quantifier relevant variables double m_MinimumIntensity = 0; bool m_UseMinimumIntensity = false; double m_MaximumIntensity = 100; bool m_UseMaximumIntensity = false; bool m_EncodeParametersInFeaturePrefix = false; double m_Binsize = 1; bool m_UseBinsize = false; int m_Bins = 256; bool m_UseBins = true; int m_Direction = 0; bool m_IgnoreMask = false; //#endif // Skip Doxygen }; } #endif //mitkAbstractGlobalImageFeature_h diff --git a/Modules/Classification/CLUtilities/include/mitkCLUtil.h b/Modules/Classification/CLUtilities/include/mitkCLUtil.h index 7db22c89d1..46cd3714e4 100644 --- a/Modules/Classification/CLUtilities/include/mitkCLUtil.h +++ b/Modules/Classification/CLUtilities/include/mitkCLUtil.h @@ -1,583 +1,583 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkCLUtil_h #define mitkCLUtil_h #include #include #include #include #include #include #include namespace mitk { class MITKCLUTILITIES_EXPORT CLUtil { public: /// /// \brief The MorphologicalDimensions enum /// enum MorphologicalDimensions { Axial,Coronal,Sagital,All }; /// /// \brief CreateCheckerBoardPredictionMask /// \param image /// \param outimage /// static void CreateCheckerboardMask(mitk::Image::Pointer image, mitk::Image::Pointer & outimage); /// /// \brief InterpolateCreateCheckerboardPrediction /// \param image /// \param outimage /// static void InterpolateCheckerboardPrediction(mitk::Image::Pointer checkerboard_prediction, mitk::Image::Pointer & checkerboard_mask, mitk::Image::Pointer & outimage); /// /// \brief CountVoxel /// \param image /// \param map /// static void CountVoxel(mitk::Image::Pointer image, std::map & map); /// /// \brief CountVoxel /// \param image /// \param label /// \param count /// static void CountVoxel(mitk::Image::Pointer image, unsigned int label, unsigned int & count); /// /// \brief CountVoxel /// \param image /// \param count /// static void CountVoxel(mitk::Image::Pointer image, unsigned int & count); /// /// \brief SumVoxelForLabel /// \param image /// \param source /// \param label /// \param val /// static void SumVoxelForLabel(mitk::Image::Pointer image, const mitk::Image::Pointer & source , unsigned int label, double & val ); /// /// \brief SqSumVoxelForLabel /// \param image /// \param source /// \param label /// \param val /// static void SqSumVoxelForLabel(mitk::Image::Pointer image, const mitk::Image::Pointer & source, unsigned int label, double & val ); /// /// \brief LogicalAndImages /// \param image1 /// \param image2 /// static void LogicalAndImages(const Image::Pointer &image1, const Image::Pointer &image2, Image::Pointer &outimage); /// /// \brief GaussianFilter /// \param image /// \param smoothed /// \param sigma /// static void GaussianFilter(mitk::Image::Pointer image, mitk::Image::Pointer & smoothed ,double sigma); /// /// \brief SubtractGaussianFilter /// \param image /// \param smoothed (Result is sigma1-sigma2) /// \param sigma1 /// \param sigma2 /// static void DifferenceOfGaussianFilter(mitk::Image::Pointer image, mitk::Image::Pointer & smoothed, double sigma1, double sigma2); /// /// \brief Laplacian of Gaussian /// \param image /// \param smoothed (Result is sigma1-sigma2) /// \param sigma1 /// \param sigma2 /// static void LaplacianOfGaussianFilter(mitk::Image::Pointer image, mitk::Image::Pointer & smoothed, double sigma1); /// /// \brief SubtractGaussianFilter /// \param image /// \param smoothed (Result is sigma1-sigma2) /// \param sigma1 /// \param sigma2 /// static void HessianOfGaussianFilter(mitk::Image::Pointer image, std::vector &out, double sigma); /// /// \brief Local Histogram /// \param image /// \param smoothed (Result is sigma1-sigma2) /// \param sigma1 /// \param sigma2 /// static void LocalHistogram(mitk::Image::Pointer image, std::vector &out, int Bins, int NeighbourhoodSize); /// /// \brief transform /// \param matrix /// \param mask /// \param outimage /// template static mitk::Image::Pointer Transform(const Eigen::Matrix & matrix, const mitk::Image::Pointer & mask) { itk::Image::Pointer itkMask; mitk::CastToItkImage(mask,itkMask); typename itk::Image::Pointer itk_img = itk::Image::New(); itk_img->SetRegions(itkMask->GetLargestPossibleRegion()); itk_img->SetOrigin(itkMask->GetOrigin()); itk_img->SetSpacing(itkMask->GetSpacing()); itk_img->SetDirection(itkMask->GetDirection()); itk_img->Allocate(); unsigned int n_numSamples = 0; mitk::CLUtil::CountVoxel(mask,n_numSamples); if(n_numSamples != matrix.rows()) MITK_ERROR << "Number of samples in matrix and number of points under the masks is not the same!"; auto mit = itk::ImageRegionConstIterator >(itkMask, itkMask->GetLargestPossibleRegion()); auto oit = itk::ImageRegionIterator >(itk_img, itk_img->GetLargestPossibleRegion()); unsigned int current_row = 0; while(!mit.IsAtEnd()) { if(mit.Value() > 0) oit.Set(matrix(current_row++,0)); else oit.Set(0.0); ++mit; ++oit; } mitk::Image::Pointer out_img = mitk::Image::New(); mitk::GrabItkImageMemory(itk_img,out_img); return out_img; } /// /// \brief TransformImageToMatrix /// \param in_img /// \param mask /// \param out_matrix /// template static Eigen::Matrix Transform(const mitk::Image::Pointer & img, const mitk::Image::Pointer & mask) { itk::Image::Pointer current_mask; mitk::CastToItkImage(mask,current_mask); unsigned int n_numSamples = 0; mitk::CLUtil::CountVoxel(mask,n_numSamples); typename itk::Image::Pointer current_img; mitk::CastToItkImage(img,current_img); Eigen::Matrix out_matrix(n_numSamples,1); auto mit = itk::ImageRegionConstIterator >(current_mask, current_mask->GetLargestPossibleRegion()); auto iit = itk::ImageRegionConstIterator >(current_img,current_img->GetLargestPossibleRegion()); unsigned int current_row = 0; while (!mit.IsAtEnd()) { if(mit.Value() > 0) out_matrix(current_row++) = iit.Value(); ++mit; ++iit; } return out_matrix; } /// /// \brief DilateBinary /// \param BinaryImage /// \param BinaryImage /// \param Size of the StructuringElement /// \param Dimension /// static void DilateBinary(mitk::Image::Pointer & sourceImage, mitk::Image::Pointer& resultImage, int radius , MorphologicalDimensions d); /// /// \brief ErodeBinary /// \param BinaryImage /// \param BinaryImage /// \param Size of the StructuringElement /// \param Dimension /// static void ErodeBinary(mitk::Image::Pointer & sourceImage, mitk::Image::Pointer& resultImage, int radius, MorphologicalDimensions d); /// /// \brief ClosingBinary /// \param BinaryImage /// \param BinaryImage /// \param Size of the StructuringElement /// \param Dimension /// static void ClosingBinary(mitk::Image::Pointer & sourceImage, mitk::Image::Pointer& resultImage, int radius, MorphologicalDimensions d); /// /// \brief MergeLabels /// \param MultilabelImage - /// \param map merge instruction where each map entry defines a mapping instruction. Key - Value + /// \param map merge instruction where each map entry defines a mapping instruction. Key \c \ - Value \c \ /// static void MergeLabels(mitk::Image::Pointer & img, const std::map & map); /// /// \brief ConnectedComponentsImage /// \param BinaryImage /// \param BinaryImage /// \param MultilabelImage /// \param Number of components found in the image /// static void ConnectedComponentsImage(mitk::Image::Pointer & image, mitk::Image::Pointer& mask, mitk::Image::Pointer &outimage, unsigned int& num_components); /// /// \brief GrabLabel /// \param MultiLabelImage /// \param outimage /// \param label /// static void GrabLabel(mitk::Image::Pointer & image, mitk::Image::Pointer & outimage, unsigned int label); /// /// \brief itkInsertLabel /// \param image /// \param maskImage /// \param label /// static void InsertLabel(mitk::Image::Pointer & image, mitk::Image::Pointer & maskImage, unsigned int label); /// /// \brief ErodeGrayscale /// \param image /// \param outimage /// \param radius /// \param d /// static void ErodeGrayscale(mitk::Image::Pointer & image, unsigned int radius, mitk::CLUtil::MorphologicalDimensions d, mitk::Image::Pointer & outimage ); /// /// \brief DilateGrayscale /// \param image /// \param outimage /// \param radius /// \param d /// static void DilateGrayscale(mitk::Image::Pointer & image, unsigned int radius, mitk::CLUtil::MorphologicalDimensions d, mitk::Image::Pointer & outimage ); /// /// \brief FillHoleGrayscale /// \param image /// \param outimage /// static void FillHoleGrayscale(mitk::Image::Pointer & image, mitk::Image::Pointer & outimage); /// /// \brief ProbabilityMap /// \param sourceImage /// \param mean /// \param std_dev /// \param resultImage /// static void ProbabilityMap(const mitk::Image::Pointer& sourceImage, double mean, double std_dev, mitk::Image::Pointer& resultImage); template static void itkCountVoxel( TImageType * image, std::map & map) { auto it = itk::ImageRegionIterator< TImageType >(image,image->GetLargestPossibleRegion()); while(!it.IsAtEnd()) { if(map.find(it.Value()) == map.end()) map[it.Value()] = 0; map[it.Value()]++; ++it; } } template static void itkCountVoxel(TImageType* image, typename TImageType::PixelType label, unsigned int & count ) { itk::ImageRegionConstIterator inputIter(image, image->GetLargestPossibleRegion()); while(!inputIter.IsAtEnd()) { if(inputIter.Value() == label) ++count; ++inputIter; } } template static inline void itkCountVoxel(TImageType * mask, unsigned int & n_numSamples) { auto mit = itk::ImageRegionConstIterator(mask, mask->GetLargestPossibleRegion()); while (!mit.IsAtEnd()) { if(mit.Value() > 0) n_numSamples++; ++mit; } } template static void itkSampleLabel(TImageType1* image, TImageType2* output, double acceptrate, unsigned int label) { std::srand (time(nullptr)); itk::ImageRegionConstIterator< TImageType1 > inputIter(image, image->GetLargestPossibleRegion()); itk::ImageRegionIterator< TImageType2 > outputIter(output, output->GetLargestPossibleRegion()); while (!inputIter.IsAtEnd()) { double r = (double)(rand()) / RAND_MAX; if(inputIter.Get() == label && r < acceptrate) outputIter.Set(label); ++inputIter; ++outputIter; } } template static void itkSampleLabel(TImageType* image, mitk::Image::Pointer & output, unsigned int n_samples_drawn) { std::srand (time(nullptr)); typename TImageType::Pointer itk_out = TImageType::New(); itk_out->SetRegions(image->GetLargestPossibleRegion()); itk_out->SetDirection(image->GetDirection()); itk_out->SetOrigin(image->GetOrigin()); itk_out->SetSpacing(image->GetSpacing()); itk_out->Allocate(); itk_out->FillBuffer(0); itk::ImageRegionConstIterator< TImageType > inputIter(image, image->GetLargestPossibleRegion()); itk::ImageRegionIterator< TImageType > outputIter(itk_out, itk_out->GetLargestPossibleRegion()); for(unsigned int i = 0 ; i < n_samples_drawn ;) { double r = (double)(rand()) / RAND_MAX; if(inputIter.Value() != 0 && r < 0.01 && outputIter.Value() == 0) { outputIter.Set(inputIter.Value()); i++; } ++inputIter; ++outputIter; if(inputIter.IsAtEnd()) { inputIter.GoToBegin(); outputIter.GoToBegin(); } } mitk::CastToMitkImage(itk_out, output); } private: template static void itkErodeGrayscale(TImageType * image, mitk::Image::Pointer & outimage , unsigned int radius, mitk::CLUtil::MorphologicalDimensions d); template static void itkDilateGrayscale(TImageType * image, mitk::Image::Pointer & outimage , unsigned int radius, mitk::CLUtil::MorphologicalDimensions d); template static void itkFillHoleGrayscale(TImageType * image, mitk::Image::Pointer & outimage); template< typename TImageType > static void itkInsertLabel(TImageType * maskImage, mitk::Image::Pointer & outimage, unsigned int label) { typename TImageType::Pointer itk_out; if(outimage.IsNull()) // create if necessary { MITK_INFO << "Initialize new image"; itk_out = TImageType::New(); itk_out->SetSpacing(maskImage->GetSpacing()); itk_out->SetDirection(maskImage->GetDirection()); itk_out->SetOrigin(maskImage->GetOrigin()); itk_out->SetRegions(maskImage->GetLargestPossibleRegion()); itk_out->Allocate(); itk_out->FillBuffer(0); }else { mitk::CastToItkImage(outimage, itk_out); } itk::ImageRegionIterator oit(itk_out,itk_out->GetLargestPossibleRegion()); itk::ImageRegionConstIterator mit(maskImage,maskImage->GetLargestPossibleRegion()); while(!mit.IsAtEnd()) { if(mit.Value() != 0) { oit.Set(label); } ++oit; ++mit; } mitk::CastToMitkImage(itk_out,outimage); } template< typename TImageType > static void itkGrabLabel(TImageType * image, mitk::Image::Pointer & outimage, unsigned int label) { typedef itk::Image TOutType; TOutType::Pointer itk_out = TOutType::New(); itk_out->SetRegions(image->GetLargestPossibleRegion()); itk_out->SetDirection(image->GetDirection()); itk_out->SetOrigin(image->GetOrigin()); itk_out->SetSpacing(image->GetSpacing()); itk_out->Allocate(); itk::ImageRegionConstIterator iit(image, image->GetLargestPossibleRegion()); itk::ImageRegionIterator oit(itk_out,itk_out->GetLargestPossibleRegion()); while(!iit.IsAtEnd()) { if(iit.Value() == static_cast(label)) oit.Set(1); else oit.Set(0); ++iit; ++oit; } mitk::CastToMitkImage(itk_out, outimage); } template static void itkMergeLabels(TImagetype * img, const std::map & map) { auto it = itk::ImageRegionIterator(img,img->GetLargestPossibleRegion()); while(!it.IsAtEnd()) { if(map.find(it.Value())!=map.end()) it.Set( map.at(it.Value()) ); ++it; } } template static void itkConnectedComponentsImage(TImageType * image, mitk::Image::Pointer& mask, mitk::Image::Pointer &outimage, unsigned int& num_components) { typedef itk::Image MaskImageType; MaskImageType::Pointer itk_mask; if(mask.IsNull()) { itk_mask = MaskImageType::New(); itk_mask->SetRegions(image->GetLargestPossibleRegion()); itk_mask->SetDirection(image->GetDirection()); itk_mask->SetOrigin(image->GetOrigin()); itk_mask->SetSpacing(image->GetSpacing()); itk_mask->Allocate(); itk_mask->FillBuffer(1); }else{ mitk::CastToItkImage(mask,itk_mask); } typedef itk::ConnectedComponentImageFilter FilterType; typename FilterType::Pointer cc_filter = FilterType::New(); cc_filter->SetMaskImage(itk_mask.GetPointer()); cc_filter->SetInput(image); cc_filter->SetBackgroundValue(0); cc_filter->Update(); num_components = cc_filter->GetObjectCount(); mitk::CastToMitkImage(cc_filter->GetOutput(), outimage); } template< typename TImageType > static void itkCreateCheckerboardMask(TImageType * image, mitk::Image::Pointer & outimage); template< typename TImageType > static void itkInterpolateCheckerboardPrediction(TImageType * checkerboard_prediction, mitk::Image::Pointer & checkerboard_mask, mitk::Image::Pointer & outimage); template static void itkSumVoxelForLabel(TImageType* image, const mitk::Image::Pointer & source , typename TImageType::PixelType label, double & val ); template static void itkSqSumVoxelForLabel(TImageType* image, const mitk::Image::Pointer & source, typename TImageType::PixelType label, double & val ); template static void itkFitStructuringElement(TStructuringElement & se, MorphologicalDimensions d, int radius); template static void itkDilateBinary(TImageType * sourceImage, mitk::Image::Pointer& resultImage, int radius , MorphologicalDimensions d); template static void itkErodeBinary(TImageType * sourceImage, mitk::Image::Pointer& resultImage, int radius, MorphologicalDimensions d); template static void itkClosingBinary(TImageType * sourceImage, mitk::Image::Pointer& resultImage, int radius, MorphologicalDimensions d); template static void itkFillHolesBinary(itk::Image* sourceImage, mitk::Image::Pointer& resultImage); template static void itkLogicalAndImages(const TImageType * image1, const mitk::Image::Pointer & image2, mitk::Image::Pointer & outimage); template static void itkGaussianFilter(TImageType * image, mitk::Image::Pointer & smoothed ,double sigma); template static void itkDifferenceOfGaussianFilter(TImageType * image, mitk::Image::Pointer & smoothed, double sigma1, double sigma2); template static void itkProbabilityMap(const TImageType * sourceImage, double mean, double std_dev, mitk::Image::Pointer& resultImage); template static void itkHessianOfGaussianFilter(itk::Image* itkImage, double variance, std::vector &out); template static void itkLaplacianOfGaussianFilter(itk::Image* itkImage, double variance, mitk::Image::Pointer &output); template static void itkLocalHistograms(itk::Image* itkImage, std::vector &out, int size, int bins); }; } //namespace MITK #endif diff --git a/Modules/Classification/CLUtilities/include/mitkGIFCooccurenceMatrix2.h b/Modules/Classification/CLUtilities/include/mitkGIFCooccurenceMatrix2.h index cdc333aca5..bb48f36667 100644 --- a/Modules/Classification/CLUtilities/include/mitkGIFCooccurenceMatrix2.h +++ b/Modules/Classification/CLUtilities/include/mitkGIFCooccurenceMatrix2.h @@ -1,162 +1,162 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkGIFCooccurenceMatrix2_h #define mitkGIFCooccurenceMatrix2_h #include #include #include #include namespace mitk { /** * \brief Calculates features based on the co-occurence matrix. * * The co-occurence matrix describes the relations between voxels in a specific direction. The elements \f$m_{i,k} \f$ of the * matrix count how often a voxel with the intensity \f$i \f$ has a neighbour in a certain direction with the intensity \f$ k \f$. * The direction for each matrix is given by a directed vector \f$ \overrightarrow{d} \f$. * * It is important to calculate the matrices for all possible directions in order to obtain a rotation invariant feature. * For the 3D case, this means that there are 26 possible directions. Using the symmetrical properties of the co-occurence * matrix, it is then possible to calculate the features in all directions looking at 13 different directions. * * The standard length of the vector is 1, e.g. looking at direct neighbours. It is possible to look at more * distance neighbours. This is achieved using the parameter range which defines the distance between * two neighbouring voxels in number of voxels. The default value for this is 1. It can be changes using the Method * SetRange() or by passing the option cooc2::range. * * There are two possible ways of combining the information obtained from the multiple directions. The first option * is to calculate a common matrix for all directions and then use this matrix to calculate the describing features. * The second method is to calculate a matrix for each direction, obtain the features and then report the mean and * standard value of these features. Both mehtods are calcuated by this filters and reported, distinguisehd by either * an "Overall" if a single matrix is used, a "Mean" for the mean Value, or an "Std.Dev." for the standard deviation. * * The connected areas are based on the binned image, the binning parameters can be set via the default * parameters as described in AbstractGlobalImageFeature. The intensity used for the calculation is * always equal to the bin number. It is also possible to determine the * dimensionality of the neighbourhood using direction-related commands as described in AbstractGlobalImageFeature. * No other options are possible beside these two options. * * This feature calculator is activated by the option -cooccurence2 or -cooc2. * * The features are calculated based on a mask. It is assumed that the mask is * of the type of an unsigned short image. All voxels with the value 1 are treated as masked. * * The following features are defined. We always give the notation for the overall matrix feature - * although those for the mean and std.dev. are basically equal. In the name, is replace + * although those for the mean and std.dev. are basically equal. In the name, \ is replace * by the distance of the neighbours. For the definitions of the feature, the probability of each * intensity pair (i,k) \f$ p_{i,k} = \frac{m_{i,k}}{\sum_i \sum_k m_{i,k}} \f$. * * In addition, the marginal sum \f$ p_{i,\cdot} = p_{\cdot,k=i} = \sum_k p_{i,k} \f$, which is * identical for both axis due to the symetrical nature of the matrix. Furthermore, the diagonal and * cross diagnoal features are used: * \f[ p_{i-k}(l) = \sum_i \sum_k p_{i,k} \delta(l - \| i -k \| ) \enspace \enspace l = 0, \dots, N_g -1 \f] * \f[ p_{i+k}(l) = \sum_i \sum_k p_{i,k} \delta(l - ( i + k ) ) \enspace \enspace l = 2, \dots, 2 N_g \f] * Here, \f$ \delta(x) \f$ is the dirac function, which is one for \f$x=0 \f$ and zero otherwise. - * - Co-occurenced Based Features ()::Overall Joint Maximum: + * - Co-occurenced Based Features (\)::%Overall Joint Maximum: * \f[ \textup{Joint Maximum}= \textup{max}(p_{i,k}) \f] - * - Co-occurenced Based Features ()::Overall Joint Average: + * - Co-occurenced Based Features (\)::%Overall Joint Average: * \f[ \textup{Joint Average} = \mu_{ja} = \sum_i \sum_k i p_{i,k} \f] - * - Co-occurenced Based Features ()::Overall Joint Variance: + * - Co-occurenced Based Features (\)::%Overall Joint Variance: * \f[ \textup{Joint Variance} = \sum_i \sum_k (i - \mu_{ja})^2 p_{i,k} \f] - * - Co-occurenced Based Features ()::Overall Joint Entropy: + * - Co-occurenced Based Features (\)::%Overall Joint Entropy: * \f[ \textup{Joint Entropy} = e_j = - \sum_i \sum_k p_{i,k} \textup{log}_2 p_{i,k} \f] - * - Co-occurenced Based Features ()::Overall Row Maximum: + * - Co-occurenced Based Features (\)::%Overall Row Maximum: * \f[ \textup{Row Maximum}= \textup{max}(p_{i,\cdot}) \f] - * - Co-occurenced Based Features ()::Overall Row Average: + * - Co-occurenced Based Features (\)::%Overall Row Average: * \f[ \textup{Row Average} = \mu_{ra} = \sum_i i p_{i,\cdot} \f] - * - Co-occurenced Based Features ()::Overall Row Variance: + * - Co-occurenced Based Features (\)::%Overall Row Variance: * \f[ \textup{Row Variance} = \sigma^2_{i, \cdot} = \sum_i (i - \mu_{ra})^2 p_{i,\cdot} \f] - * - Co-occurenced Based Features ()::Overall Row Entropy: + * - Co-occurenced Based Features (\)::%Overall Row Entropy: * \f[ \textup{Row Entropy} = e_r = - \sum_i p_{i,\cdot} \textup{log}_2 p_{i,\cdot} \f] - * - Co-occurenced Based Features ()::Overall First Row-Column Entropy: + * - Co-occurenced Based Features (\)::%Overall First Row-Column Entropy: * \f[ \textup{First Row-Column Entropy} = e_1 = - \sum_i \sum_k p_{i,k} \textup{log}_2 ( p_{i,\cdot} p_{\cdot,k}) \f] - * - Co-occurenced Based Features ()::Overall Second Row-Column Entropy: + * - Co-occurenced Based Features (\)::%Overall Second Row-Column Entropy: * \f[ \textup{Second Row-Column Entropy} = e_2 = - \sum_i \sum_k p_{i,\cdot} p_{\cdot,k} \textup{log}_2 ( p_{i,\cdot} p_{\cdot,k}) \f] - * - Co-occurenced Based Features ()::Overall Difference Average: + * - Co-occurenced Based Features (\)::%Overall Difference Average: * \f[ \textup{Difference Average} = \mu_{da} = \sum_l l p_{i-k}(l) \f] - * - Co-occurenced Based Features ()::Overall Difference Variance: + * - Co-occurenced Based Features (\)::%Overall Difference Variance: * \f[ \textup{Difference Variance} = \sum_l (i - \mu_{da})^2 p_{i-k}(l) \f] - * - Co-occurenced Based Features ()::Overall Difference Entropy: + * - Co-occurenced Based Features (\)::%Overall Difference Entropy: * \f[ \textup{Difference Entropy} = - \sum_l p_{i-k}(l) \textup{log}_2 p_{i-k}(l) \f] - * - Co-occurenced Based Features ()::Overall Sum Average: + * - Co-occurenced Based Features (\)::%Overall Sum Average: * \f[ \textup{Sum Average} = \mu_{sa} = \sum_l l p_{i+k}(l) \f] - * - Co-occurenced Based Features ()::Overall Sum Variance: + * - Co-occurenced Based Features (\)::%Overall Sum Variance: * \f[ \textup{Sum Variance} = \sum_l (i - \mu_{sa})^2 p_{i+k}(l) \f] - * - Co-occurenced Based Features ()::Overall Sum Entropy: + * - Co-occurenced Based Features (\)::%Overall Sum Entropy: * \f[ \textup{Sum Entropy} = - \sum_l p_{i+k}(l) \textup{log}_2 p_{i+k}(l) \f] - * - Co-occurenced Based Features ()::Overall Angular Second Moment: + * - Co-occurenced Based Features (\)::%Overall Angular Second Moment: * \f[ \textup{Angular Second Moment} = \sum_i \sum_k p^2_{i,k} \f] - * - Co-occurenced Based Features ()::Overall Contrast: + * - Co-occurenced Based Features (\)::%Overall Contrast: * \f[ \textup{Contrast} = \sum_i \sum_k (i-k)^2 p_{i,k} \f] - * - Co-occurenced Based Features ()::Overall Dissimilarity: + * - Co-occurenced Based Features (\)::%Overall Dissimilarity: * \f[ \textup{Dissimilarity} = \sum_i \sum_k \| i-k\| p^2_{i,k} \f] - * - Co-occurenced Based Features ()::Overall Inverse Difference: + * - Co-occurenced Based Features (\)::%Overall Inverse Difference: * \f[ \textup{Inverse Difference} = \sum_i \sum_k \frac{p_{i,k}}{1+\| i-k\|} \f] - * - Co-occurenced Based Features ()::Overall Inverse Difference Normalized: + * - Co-occurenced Based Features (\)::%Overall Inverse Difference Normalized: * \f[ \textup{Inverse Difference Normalized} = \sum_i \sum_k \frac{p_{i,k}}{1+\frac{\| i-k\|}{N_g}} \f] - * - Co-occurenced Based Features ()::Overall Inverse Difference Moment: + * - Co-occurenced Based Features (\)::%Overall Inverse Difference Moment: * \f[ \textup{Inverse Difference Moment} = \sum_i \sum_k \frac{p_{i,k}}{1+ ( i-k )^2} \f] - * - Co-occurenced Based Features ()::Overall Inverse Difference Moment Normalized: + * - Co-occurenced Based Features (\)::%Overall Inverse Difference Moment Normalized: * \f[ \textup{Inverse Difference Moment Normalized} = \sum_i \sum_k \frac{p_{i,k}}{1+\frac{( i-k ) ^2}{N_g}} \f] - * - Co-occurenced Based Features ()::Overall Inverse Variance: + * - Co-occurenced Based Features (\)::%Overall Inverse Variance: * \f[ \textup{Inverse Difference Moment Normalized} = \sum_i \sum_k \frac{p_{i,k}}{(i-k)^2} \f] - * - Co-occurenced Based Features ()::Overall Correlation: + * - Co-occurenced Based Features (\)::%Overall Correlation: * \f[ \textup{Correlation} = \frac{1}{\sigma^2_{i,\cdot}} \sum_i \sum_k (i - \mu_{ra})(k - \mu_{ra}) p_{i,k} \f] - * - Co-occurenced Based Features ()::Overall Autocorrelation: + * - Co-occurenced Based Features (\)::%Overall Autocorrelation: * \f[ \textup{Autocorrelation} = \sum_i \sum_k i k p_{i,k} \f] - * - Co-occurenced Based Features ()::Overall Cluster Tendency: + * - Co-occurenced Based Features (\)::%Overall Cluster Tendency: * \f[ \textup{Cluster Tendency} = \sum_i \sum_k (i + k - 2\mu_{ra})^2 p_{i,k} \f] - * - Co-occurenced Based Features ()::Overall Cluster Shade: + * - Co-occurenced Based Features (\)::%Overall Cluster Shade: * \f[ \textup{Cluster Shade} = \sum_i \sum_k (i + k - 2\mu_{ra})^3 p_{i,k} \f] - * - Co-occurenced Based Features ()::Overall Cluster Prominence: + * - Co-occurenced Based Features (\)::%Overall Cluster Prominence: * \f[ \textup{Cluster Prominence} = \sum_i \sum_k (i + k - 2\mu_{ra})^4 p_{i,k} \f] - * - Co-occurenced Based Features ()::Overall First Measure of Information Correlation: + * - Co-occurenced Based Features (\)::%Overall First Measure of Information Correlation: * \f[ \textup{First Measure of Information Correlation} = \frac{ e_j- e_1}{e_r} \f] - * - Co-occurenced Based Features ()::Overall Second Measure of Information Correlation: + * - Co-occurenced Based Features (\)::%Overall Second Measure of Information Correlation: * \f[ \textup{Second Measure of Information Correlation} = \sqrt{1- \exp(-2 (e_2 - e_j)} \f] */ class MITKCLUTILITIES_EXPORT GIFCooccurenceMatrix2 : public AbstractGlobalImageFeature { public: mitkClassMacro(GIFCooccurenceMatrix2, AbstractGlobalImageFeature); itkFactorylessNewMacro(Self); itkCloneMacro(Self); GIFCooccurenceMatrix2(); FeatureListType CalculateFeatures(const Image* image, const Image* mask, const Image* maskNoNAN) override; using Superclass::CalculateFeatures; itkGetConstMacro(Ranges, std::vector); void SetRanges(std::vector ranges); void SetRange(double range); void AddArguments(mitkCommandLineParser& parser) const override; protected: std::string GenerateLegacyFeatureEncoding(const FeatureID& id) const override; FeatureListType DoCalculateFeatures(const Image* image, const Image* mask) override; void ConfigureSettingsByParameters(const ParametersType& parameters) override; private: std::vector m_Ranges; }; } #endif //mitkGIFCooccurenceMatrix2_h diff --git a/Modules/Classification/CLUtilities/include/mitkGIFCurvatureStatistic.h b/Modules/Classification/CLUtilities/include/mitkGIFCurvatureStatistic.h index d2e8b022cc..302f452775 100644 --- a/Modules/Classification/CLUtilities/include/mitkGIFCurvatureStatistic.h +++ b/Modules/Classification/CLUtilities/include/mitkGIFCurvatureStatistic.h @@ -1,98 +1,98 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkGIFCurvatureStatistic_h #define mitkGIFCurvatureStatistic_h #include #include #include namespace mitk { /** * \brief Calculates features based on the co-occurence matrix. * * The Curvature is a measure for the bending of a surface and is therefore a measure for the description of the * surface of an segmentation. * * THe curvature is calculated for each point of the surface of the given object and then a combined measure is * produced. It measures the divergence of the orientation of an curve from the * tangent of the curve. There are multiple ways to calculate the Curvature: * * Gaussian Curvature: The discrete gaussian curvature (K) is computed as \f$K(\textup{Corner Point v}) = 2 * \pi - \sum_{\textup{Neighoubring Voxel Surfaces f of v}} (\textup{Angle}_f \textup{at} v) \f$. * Mean Curvature:The mean curvature (H) is computed as \f$H(\textup{Corner Point v}) = \textup{average over edges e neighbouring v of H(e)} \f$. * with \f$H(edge e) = length(e)*dihedral_angle(e)\f$ * Maximum (\f$k_max\f$) and Minimum (\f$k_min\f$) Principal Curvatures * \f$k_max = H + sqrt(H^2 - K)\f$ * \f$k_min = H - sqrt(H^2 - K)\f$ * Excepting spherical and planar surfaces which have equal principal curvatures, * the curvature at a point on a surface varies with the direction one "sets off" * from the point. For all directions, the curvature will pass through two extrema: * a minimum (\f$k_min\f$) and a maximum (\f$k_max\f$) which occur at mutually orthogonal * directions to each other. * * This method does not take any parameters. * * This feature calculator is activated by the option -curvature or -cur. * * The features are calculated based on a mask, which is converted into a mesh. * * The following features are defined. All features are calculated for all four possible * curvation calculation methods (Gaussian, Mean, Minimum, Maximum). The principal way - * of calculating these features is the same, the used curvation is indicated by in the + * of calculating these features is the same, the used curvation is indicated by \ in the * feature name: * - * - Curvature Feature::Minimum Curvature: + * - Curvature Feature::Minimum \ Curvature: * The minimum curvature for the whole given mask - * - Curvature Feature::Maximum Curvature: + * - Curvature Feature::Maximum \ Curvature: * The maximum curvature for the whole given mask - * - Curvature Feature::Mean Curvature: + * - Curvature Feature::Mean \ Curvature: * The mean curvature for the whole given mask - * - Curvature Feature::Standard Deviation Curvature: + * - Curvature Feature::Standard Deviation \ Curvature: * The standard deviation curvature for the whole given mask - * - Curvature Feature::Skewness Curvature: + * - Curvature Feature::Skewness \ Curvature: * The skewness curvature for the whole given mask - * - Curvature Feature::Mean Positive Curvature: + * - Curvature Feature::Mean Positive \ Curvature: * The mean curvature of all positive curvatures from the whole given mask - * - Curvature Feature::Standard Deviation Positive Curvature: + * - Curvature Feature::Standard Deviation Positive \ Curvature: * The Standard Deviation curvature of all positive curvatures from the whole given mask - * - Curvature Feature::Skewness Positive Curvature: + * - Curvature Feature::Skewness Positive \ Curvature: * The Skewness curvature of all positive curvatures from the whole given mask - * - Curvature Feature::Mean Negative Curvature: + * - Curvature Feature::Mean Negative \ Curvature: * The mean curvature of all Negative curvatures from the whole given mask - * - Curvature Feature::Standard Deviation Negative Curvature: + * - Curvature Feature::Standard Deviation Negative \ Curvature: * The Standard Deviation curvature of all Negative curvatures from the whole given mask - * - Curvature Feature::Skewness Negative Curvature: + * - Curvature Feature::Skewness Negative \ Curvature: * The Skewness curvature of all Negative curvatures from the whole given mask */ class MITKCLUTILITIES_EXPORT GIFCurvatureStatistic : public AbstractGlobalImageFeature { public: mitkClassMacro(GIFCurvatureStatistic,AbstractGlobalImageFeature); itkFactorylessNewMacro(Self); itkCloneMacro(Self); GIFCurvatureStatistic(); FeatureListType CalculateFeatures(const Image* image, const Image* mask, const Image* maskNoNAN) override; using Superclass::CalculateFeatures; void AddArguments(mitkCommandLineParser &parser) const override; protected: FeatureListType DoCalculateFeatures(const Image* image, const Image* mask) override; }; } #endif //mitkGIFCurvatureStatistic_h diff --git a/Modules/ContourModel/DataManagement/mitkContourElement.h b/Modules/ContourModel/DataManagement/mitkContourElement.h index ed4342255b..9191b72409 100644 --- a/Modules/ContourModel/DataManagement/mitkContourElement.h +++ b/Modules/ContourModel/DataManagement/mitkContourElement.h @@ -1,237 +1,237 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _mitkContourElement_H_ #define _mitkContourElement_H_ #include "mitkCommon.h" #include #include //#include #include namespace mitk { /** \brief Represents a contour in 3D space. A ContourElement is consisting of linked vertices implicitely defining the contour. They are stored in a double ended queue making it possible to add vertices at front and end of the contour and to iterate in both directions. To mark a vertex as a special one it can be set as a control point. - \Note It is highly not recommend to use this class directly as no secure mechanism is used here. + \note It is highly not recommend to use this class directly as no secure mechanism is used here. Use mitk::ContourModel instead providing some additional features. */ class MITKCONTOURMODEL_EXPORT ContourElement : public itk::LightObject { public: mitkClassMacroItkParent(ContourElement, itk::LightObject); itkFactorylessNewMacro(Self); itkCloneMacro(Self); // Data container representing vertices /** \brief Represents a single vertex of contour. */ struct ContourModelVertex { ContourModelVertex(mitk::Point3D &point, bool active = false) : IsControlPoint(active), Coordinates(point) {} ContourModelVertex(const ContourModelVertex &other) : IsControlPoint(other.IsControlPoint), Coordinates(other.Coordinates) { } /** \brief Treat point special. */ bool IsControlPoint; /** \brief Coordinates in 3D space. */ mitk::Point3D Coordinates; }; // END Data container representing vertices typedef ContourModelVertex VertexType; typedef std::deque VertexListType; typedef VertexListType::iterator VertexIterator; typedef VertexListType::const_iterator ConstVertexIterator; // start of inline methods /** \brief Return a const iterator a the front. */ virtual ConstVertexIterator ConstIteratorBegin() { return this->m_Vertices->begin(); } /** \brief Return a const iterator a the end. */ virtual ConstVertexIterator ConstIteratorEnd() { return this->m_Vertices->end(); } /** \brief Return an iterator a the front. */ virtual VertexIterator IteratorBegin() { return this->m_Vertices->begin(); } /** \brief Return an iterator a the end. */ virtual VertexIterator IteratorEnd() { return this->m_Vertices->end(); } /** \brief Returns the number of contained vertices. */ virtual int GetSize() { return this->m_Vertices->size(); } // end of inline methods /** \brief Add a vertex at the end of the contour \param point - coordinates in 3D space. \param isControlPoint - is the vertex a special control point. */ virtual void AddVertex(mitk::Point3D &point, bool isControlPoint); /** \brief Add a vertex at the end of the contour \param vertex - a contour element vertex. */ virtual void AddVertex(VertexType &vertex); /** \brief Add a vertex at the front of the contour \param point - coordinates in 3D space. \param isControlPoint - is the vertex a control point. */ virtual void AddVertexAtFront(mitk::Point3D &point, bool isControlPoint); /** \brief Add a vertex at the front of the contour \param vertex - a contour element vertex. */ virtual void AddVertexAtFront(VertexType &vertex); /** \brief Add a vertex at a given index of the contour \param point - coordinates in 3D space. \param isControlPoint - is the vertex a special control point. \param index - the index to be inserted at. */ virtual void InsertVertexAtIndex(mitk::Point3D &point, bool isControlPoint, int index); /** \brief Set coordinates a given index. \param pointId Index of vertex. \param point Coordinates. */ virtual void SetVertexAt(int pointId, const mitk::Point3D &point); /** \brief Set vertex a given index. \param pointId Index of vertex. \param vertex Vertex. */ virtual void SetVertexAt(int pointId, const VertexType *vertex); /** \brief Returns the vertex a given index \param index */ virtual VertexType *GetVertexAt(int index); /** \brief Returns the approximate nearest vertex a given posoition in 3D space \param point - query position in 3D space. \param eps - the error bound for search algorithm. */ virtual VertexType *GetVertexAt(const mitk::Point3D &point, float eps); /** \brief Returns the index of the given vertex within the contour. \param vertex - the vertex to be searched. \return index of vertex. -1 if not found. */ virtual int GetIndex(const VertexType *vertex); /** \brief Returns the container of the vertices. */ VertexListType *GetVertexList(); /** \brief Returns whether the contour element is empty. */ bool IsEmpty(); /** \brief Returns if the conour is closed or not. */ virtual bool IsClosed(); /** \brief Returns whether a given point is near a contour, according to eps. \param point - query position in 3D space. \param eps - the error bound for search algorithm. */ virtual bool IsNearContour(const mitk::Point3D &point, float eps); /** \brief Close the contour. Connect first with last element. */ virtual void Close(); /** \brief Open the contour. Disconnect first and last element. */ virtual void Open(); /** \brief Set the contours IsClosed property. \param isClosed - true = closed; false = open; */ virtual void SetClosed(bool isClosed); /** \brief Concatenate the contuor with a another contour. All vertices of the other contour will be added after last vertex. \param other - the other contour \param check - set it true to avoid intersections */ void Concatenate(mitk::ContourElement *other, bool check); /** \brief Remove the given vertex from the container if exists. \param vertex - the vertex to be removed. */ virtual bool RemoveVertex(const VertexType *vertex); /** \brief Remove a vertex at given index within the container if exists. \param index - the index where the vertex should be removed. */ virtual bool RemoveVertexAt(int index); /** \brief Remove the approximate nearest vertex at given position in 3D space if one exists. \param point - query point in 3D space. \param eps - error bound for search algorithm. */ virtual bool RemoveVertexAt(mitk::Point3D &point, float eps); /** \brief Clear the storage container. */ virtual void Clear(); /** \brief Returns the approximate nearest vertex a given posoition in 3D space \param point - query position in 3D space. \param eps - the error bound for search algorithm. */ VertexType *BruteForceGetVertexAt(const mitk::Point3D &point, float eps); /** \brief Returns the approximate nearest vertex a given posoition in 3D space \param point - query position in 3D space. \param eps - the error bound for search algorithm. */ // VertexType* OptimizedGetVertexAt(const mitk::Point3D &point, float eps); VertexListType *GetControlVertices(); /** \brief Uniformly redistribute control points with a given period (in number of vertices) \param vertex - the vertex around which the redistribution is done. \param period - number of vertices between control points. */ void RedistributeControlVertices(const VertexType *vertex, int period); protected: mitkCloneMacro(Self); ContourElement(); ContourElement(const mitk::ContourElement &other); ~ContourElement() override; VertexListType *m_Vertices; // double ended queue with vertices bool m_IsClosed; }; } // namespace mitk #endif // _mitkContourElement_H_ diff --git a/Modules/ContourModel/DataManagement/mitkContourModel.h b/Modules/ContourModel/DataManagement/mitkContourModel.h index 581768c89a..7cded5022d 100644 --- a/Modules/ContourModel/DataManagement/mitkContourModel.h +++ b/Modules/ContourModel/DataManagement/mitkContourModel.h @@ -1,452 +1,452 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _MITK_CONTOURMODEL_H_ #define _MITK_CONTOURMODEL_H_ #include "mitkBaseData.h" #include "mitkCommon.h" #include #include namespace mitk { /** \brief ContourModel is a structure of linked vertices defining a contour in 3D space. The vertices are stored in a mitk::ContourElement is stored for each timestep. The contour line segments are implicitly defined by the given linked vertices. By default two control points are are linked by a straight line.It is possible to add vertices at front and end of the contour and to iterate in both directions. Points are specified containing coordinates and additional (data) information, see mitk::ContourElement. For accessing a specific vertex either an index or a position in 3D Space can be used. The vertices are best accessed by using a VertexIterator. Interaction with the contour is thus available without any mitk interactor class using the api of ContourModel. It is possible to shift single vertices also as shifting the whole contour. A contour can be either open like a single curved line segment or closed. A closed contour can for example represent a jordan curve. \section mitkContourModelDisplayOptions Display Options The default mappers for this data structure are mitk::ContourModelGLMapper2D and mitk::ContourModelMapper3D. See these classes for display options which can can be set via properties. */ class MITKCONTOURMODEL_EXPORT ContourModel : public BaseData { public: mitkClassMacro(ContourModel, BaseData); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /*+++++++++++++++ typedefs +++++++++++++++++++++++++++++++*/ typedef mitk::ContourElement::VertexType VertexType; typedef mitk::ContourElement::VertexListType VertexListType; typedef mitk::ContourElement::VertexIterator VertexIterator; typedef mitk::ContourElement::ConstVertexIterator ConstVertexIterator; typedef std::vector ContourModelSeries; /*+++++++++++++++ END typedefs ++++++++++++++++++++++++++++*/ /** \brief Possible interpolation of the line segments between control points */ enum LineSegmentInterpolation { LINEAR, B_SPLINE }; /*++++++++++++++++ inline methods +++++++++++++++++++++++*/ /** \brief Get the current selected vertex. */ VertexType *GetSelectedVertex() { return this->m_SelectedVertex; } /** \brief Deselect vertex. */ void Deselect() { this->m_SelectedVertex = nullptr; } /** \brief Set selected vertex as control point */ void SetSelectedVertexAsControlPoint(bool isControlPoint = true) { if (this->m_SelectedVertex) { m_SelectedVertex->IsControlPoint = isControlPoint; this->Modified(); } } /** \brief Set the interpolation of the line segments between control points. */ void SetLineSegmentInterpolation(LineSegmentInterpolation interpolation) { this->m_lineInterpolation = interpolation; this->Modified(); } /** \brief Get the interpolation of the line segments between control points. */ LineSegmentInterpolation GetLineSegmentInterpolation() { return this->m_lineInterpolation; } /*++++++++++++++++ END inline methods +++++++++++++++++++++++*/ /** \brief Add a vertex to the contour at given timestep. The vertex is added at the end of contour. \param vertex - coordinate representation of a control point \param timestep - the timestep at which the vertex will be add ( default 0) - @Note Adding a vertex to a timestep which exceeds the timebounds of the contour + @note Adding a vertex to a timestep which exceeds the timebounds of the contour will not be added, the TimeGeometry will not be expanded. */ void AddVertex(mitk::Point3D &vertex, int timestep = 0); /** \brief Add a vertex to the contour at given timestep. The vertex is added at the end of contour. \param vertex - coordinate representation of a control point \param timestep - the timestep at which the vertex will be add ( default 0) - @Note Adding a vertex to a timestep which exceeds the timebounds of the contour + @note Adding a vertex to a timestep which exceeds the timebounds of the contour will not be added, the TimeGeometry will not be expanded. */ void AddVertex(VertexType &vertex, int timestep = 0); /** \brief Add a vertex to the contour at given timestep. The vertex is added at the end of contour. \param vertex - coordinate representation of a control point \param timestep - the timestep at which the vertex will be add ( default 0) - @Note Adding a vertex to a timestep which exceeds the timebounds of the contour + @note Adding a vertex to a timestep which exceeds the timebounds of the contour will not be added, the TimeSlicedGeometry will not be expanded. */ void AddVertex(const VertexType *vertex, int timestep = 0); /** \brief Add a vertex to the contour. \param vertex - coordinate representation of a control point \param timestep - the timestep at which the vertex will be add ( default 0) \param isControlPoint - specifies the vertex to be handled in a special way (e.g. control points will be rendered). - @Note Adding a vertex to a timestep which exceeds the timebounds of the contour + @note Adding a vertex to a timestep which exceeds the timebounds of the contour will not be added, the TimeGeometry will not be expanded. */ void AddVertex(mitk::Point3D &vertex, bool isControlPoint, int timestep = 0); /** \brief Add a vertex to the contour at given timestep AT THE FRONT of the contour. The vertex is added at the FRONT of contour. \param vertex - coordinate representation of a control point \param timestep - the timestep at which the vertex will be add ( default 0) - @Note Adding a vertex to a timestep which exceeds the timebounds of the contour + @note Adding a vertex to a timestep which exceeds the timebounds of the contour will not be added, the TimeGeometry will not be expanded. */ void AddVertexAtFront(mitk::Point3D &vertex, int timestep = 0); /** \brief Add a vertex to the contour at given timestep AT THE FRONT of the contour. The vertex is added at the FRONT of contour. \param vertex - coordinate representation of a control point \param timestep - the timestep at which the vertex will be add ( default 0) - @Note Adding a vertex to a timestep which exceeds the timebounds of the contour + @note Adding a vertex to a timestep which exceeds the timebounds of the contour will not be added, the TimeGeometry will not be expanded. */ void AddVertexAtFront(VertexType &vertex, int timestep = 0); /** \brief Add a vertex to the contour at given timestep AT THE FRONT of the contour. \param vertex - coordinate representation of a control point \param timestep - the timestep at which the vertex will be add ( default 0) \param isControlPoint - specifies the vertex to be handled in a special way (e.g. control points will be rendered). - @Note Adding a vertex to a timestep which exceeds the timebounds of the contour + @note Adding a vertex to a timestep which exceeds the timebounds of the contour will not be added, the TimeGeometry will not be expanded. */ void AddVertexAtFront(mitk::Point3D &vertex, bool isControlPoint, int timestep = 0); /** \brief Insert a vertex at given index. */ void InsertVertexAtIndex(mitk::Point3D &vertex, int index, bool isControlPoint = false, int timestep = 0); /** \brief Set a coordinates for point at given index. */ bool SetVertexAt(int pointId, const mitk::Point3D &point, unsigned int timestep = 0); /** \brief Set a coordinates for point at given index. */ bool SetVertexAt(int pointId, const VertexType *vertex, unsigned int timestep = 0); /** \brief Return if the contour is closed or not. */ bool IsClosed(int timestep = 0) const; /** \brief Concatenate two contours. The starting control point of the other will be added at the end of the contour. \param timestep - the timestep at which the vertex will be add ( default 0) \param check - check for intersections ( default false) */ void Concatenate(mitk::ContourModel *other, int timestep = 0, bool check = false); /** \brief Returns a const VertexIterator at the start element of the contour. @throw mitk::Exception if the timestep is invalid. */ VertexIterator Begin(int timestep = 0) const; /** \brief Returns a const VertexIterator at the start element of the contour. @throw mitk::Exception if the timestep is invalid. */ VertexIterator IteratorBegin(int timestep = 0) const; /** \brief Returns a const VertexIterator at the end element of the contour. @throw mitk::Exception if the timestep is invalid. */ VertexIterator End(int timestep = 0) const; /** \brief Returns a const VertexIterator at the end element of the contour. @throw mitk::Exception if the timestep is invalid. */ VertexIterator IteratorEnd(int timestep = 0) const; /** \brief Close the contour. The last control point will be linked with the first point. */ virtual void Close(int timestep = 0); /** \brief Set isClosed to false contour. The link between the last control point the first point will be removed. */ virtual void Open(int timestep = 0); /** \brief Set closed property to given boolean. false - The link between the last control point the first point will be removed. true - The last control point will be linked with the first point. */ virtual void SetClosed(bool isClosed, int timestep = 0); /** \brief Returns the number of vertices at a given timestep. \param timestep - default = 0 */ int GetNumberOfVertices(int timestep = 0) const; /** \brief Returns whether the contour model is empty at a given timestep. \param timestep - default = 0 */ virtual bool IsEmpty(int timestep) const; /** \brief Returns whether the contour model is empty. */ bool IsEmpty() const override; /** \brief Returns the vertex at the index position within the container. */ virtual const VertexType *GetVertexAt(int index, int timestep = 0) const; /** \brief Remove a vertex at given timestep within the container. \return index of vertex. -1 if not found. */ int GetIndex(const VertexType *vertex, int timestep = 0); /** \brief Check if there isn't something at this timestep. */ bool IsEmptyTimeStep(unsigned int t) const override; /** \brief Check if mouse cursor is near the contour. */ virtual bool IsNearContour(mitk::Point3D &point, float eps, int timestep); /** \brief Mark a vertex at an index in the container as selected. */ bool SelectVertexAt(int index, int timestep = 0); /** \brief Mark a vertex at an index in the container as control point. */ bool SetControlVertexAt(int index, int timestep = 0); /** \brief Mark a vertex at a given position in 3D space. \param point - query point in 3D space \param eps - radius for nearest neighbour search (error bound). \param timestep - search at this timestep @return true = vertex found; false = no vertex found */ bool SelectVertexAt(mitk::Point3D &point, float eps, int timestep = 0); /* \pararm point - query point in 3D space \pararm eps - radius for nearest neighbour search (error bound). \pararm timestep - search at this timestep @return true = vertex found; false = no vertex found */ bool SetControlVertexAt(mitk::Point3D &point, float eps, int timestep = 0); /** \brief Remove a vertex at given index within the container. @return true = the vertex was successfuly removed; false = wrong index. */ bool RemoveVertexAt(int index, int timestep = 0); /** \brief Remove a vertex at given timestep within the container. @return true = the vertex was successfuly removed. */ bool RemoveVertex(const VertexType *vertex, int timestep = 0); /** \brief Remove a vertex at a query position in 3D space. The vertex to be removed will be search by nearest neighbour search. Note that possibly no vertex at this position and eps is stored inside the contour. @return true = the vertex was successfuly removed; false = no vertex found. */ bool RemoveVertexAt(mitk::Point3D &point, float eps, int timestep = 0); /** \brief Shift the currently selected vertex by a translation vector. \param translate - the translation vector. */ void ShiftSelectedVertex(mitk::Vector3D &translate); /** \brief Shift the whole contour by a translation vector at given timestep. \param translate - the translation vector. \param timestep - at this timestep the contour will be shifted. */ void ShiftContour(mitk::Vector3D &translate, int timestep = 0); /** \brief Clear the storage container at given timestep. All control points are removed at timestep. */ virtual void Clear(int timestep); /** \brief Initialize all data objects */ void Initialize() override; /** \brief Initialize object with specs of other contour. Note: No data will be copied. */ void Initialize(mitk::ContourModel &other); /*++++++++++++++++++ method inherit from base data +++++++++++++++++++++++++++*/ /** \brief Inherit from base data - no region support available for contourModel objects. */ void SetRequestedRegionToLargestPossibleRegion() override; /** \brief Inherit from base data - no region support available for contourModel objects. */ bool RequestedRegionIsOutsideOfTheBufferedRegion() override; /** \brief Inherit from base data - no region support available for contourModel objects. */ bool VerifyRequestedRegion() override; /** \brief Get the updated geometry with recomputed bounds. */ virtual const mitk::BaseGeometry *GetUpdatedGeometry(int t = 0); /** \brief Get the BaseGeometry for timestep t. */ virtual mitk::BaseGeometry *GetGeometry(int t = 0) const; /** \brief Inherit from base data - no region support available for contourModel objects. */ void SetRequestedRegion(const itk::DataObject *data) override; /** \brief Expand the timebounds of the TimeGeometry to given number of timesteps. */ void Expand(unsigned int timeSteps) override; /** \brief Update the OutputInformation of a ContourModel object The BoundingBox of the contour will be updated, if necessary. */ void UpdateOutputInformation() override; /** \brief Clear the storage container. The object is set to initial state. All control points are removed and the number of timesteps are set to 1. */ void Clear() override; /** \brief overwrite if the Data can be called by an Interactor (StateMachine). */ void ExecuteOperation(Operation *operation) override; /** \brief Redistributes ontrol vertices with a given period (as number of vertices) \param period - the number of vertices between control points. \param timestep - at this timestep all lines will be rebuilt. */ virtual void RedistributeControlVertices(int period, int timestep); protected: mitkCloneMacro(Self); ContourModel(); ContourModel(const mitk::ContourModel &other); ~ContourModel() override; // inherit from BaseData. called by Clear() void ClearData() override; // inherit from BaseData. Initial state of a contour with no vertices and a single timestep. void InitializeEmpty() override; // Shift a vertex void ShiftVertex(VertexType *vertex, mitk::Vector3D &vector); // Storage with time resolved support. ContourModelSeries m_ContourSeries; // The currently selected vertex. VertexType *m_SelectedVertex; // The interpolation of the line segment between control points. LineSegmentInterpolation m_lineInterpolation; // only update the bounding geometry if necessary bool m_UpdateBoundingBox; }; itkEventMacro(ContourModelEvent, itk::AnyEvent); itkEventMacro(ContourModelShiftEvent, ContourModelEvent); itkEventMacro(ContourModelSizeChangeEvent, ContourModelEvent); itkEventMacro(ContourModelAddEvent, ContourModelSizeChangeEvent); itkEventMacro(ContourModelRemoveEvent, ContourModelSizeChangeEvent); itkEventMacro(ContourModelExpandTimeBoundsEvent, ContourModelEvent); itkEventMacro(ContourModelClosedEvent, ContourModelEvent); } #endif diff --git a/Modules/Core/include/mitkBaseGeometry.h b/Modules/Core/include/mitkBaseGeometry.h index 32940d3d80..bda3ebf7fc 100644 --- a/Modules/Core/include/mitkBaseGeometry.h +++ b/Modules/Core/include/mitkBaseGeometry.h @@ -1,765 +1,755 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BaseGeometry_H_HEADER_INCLUDED #define BaseGeometry_H_HEADER_INCLUDED #include "mitkOperationActor.h" #include #include #include "itkScalableAffineTransform.h" #include "mitkNumericTypes.h" #include #include #include #include #include #include #include class vtkMatrix4x4; class vtkMatrixToLinearTransform; class vtkLinearTransform; namespace mitk { //##Documentation //## @brief Standard 3D-BoundingBox typedef //## //## Standard 3D-BoundingBox typedef to get rid of template arguments (3D, type). typedef itk::BoundingBox BoundingBox; //##Documentation //## @brief Standard typedef for time-bounds typedef itk::FixedArray TimeBounds; typedef itk::FixedArray FixedArrayType; typedef itk::AffineGeometryFrame AffineGeometryFrame3D; //##Documentation //## @brief BaseGeometry Describes the geometry of a data object //## //## The class holds //## \li a bounding box which is axes-parallel in intrinsic coordinates //## (often integer indices of pixels), to be accessed by //## GetBoundingBox() //## \li a transform to convert intrinsic coordinates into a //## world-coordinate system with coordinates in millimeters //## and milliseconds (all are floating point values), to //## be accessed by GetIndexToWorldTransform() //## \li an origin and spacing to define the geometry //## //## BaseGeometry and its sub-classes allow converting between //## intrinsic coordinates (called index or unit coordinates) //## and world-coordinates (called world or mm coordinates), //## e.g. WorldToIndex. //## In case you need integer index coordinates, provide an //## mitk::Index3D (or itk::Index) as target variable to //## WorldToIndex, otherwise you will get a continuous index //## (floating point values). //## //## An important sub-class is SlicedGeometry3D, which descibes //## data objects consisting of slices, e.g., objects of type Image. //## Conversions between world coordinates (in mm) and unit coordinates //## (e.g., pixels in the case of an Image) can be performed. //## //## For more information on related classes, see \ref Geometry. //## //## BaseGeometry instances referring to an Image need a slightly //## different definition of corners, see SetImageGeometry. This //## is usualy automatically called by Image. //## //## BaseGeometry have to be initialized in the method GenerateOutputInformation() //## of BaseProcess (or CopyInformation/ UpdateOutputInformation of BaseData, //## if possible, e.g., by analyzing pic tags in Image) subclasses. See also //## itk::ProcessObject::GenerateOutputInformation(), //## itk::DataObject::CopyInformation() and //## itk::DataObject::UpdateOutputInformation(). //## //## At least, it can return the bounding box of the data object. //## //## The BaseGeometry class is an abstract class. The most simple implementation //## is the sublass Geometry3D. //## //## Rule: everything is in mm (ms) if not stated otherwise. //## @ingroup Geometry class MITKCORE_EXPORT BaseGeometry : public itk::Object, public OperationActor { public: mitkClassMacroItkParent(BaseGeometry, itk::Object); itkCloneMacro(Self); // ********************************** TypeDef ********************************** typedef GeometryTransformHolder::TransformType TransformType; typedef itk::BoundingBox BoundingBoxType; typedef BoundingBoxType::BoundsArrayType BoundsArrayType; typedef BoundingBoxType::Pointer BoundingBoxPointer; // ********************************** Origin, Spacing ********************************** //##Documentation //## @brief Get the origin, e.g. the upper-left corner of the plane const Point3D GetOrigin() const; //##Documentation //## @brief Set the origin, i.e. the upper-left corner of the plane //## void SetOrigin(const Point3D &origin); //##Documentation //## @brief Get the spacing (size of a pixel). //## const mitk::Vector3D GetSpacing() const; //##Documentation //## @brief Set the spacing (m_Spacing). //## //##The spacing is also changed in the IndexToWorldTransform. void SetSpacing(const mitk::Vector3D &aSpacing, bool enforceSetSpacing = false); //##Documentation //## @brief Get the origin as VnlVector //## //## \sa GetOrigin VnlVector GetOriginVnl() const; // ********************************** other functions ********************************** //##Documentation //## @brief Get the DICOM FrameOfReferenceID referring to the //## used world coordinate system itkGetConstMacro(FrameOfReferenceID, unsigned int); //##Documentation //## @brief Set the DICOM FrameOfReferenceID referring to the //## used world coordinate system itkSetMacro(FrameOfReferenceID, unsigned int); itkGetConstMacro(IndexToWorldTransformLastModified, unsigned long); //##Documentation //## @brief Overload of function Modified() to prohibit several calls of Modified() using the ModifiedLock class. //## //## For the use of Modified(), see class ModifiedLock. void Modified() const override; friend class ModifiedLock; //##Documentation //## @brief Is this BaseGeometry in a state that is valid? //## //## This function returns always true in the BaseGeometry class. Other implementations are possible in subclasses. virtual bool IsValid() const; // ********************************** Initialize ********************************** //##Documentation //## @brief Initialize the BaseGeometry void Initialize(); void InitializeGeometry(Self *newGeometry) const; // ********************************** Transformations Set/Get ********************************** //##Documentation //## @brief Get the transformation used to convert from index //## to world coordinates mitk::AffineTransform3D *GetIndexToWorldTransform(); //##Documentation //## @brief Get the transformation used to convert from index //## to world coordinates const mitk::AffineTransform3D *GetIndexToWorldTransform() const; //## @brief Set the transformation used to convert from index //## to world coordinates. The spacing of the new transform is //## copied to m_spacing. void SetIndexToWorldTransform(mitk::AffineTransform3D *transform); //##Documentation //## @brief Convenience method for setting the ITK transform //## (m_IndexToWorldTransform) via an vtkMatrix4x4.The spacing of //## the new transform is copied to m_spacing. //## \sa SetIndexToWorldTransform void SetIndexToWorldTransformByVtkMatrix(vtkMatrix4x4 *vtkmatrix); //## @brief Set the transformation used to convert from index //## to world coordinates.This function keeps the original spacing. void SetIndexToWorldTransformWithoutChangingSpacing(mitk::AffineTransform3D *transform); //##Documentation //## @brief Convenience method for setting the ITK transform //## (m_IndexToWorldTransform) via an vtkMatrix4x4. This function keeps the original spacing. //## \sa SetIndexToWorldTransform void SetIndexToWorldTransformByVtkMatrixWithoutChangingSpacing(vtkMatrix4x4 *vtkmatrix); //## Get the Vtk Matrix which describes the transform. vtkMatrix4x4 *GetVtkMatrix(); //##Documentation //## @brief Get the m_IndexToWorldTransform as a vtkLinearTransform vtkLinearTransform *GetVtkTransform() const; //##Documentation //## @brief Set the transform to identity, the spacing to 1 and origin to 0 //## void SetIdentity(); // ********************************** Transformations ********************************** //##Documentation //## @brief Compose new IndexToWorldTransform with a given transform. //## //## This method composes m_IndexToWorldTransform with another transform, //## modifying self to be the composition of self and other. //## If the argument pre is true, then other is precomposed with self; //## that is, the resulting transformation consists of first applying //## other to the source, followed by self. If pre is false or omitted, //## then other is post-composed with self; that is the resulting //## transformation consists of first applying self to the source, //## followed by other. //## This method also changes m_spacing. void Compose(const TransformType *other, bool pre = false); //##Documentation //## @brief Compose new IndexToWorldTransform with a given vtkMatrix4x4. //## //## Converts the vtkMatrix4x4 into a itk-transform and calls the previous method. void Compose(const vtkMatrix4x4 *vtkmatrix, bool pre = false); //##Documentation //## @brief Translate the origin by a vector //## void Translate(const Vector3D &vector); //##Documentation //##@brief executes affine operations (translate, rotate, scale) void ExecuteOperation(Operation *operation) override; //##Documentation //## @brief Convert world coordinates (in mm) of a \em point to (continuous!) index coordinates //## \warning If you need (discrete) integer index coordinates (e.g., for iterating easily over an image), //## use WorldToIndex(const mitk::Point3D& pt_mm, itk::Index &index). //## For further information about coordinates types, please see the Geometry documentation void WorldToIndex(const mitk::Point3D &pt_mm, mitk::Point3D &pt_units) const; //##Documentation //## @brief Convert world coordinates (in mm) of a \em vector //## \a vec_mm to (continuous!) index coordinates. //## For further information about coordinates types, please see the Geometry documentation void WorldToIndex(const mitk::Vector3D &vec_mm, mitk::Vector3D &vec_units) const; //##Documentation //## @brief Convert world coordinates (in mm) of a \em point to (discrete!) index coordinates. //## This method rounds to integer indices! //## For further information about coordinates types, please see the Geometry documentation template void WorldToIndex(const mitk::Point3D &pt_mm, itk::Index &index) const { typedef itk::Index IndexType; mitk::Point3D pt_units; this->WorldToIndex(pt_mm, pt_units); int i, dim = index.GetIndexDimension(); if (dim > 3) { index.Fill(0); dim = 3; } for (i = 0; i < dim; ++i) { index[i] = itk::Math::RoundHalfIntegerUp(pt_units[i]); } } //##Documentation //## @brief Convert (continuous or discrete) index coordinates of a \em vector //## \a vec_units to world coordinates (in mm) //## For further information about coordinates types, please see the Geometry documentation void IndexToWorld(const mitk::Vector3D &vec_units, mitk::Vector3D &vec_mm) const; //##Documentation //## @brief Convert (continuous or discrete) index coordinates of a \em point to world coordinates (in mm) //## For further information about coordinates types, please see the Geometry documentation void IndexToWorld(const mitk::Point3D &pt_units, mitk::Point3D &pt_mm) const; //##Documentation //## @brief Convert (discrete) index coordinates of a \em point to world coordinates (in mm) //## For further information about coordinates types, please see the Geometry documentation template void IndexToWorld(const itk::Index &index, mitk::Point3D &pt_mm) const { mitk::Point3D pt_units; pt_units.Fill(0); int i, dim = index.GetIndexDimension(); if (dim > 3) { dim = 3; } for (i = 0; i < dim; ++i) { pt_units[i] = index[i]; } IndexToWorld(pt_units, pt_mm); } //##Documentation //## @brief Convert (continuous or discrete) index coordinates of a \em vector //## \a vec_units to world coordinates (in mm) //## @deprecated First parameter (Point3D) is not used. If possible, please use void IndexToWorld(const // mitk::Vector3D& vec_units, mitk::Vector3D& vec_mm) const. //## For further information about coordinates types, please see the Geometry documentation void IndexToWorld(const mitk::Point3D &atPt3d_units, const mitk::Vector3D &vec_units, mitk::Vector3D &vec_mm) const; //##Documentation //## @brief Convert world coordinates (in mm) of a \em vector //## \a vec_mm to (continuous!) index coordinates. //## @deprecated First parameter (Point3D) is not used. If possible, please use void WorldToIndex(const // mitk::Vector3D& vec_mm, mitk::Vector3D& vec_units) const. //## For further information about coordinates types, please see the Geometry documentation void WorldToIndex(const mitk::Point3D &atPt3d_mm, const mitk::Vector3D &vec_mm, mitk::Vector3D &vec_units) const; //##Documentation //## @brief Deprecated for use with ITK version 3.10 or newer. //## Convert ITK physical coordinates of a \em point (in mm, //## but without a rotation) into MITK world coordinates (in mm) //## //## For more information, see WorldToItkPhysicalPoint. template void ItkPhysicalPointToWorld(const itk::Point &itkPhysicalPoint, mitk::Point3D &pt_mm) const { mitk::vtk2itk(itkPhysicalPoint, pt_mm); } //##Documentation //## @brief Deprecated for use with ITK version 3.10 or newer. //## Convert world coordinates (in mm) of a \em point to //## ITK physical coordinates (in mm, but without a possible rotation) //## //## This method is useful if you have want to access an mitk::Image //## via an itk::Image. ITK v3.8 and older did not support rotated (tilted) //## images, i.e., ITK images are always parallel to the coordinate axes. //## When accessing a (possibly rotated) mitk::Image via an itk::Image //## the rotational part of the transformation in the BaseGeometry is //## simply discarded; in other word: only the origin and spacing is //## used by ITK, not the complete matrix available in MITK. //## With WorldToItkPhysicalPoint you can convert an MITK world //## coordinate (including the rotation) into a coordinate that //## can be used with the ITK image as a ITK physical coordinate //## (excluding the rotation). template void WorldToItkPhysicalPoint(const mitk::Point3D &pt_mm, itk::Point &itkPhysicalPoint) const { mitk::vtk2itk(pt_mm, itkPhysicalPoint); } // ********************************** BoundingBox ********************************** /** Get the bounding box */ itkGetConstObjectMacro(BoundingBox, BoundingBoxType); // a bit of a misuse, but we want only doxygen to see the following: #ifdef DOXYGEN_SKIP //##Documentation //## @brief Get bounding box (in index/unit coordinates) itkGetConstObjectMacro(BoundingBox, BoundingBoxType); //##Documentation //## @brief Get bounding box (in index/unit coordinates) as a BoundsArrayType const BoundsArrayType GetBounds() const; #endif const BoundsArrayType GetBounds() const; //##Documentation //## \brief Set the bounding box (in index/unit coordinates) //## //## Only possible via the BoundsArray to make clear that a //## copy of the bounding-box is stored, not a reference to it. void SetBounds(const BoundsArrayType &bounds); //##Documentation //## @brief Set the bounding box (in index/unit coordinates) via a float array void SetFloatBounds(const float bounds[6]); //##Documentation //## @brief Set the bounding box (in index/unit coordinates) via a double array void SetFloatBounds(const double bounds[6]); //##Documentation //## @brief Get a VnlVector along bounding-box in the specified //## @a direction, length is spacing //## //## \sa GetAxisVector VnlVector GetMatrixColumn(unsigned int direction) const; //##Documentation //## @brief Calculates a bounding-box around the geometry relative //## to a coordinate system defined by a transform //## mitk::BoundingBox::Pointer CalculateBoundingBoxRelativeToTransform(const mitk::AffineTransform3D *transform) const; //##Documentation //## @brief Set the time bounds (in ms) // void SetTimeBounds(const TimeBounds& timebounds); // ********************************** Geometry ********************************** #ifdef DOXYGEN_SKIP //##Documentation //## @brief Get the extent of the bounding box (in index/unit coordinates) //## //## To access the extent in mm use GetExtentInMM ScalarType GetExtent(unsigned int direction) const; #endif /** Get the extent of the bounding box */ ScalarType GetExtent(unsigned int direction) const; //##Documentation //## @brief Get the extent of the bounding-box in the specified @a direction in mm //## //## Equals length of GetAxisVector(direction). ScalarType GetExtentInMM(int direction) const; //##Documentation //## @brief Get vector along bounding-box in the specified @a direction in mm //## //## The length of the vector is the size of the bounding-box in the //## specified @a direction in mm //## \sa GetMatrixColumn Vector3D GetAxisVector(unsigned int direction) const; //##Documentation //## @brief Checks, if the given geometry can be converted to 2D without information loss //## e.g. when a 2D image is saved, the matrix is usually cropped to 2x2, and when you load it back to MITK //## it will be filled with standard values. This function checks, if information would be lost during this //## procedure virtual bool Is2DConvertable(); //##Documentation //## @brief Get the center of the bounding-box in mm //## Point3D GetCenter() const; //##Documentation //## @brief Get the squared length of the diagonal of the bounding-box in mm //## double GetDiagonalLength2() const; //##Documentation //## @brief Get the length of the diagonal of the bounding-box in mm //## double GetDiagonalLength() const; //##Documentation //## @brief Get the position of the corner number \a id (in world coordinates) //## //## See SetImageGeometry for how a corner is defined on images. Point3D GetCornerPoint(int id) const; //##Documentation //## @brief Get the position of a corner (in world coordinates) //## //## See SetImageGeometry for how a corner is defined on images. Point3D GetCornerPoint(bool xFront = true, bool yFront = true, bool zFront = true) const; //##Documentation //## @brief Set the extent of the bounding-box in the specified @a direction in mm //## //## @note This changes the matrix in the transform, @a not the bounds, which are given in units! void SetExtentInMM(int direction, ScalarType extentInMM); //##Documentation //## @brief Test whether the point \a p (world coordinates in mm) is //## inside the bounding box bool IsInside(const mitk::Point3D &p) const; //##Documentation //## @brief Test whether the point \a p ((continous!)index coordinates in units) is //## inside the bounding box bool IsIndexInside(const mitk::Point3D &index) const; //##Documentation //## @brief Convenience method for working with ITK indices template bool IsIndexInside(const itk::Index &index) const { int i, dim = index.GetIndexDimension(); Point3D pt_index; pt_index.Fill(0); for (i = 0; i < dim; ++i) { pt_index[i] = index[i]; } return IsIndexInside(pt_index); } // ********************************* Image Geometry ******************************** //##Documentation //## @brief When switching from an Image Geometry to a normal Geometry (and the other way around), you have to //change // the origin as well (See Geometry Documentation)! This function will change the "isImageGeometry" bool flag and // changes the origin respectively. virtual void ChangeImageGeometryConsideringOriginOffset(const bool isAnImageGeometry); //##Documentation //## @brief Is this an ImageGeometry? //## //## For more information, see SetImageGeometry itkGetConstMacro(ImageGeometry, bool) //##Documentation //## @brief Define that this BaseGeometry is refering to an Image //## //## A geometry referring to an Image needs a slightly different //## definition of the position of the corners (see GetCornerPoint). //## The position of a voxel is defined by the position of its center. //## If we would use the origin (position of the (center of) the first //## voxel) as a corner and display this point, it would seem to be //## \em not at the corner but a bit within the image. Even worse for //## the opposite corner of the image: here the corner would appear //## outside the image (by half of the voxel diameter). Thus, we have //## to correct for this and to be able to do that, we need to know //## that the BaseGeometry is referring to an Image. itkSetMacro(ImageGeometry, bool); itkBooleanMacro(ImageGeometry); const GeometryTransformHolder *GetGeometryTransformHolder() const; protected: // ********************************** Constructor ********************************** BaseGeometry(); BaseGeometry(const BaseGeometry &other); ~BaseGeometry() override; - //##Documentation - //## @brief clones the geometry - //## - //## Overwrite in all sub-classes. - //## Normally looks like: - //## \code - //## Self::Pointer newGeometry = new Self(*this); - //## newGeometry->UnRegister(); - //## return newGeometry.GetPointer(); - //## \endcode itk::LightObject::Pointer InternalClone() const override = 0; void PrintSelf(std::ostream &os, itk::Indent indent) const override; static const std::string GetTransformAsString(TransformType *transformType); itkGetConstMacro(NDimensions, unsigned int); bool IsBoundingBoxNull() const; bool IsIndexToWorldTransformNull() const; void SetVtkMatrixDeepCopy(vtkTransform *vtktransform); void _SetSpacing(const mitk::Vector3D &aSpacing, bool enforceSetSpacing = false); //##Documentation //## @brief PreSetSpacing //## //## These virtual function allows a different beahiour in subclasses. //## Do implement them in every subclass of BaseGeometry. If not needed, use //## {Superclass::PreSetSpacing();}; virtual void PreSetSpacing(const mitk::Vector3D & /*aSpacing*/){}; //##Documentation //## @brief CheckBounds //## //## This function is called in SetBounds. Assertions can be implemented in this function (see PlaneGeometry.cpp). //## If you implement this function in a subclass, make sure, that all classes were your class inherits from //## have an implementation of CheckBounds //## (e.g. inheritance BaseGeometry <- A <- B. Implementation of CheckBounds in class B needs implementation in A as // well!) virtual void CheckBounds(const BoundsArrayType & /*bounds*/){}; //##Documentation //## @brief CheckIndexToWorldTransform //## //## This function is called in SetIndexToWorldTransform. Assertions can be implemented in this function (see // PlaneGeometry.cpp). //## In Subclasses of BaseGeometry, implement own conditions or call Superclass::CheckBounds(bounds);. virtual void CheckIndexToWorldTransform(mitk::AffineTransform3D * /*transform*/){}; private: GeometryTransformHolder *m_GeometryTransform; void InitializeGeometryTransformHolder(const BaseGeometry *otherGeometry); //##Documentation //## @brief Bounding Box, which is axes-parallel in intrinsic coordinates //## (often integer indices of pixels) BoundingBoxPointer m_BoundingBox; unsigned int m_FrameOfReferenceID; // mitk::TimeBounds m_TimeBounds; static const unsigned int m_NDimensions = 3; mutable TransformType::Pointer m_InvertedTransform; mutable unsigned long m_IndexToWorldTransformLastModified; bool m_ImageGeometry; //##Documentation //## @brief ModifiedLockFlag is used to prohibit the call of Modified() //## //## For the use of this Flag, see class ModifiedLock. This flag should only be set //## by the ModifiedLock class! bool m_ModifiedLockFlag; //##Documentation //## @brief ModifiedcalledFlag is used to collect calls of Modified(). //## //## For the use of this Flag, see class ModifiedLock. This flag should only be set //## by the Modified() function! mutable bool m_ModifiedCalledFlag; }; // ********************************** Equal Functions ********************************** // // Static compare functions mainly for testing // /** * @brief Equal A function comparing two geometries for beeing identical. * * @ingroup MITKTestingAPI * * The function compares the spacing, origin, axisvectors, extents, the matrix of the * IndexToWorldTransform (elementwise), the bounding (elementwise) and the ImageGeometry flag. * * The parameter eps is a tolarence value for all methods which are internally used for comparion. * If you want to use different tolerance values for different parts of the geometry, feel free to use * the other comparison methods and write your own implementation of Equal. * @param rightHandSide Compare this against leftHandSide. * @param leftHandSide Compare this against rightHandSide. * @param coordinateEps Tolerance for comparison of all spatial aspects (spacing, origin and grid alignment). * You can use mitk::eps in most cases. * @param directionEps Tolerance for comparison of all directional aspects (axis). You can use mitk::eps in most cases. * @param verbose Flag indicating if the user wants detailed console output or not. * @return True, if all comparison are true. False in any other case. */ MITKCORE_EXPORT bool Equal(const mitk::BaseGeometry& leftHandSide, const mitk::BaseGeometry& rightHandSide, ScalarType coordinateEps, ScalarType directionEps, bool verbose = false); /** * @brief Equal A function comparing two geometries for beeing identical. * * @ingroup MITKTestingAPI * * This is an overloaded version that uses a single tolerance for spatial and directional aspects. For more details, * see the other overloaded version. * * @param rightHandSide Compare this against leftHandSide. * @param leftHandSide Compare this against rightHandSide. * @param eps Tolarence for comparison. You can use mitk::eps in most cases. * @param verbose Flag indicating if the user wants detailed console output or not. * @return True, if all comparison are true. False in any other case. */ MITKCORE_EXPORT bool Equal(const mitk::BaseGeometry &leftHandSide, const mitk::BaseGeometry &rightHandSide, ScalarType eps = mitk::eps, bool verbose = false); /** * @brief Equal A function comparing two transforms (TransformType) for beeing identical. * * @ingroup MITKTestingAPI * * The function compares the IndexToWorldTransform (elementwise). * * The parameter eps is a tolarence value for all methods which are internally used for comparion. * @param rightHandSide Compare this against leftHandSide. * @param leftHandSide Compare this against rightHandSide. * @param eps Tolarence for comparison. You can use mitk::eps in most cases. * @param verbose Flag indicating if the user wants detailed console output or not. * @return True, if all comparison are true. False in any other case. */ MITKCORE_EXPORT bool Equal(const mitk::BaseGeometry::TransformType &leftHandSide, const mitk::BaseGeometry::TransformType &rightHandSide, ScalarType eps, bool verbose); /** * @brief Equal A function comparing two bounding boxes (BoundingBoxType) for beeing identical. * * @ingroup MITKTestingAPI * * The function compares the bounds (elementwise). * * The parameter eps is a tolarence value for all methods which are internally used for comparion. * @param rightHandSide Compare this against leftHandSide. * @param leftHandSide Compare this against rightHandSide. * @param eps Tolarence for comparison. You can use mitk::eps in most cases. * @param verbose Flag indicating if the user wants detailed console output or not. * @return True, if all comparison are true. False in any other case. */ MITKCORE_EXPORT bool Equal(const mitk::BaseGeometry::BoundingBoxType &leftHandSide, const mitk::BaseGeometry::BoundingBoxType &rightHandSide, ScalarType eps, bool verbose); /** * @brief A function checks if a test geometry is a sub geometry of * a given reference geometry. * * Sub geometry means that both geometries have the same voxel grid (same spacing, same axes, * orgin is on voxel grid), but the bounding box of the checked geometry is contained or equal * to the bounding box of the reference geometry.\n * By this definition equal geometries are always sub geometries of each other. * * The function checks the spacing, origin, axis vectors, extents, the matrix of the * IndexToWorldTransform (elementwise), the bounding (elementwise) and the ImageGeometry flag. * * The parameter eps is a tolerance value for all methods which are internally used for comparison. * @param testGeo Geometry that should be checked if it is a sub geometry of referenceGeo. * @param referenceGeo Geometry that should contain testedGeometry as sub geometry. * @param coordinateEps Tolerance for comparison of all spatial aspects (spacing, origin and grid alignment). * You can use mitk::eps in most cases. * @param directionEps Tolerance for comparison of all directional aspects (axis). You can use mitk::eps in most cases. * @param verbose Flag indicating if the user wants detailed console output or not. * @return True, if all comparisons are true. False otherwise. */ MITKCORE_EXPORT bool IsSubGeometry(const mitk::BaseGeometry& testGeo, const mitk::BaseGeometry& referenceGeo, ScalarType coordinateEps, ScalarType directionEps, bool verbose = false); /** * @brief A function checks if a test geometry is a sub geometry of * a given reference geometry. * * This is a overloaded version that uses a single tolerance for spatial and directional aspects. For more details, * see the other overloaded version. * * @param testGeo Geometry that should be checked if it is a sub geometry of referenceGeo. * @param referenceGeo Geometry that should contain testedGeometry as sub geometry. * @param eps Tolarence for comparison (both spatial and directional). You can use mitk::eps in most cases. * @param verbose Flag indicating if the user wants detailed console output or not. * @return True, if all comparison are true. False otherwise. */ MITKCORE_EXPORT bool IsSubGeometry(const mitk::BaseGeometry& testGeo, const mitk::BaseGeometry& referenceGeo, ScalarType eps = mitk::eps, bool verbose = false); } // namespace mitk #endif /* BaseGeometry_H_HEADER_INCLUDED */ diff --git a/Modules/Core/include/mitkBaseRenderer.h b/Modules/Core/include/mitkBaseRenderer.h index 5b14a4ec2d..b50a10e5c1 100644 --- a/Modules/Core/include/mitkBaseRenderer.h +++ b/Modules/Core/include/mitkBaseRenderer.h @@ -1,532 +1,532 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BASERENDERER_H_HEADER_INCLUDED_C1CCA0F4 #define BASERENDERER_H_HEADER_INCLUDED_C1CCA0F4 #include "mitkCameraRotationController.h" #include "mitkDataStorage.h" #include "mitkPlaneGeometry.h" #include "mitkPlaneGeometryData.h" #include "mitkSliceNavigationController.h" #include "mitkTimeGeometry.h" #include "mitkBindDispatcherInteractor.h" #include "mitkDispatcher.h" #include #include #include #include // DEPRECATED #include namespace mitk { class NavigationController; class SliceNavigationController; class CameraRotationController; class CameraController; class DataStorage; class Mapper; class BaseLocalStorageHandler; class KeyEvent; //##Documentation //## @brief Organizes the rendering process //## //## Organizes the rendering process. A Renderer contains a reference to a //## DataStorage and asks the mappers of the data objects to render //## the data into the renderwindow it is associated to. //## //## \#Render() checks if rendering is currently allowed by calling //## RenderWindow::PrepareRendering(). Initialization of a rendering context //## can also be performed in this method. //## //## The actual rendering code has been moved to \#Repaint() //## Both \#Repaint() and \#Update() are declared protected now. //## //## Note: Separation of the Repaint and Update processes (rendering vs //## creating a vtk prop tree) still needs to be worked on. The whole //## rendering process also should be reworked to use VTK based classes for //## both 2D and 3D rendering. //## @ingroup Renderer class MITKCORE_EXPORT BaseRenderer : public itk::Object { public: typedef std::map BaseRendererMapType; static BaseRendererMapType baseRendererMap; static BaseRenderer *GetInstance(vtkRenderWindow *renWin); static void AddInstance(vtkRenderWindow *renWin, BaseRenderer *baseRenderer); static void RemoveInstance(vtkRenderWindow *renWin); static BaseRenderer *GetByName(const std::string &name); static vtkRenderWindow *GetRenderWindowByName(const std::string &name); #pragma GCC visibility push(default) itkEventMacro(RendererResetEvent, itk::AnyEvent); #pragma GCC visibility pop /** Standard class typedefs. */ mitkClassMacroItkParent(BaseRenderer, itk::Object); BaseRenderer(const char *name = nullptr, vtkRenderWindow *renWin = nullptr); //##Documentation //## @brief MapperSlotId defines which kind of mapper (e.g. 2D or 3D) should be used. typedef int MapperSlotId; enum StandardMapperSlot { Standard2D = 1, Standard3D = 2 }; //##Documentation //## @brief Possible view directions for render windows. enum class ViewDirection { AXIAL = 0, SAGITTAL, CORONAL, THREE_D }; virtual void SetDataStorage(DataStorage *storage); ///< set the datastorage that will be used for rendering //##Documentation //## return the DataStorage that is used for rendering virtual DataStorage::Pointer GetDataStorage() const { return m_DataStorage.GetPointer(); } //##Documentation //## @brief Access the RenderWindow into which this renderer renders. vtkRenderWindow *GetRenderWindow() const { return m_RenderWindow; } vtkRenderer *GetVtkRenderer() const { return m_VtkRenderer; } //##Documentation //## @brief Returns the Dispatcher which handles Events for this BaseRenderer Dispatcher::Pointer GetDispatcher() const; //##Documentation //## @brief Default mapper id to use. static const MapperSlotId defaultMapper; //##Documentation //## @brief Do the rendering and flush the result. virtual void Paint(); //##Documentation //## @brief Initialize the RenderWindow. Should only be called from RenderWindow. virtual void Initialize(); //##Documentation //## @brief Called to inform the renderer that the RenderWindow has been resized. virtual void Resize(int w, int h); //##Documentation //## @brief Initialize the renderer with a RenderWindow (@a renderwindow). virtual void InitRenderer(vtkRenderWindow *renderwindow); //##Documentation //## @brief Set the initial size. Called by RenderWindow after it has become //## visible for the first time. virtual void InitSize(int w, int h); //##Documentation //## @brief Draws a point on the widget. //## Should be used during conferences to show the position of the remote mouse virtual void DrawOverlayMouse(Point2D &p2d); //##Documentation //## @brief Set/Get the WorldGeometry (m_WorldGeometry) for 3D and 2D rendering, that describing the //## (maximal) area to be rendered. //## //## Depending of the type of the passed BaseGeometry more or less information can be extracted: //## \li if it is a PlaneGeometry (which is a sub-class of BaseGeometry), m_CurrentWorldPlaneGeometry is //## also set to point to it. m_WorldTimeGeometry is set to nullptr. //## \li if it is a TimeGeometry, m_WorldTimeGeometry is also set to point to it. //## If m_WorldTimeGeometry contains instances of SlicedGeometry3D, m_CurrentWorldPlaneGeometry is set to //## one of geometries stored in the SlicedGeometry3D according to the value of m_Slice; otherwise //## a PlaneGeometry describing the top of the bounding-box of the BaseGeometry is set as the //## m_CurrentWorldPlaneGeometry. //## \li otherwise a PlaneGeometry describing the top of the bounding-box of the BaseGeometry //## is set as the m_CurrentWorldPlaneGeometry. m_WorldTimeGeometry is set to nullptr. //## @todo add calculation of PlaneGeometry describing the top of the bounding-box of the BaseGeometry //## when the passed BaseGeometry is not sliced. //## \sa m_WorldGeometry //## \sa m_WorldTimeGeometry //## \sa m_CurrentWorldPlaneGeometry virtual void SetWorldGeometry3D(const BaseGeometry *geometry); virtual void SetWorldTimeGeometry(const mitk::TimeGeometry *geometry); /** * \deprecatedSince{2013_09} Please use TimeGeometry instead of TimeSlicedGeometry. For more information see * http://www.mitk.org/Development/Refactoring%20of%20the%20Geometry%20Classes%20-%20Part%201 */ DEPRECATED(void SetWorldGeometry3D(TimeSlicedGeometry *geometry)); itkGetConstObjectMacro(WorldTimeGeometry, TimeGeometry); //##Documentation //## @brief Get the current 3D-worldgeometry (m_CurrentWorldGeometry) used for 3D-rendering itkGetConstObjectMacro(CurrentWorldGeometry, BaseGeometry); //##Documentation //## @brief Get the current 2D-worldgeometry (m_CurrentWorldPlaneGeometry) used for 2D-rendering itkGetConstObjectMacro(CurrentWorldPlaneGeometry, PlaneGeometry) /** * \deprecatedSince{2014_10} Please use GetCurrentWorldPlaneGeometry */ DEPRECATED(const PlaneGeometry *GetCurrentWorldGeometry2D()) { return GetCurrentWorldPlaneGeometry(); }; //##Documentation //## Calculates the bounds of the DataStorage (if it contains any valid data), //## creates a geometry from these bounds and sets it as world geometry of the renderer. //## //## Call this method to re-initialize the renderer to the current DataStorage //## (e.g. after loading an additional dataset), to ensure that the view is //## aligned correctly. - //## \warn This is not implemented yet. + //## \warning This is not implemented yet. virtual bool SetWorldGeometryToDataStorageBounds() { return false; } //##Documentation //## @brief Set/Get m_Slice which defines together with m_TimeStep the 2D geometry //## stored in m_WorldTimeGeometry used as m_CurrentWorldPlaneGeometry //## //## \sa m_Slice virtual void SetSlice(unsigned int slice); itkGetConstMacro(Slice, unsigned int); //##Documentation //## @brief Set/Get m_TimeStep which defines together with m_Slice the 2D geometry //## stored in m_WorldTimeGeometry used as m_CurrentWorldPlaneGeometry //## //## \sa m_TimeStep virtual void SetTimeStep(unsigned int timeStep); itkGetConstMacro(TimeStep, unsigned int); //##Documentation //## @brief Get the time-step of a BaseData object which //## exists at the time of the currently displayed content //## //## Returns -1 or mitk::BaseData::m_TimeSteps if there //## is no data at the current time. //## \sa GetTimeStep, m_TimeStep int GetTimeStep(const BaseData *data) const; //##Documentation //## @brief Get the time in ms of the currently displayed content //## //## \sa GetTimeStep, m_TimeStep ScalarType GetTime() const; //##Documentation //## @brief SetWorldGeometry is called according to the geometrySliceEvent, //## which is supposed to be a SliceNavigationController::GeometrySendEvent virtual void SetGeometry(const itk::EventObject &geometrySliceEvent); //##Documentation //## @brief UpdateWorldGeometry is called to re-read the 2D geometry from the //## slice navigation controller virtual void UpdateGeometry(const itk::EventObject &geometrySliceEvent); //##Documentation //## @brief SetSlice is called according to the geometrySliceEvent, //## which is supposed to be a SliceNavigationController::GeometrySliceEvent virtual void SetGeometrySlice(const itk::EventObject &geometrySliceEvent); //##Documentation //## @brief SetTimeStep is called according to the geometrySliceEvent, //## which is supposed to be a SliceNavigationController::GeometryTimeEvent virtual void SetGeometryTime(const itk::EventObject &geometryTimeEvent); //##Documentation //## @brief Get a DataNode pointing to a data object containing the current 2D-worldgeometry // m_CurrentWorldPlaneGeometry (for 2D rendering) itkGetObjectMacro(CurrentWorldPlaneGeometryNode, DataNode) /** * \deprecatedSince{2014_10} Please use GetCurrentWorldPlaneGeometryNode */ DEPRECATED(DataNode *GetCurrentWorldGeometry2DNode()) { return GetCurrentWorldPlaneGeometryNode(); }; //##Documentation //## @brief Sets timestamp of CurrentWorldPlaneGeometry and forces so reslicing in that renderwindow void SendUpdateSlice(); //##Documentation //## @brief Get timestamp of last call of SetCurrentWorldPlaneGeometry unsigned long GetCurrentWorldPlaneGeometryUpdateTime() { return m_CurrentWorldPlaneGeometryUpdateTime; } /** * \deprecatedSince{2014_10} Please use GetCurrentWorldPlaneGeometryUpdateTime */ DEPRECATED(unsigned long GetCurrentWorldGeometry2DUpdateTime()) { return GetCurrentWorldPlaneGeometryUpdateTime(); }; //##Documentation //## @brief Get timestamp of last change of current TimeStep unsigned long GetTimeStepUpdateTime() { return m_TimeStepUpdateTime; } //##Documentation //## @brief Perform a picking: find the x,y,z world coordinate of a //## display x,y coordinate. //## @warning Has to be overwritten in subclasses for the 3D-case. //## //## Implemented here only for 2D-rendering virtual void PickWorldPoint(const Point2D &diplayPosition, Point3D &worldPosition) const = 0; /** \brief Determines the object (mitk::DataNode) closest to the current * position by means of picking * * \warning Implementation currently empty for 2D rendering; intended to be * implemented for 3D renderers */ virtual DataNode *PickObject(const Point2D & /*displayPosition*/, Point3D & /*worldPosition*/) const { return nullptr; } //##Documentation //## @brief Get the MapperSlotId to use. itkGetMacro(MapperID, MapperSlotId); itkGetConstMacro(MapperID, MapperSlotId); //##Documentation //## @brief Set the MapperSlotId to use. virtual void SetMapperID(MapperSlotId id); virtual int *GetSize() const; virtual int *GetViewportSize() const; void SetSliceNavigationController(SliceNavigationController *SlicenavigationController); itkGetObjectMacro(CameraController, CameraController); itkGetObjectMacro(SliceNavigationController, SliceNavigationController); itkGetObjectMacro(CameraRotationController, CameraRotationController); itkGetMacro(EmptyWorldGeometry, bool); //##Documentation //## @brief Tells if the displayed region is shifted and rescaled if the render window is resized. itkGetMacro(KeepDisplayedRegion, bool) //##Documentation //## @brief Tells if the displayed region should be shifted and rescaled if the render window is resized. itkSetMacro(KeepDisplayedRegion, bool); //##Documentation //## @brief get the name of the Renderer //## @note const char *GetName() const { return m_Name.c_str(); } //##Documentation //## @brief get the x_size of the RendererWindow //## @note int GetSizeX() const { return GetSize()[0]; } //##Documentation //## @brief get the y_size of the RendererWindow //## @note int GetSizeY() const { return GetSize()[1]; } const double *GetBounds() const; void RequestUpdate(); void ForceImmediateUpdate(); /** Returns number of mappers which are visible and have level-of-detail * rendering enabled */ unsigned int GetNumberOfVisibleLODEnabledMappers() const; //##Documentation //## @brief This method converts a display point to the 3D world index //## using the geometry of the renderWindow. void DisplayToWorld(const Point2D &displayPoint, Point3D &worldIndex) const; //##Documentation //## @brief This method converts a display point to the 2D world index, mapped onto the display plane //## using the geometry of the renderWindow. void DisplayToPlane(const Point2D &displayPoint, Point2D &planePointInMM) const; //##Documentation //## @brief This method converts a 3D world index to the display point //## using the geometry of the renderWindow. void WorldToDisplay(const Point3D &worldIndex, Point2D &displayPoint) const; //##Documentation //## @brief This method converts a 3D world index to the point on the viewport //## using the geometry of the renderWindow. void WorldToView(const Point3D &worldIndex, Point2D &viewPoint) const; //##Documentation //## @brief This method converts a 2D plane coordinate to the display point //## using the geometry of the renderWindow. void PlaneToDisplay(const Point2D &planePointInMM, Point2D &displayPoint) const; //##Documentation //## @brief This method converts a 2D plane coordinate to the point on the viewport //## using the geometry of the renderWindow. void PlaneToView(const Point2D &planePointInMM, Point2D &viewPoint) const; double GetScaleFactorMMPerDisplayUnit() const; Point2D GetDisplaySizeInMM() const; Point2D GetViewportSizeInMM() const; Point2D GetOriginInMM() const; itkGetConstMacro(ConstrainZoomingAndPanning, bool) virtual void SetConstrainZoomingAndPanning(bool constrain); /** * \brief Provides (1) world coordinates for a given mouse position and (2) * translates mousePosition to Display coordinates * \deprecated Map2DRendererPositionTo3DWorldPosition is deprecated. Please use DisplayToWorld instead. */ DEPRECATED(virtual Point3D Map2DRendererPositionTo3DWorldPosition(const Point2D &mousePosition) const); protected: ~BaseRenderer() override; //##Documentation //## @brief Call update of all mappers. To be implemented in subclasses. virtual void Update() = 0; vtkRenderWindow *m_RenderWindow; vtkRenderer *m_VtkRenderer; //##Documentation //## @brief MapperSlotId to use. Defines which kind of mapper (e.g., 2D or 3D) shoud be used. MapperSlotId m_MapperID; //##Documentation //## @brief The DataStorage that is used for rendering. DataStorage::Pointer m_DataStorage; //##Documentation //## @brief Timestamp of last call of Update(). unsigned long m_LastUpdateTime; //##Documentation //## @brief CameraController for 3D rendering //## @note preliminary. itk::SmartPointer m_CameraController; SliceNavigationController::Pointer m_SliceNavigationController; CameraRotationController::Pointer m_CameraRotationController; //##Documentation //## @brief Sets m_CurrentWorldPlaneGeometry virtual void SetCurrentWorldPlaneGeometry(const PlaneGeometry *geometry2d); /** * \deprecatedSince{2014_10} Please use SetCurrentWorldPlaneGeometry */ DEPRECATED(void SetCurrentWorldGeometry2D(PlaneGeometry *geometry2d)) { SetCurrentWorldPlaneGeometry(geometry2d); }; //##Documentation //## @brief Sets m_CurrentWorldGeometry virtual void SetCurrentWorldGeometry(const BaseGeometry *geometry); private: //##Documentation //## m_WorldTimeGeometry is set by SetWorldGeometry if the passed BaseGeometry is a //## TimeGeometry (or a sub-class of it). If it contains instances of SlicedGeometry3D, //## m_Slice and m_TimeStep (set via SetSlice and SetTimeStep, respectively) define //## which 2D geometry stored in m_WorldTimeGeometry (if available) //## is used as m_CurrentWorldPlaneGeometry. //## \sa m_CurrentWorldPlaneGeometry TimeGeometry::ConstPointer m_WorldTimeGeometry; //##Documentation //## Pointer to the current 3D-worldgeometry. BaseGeometry::ConstPointer m_CurrentWorldGeometry; //##Documentation //## Pointer to the current 2D-worldgeometry. The 2D-worldgeometry //## describes the maximal area (2D manifold) to be rendered in case we //## are doing 2D-rendering. //## It is const, since we are not allowed to change it (it may be taken //## directly from the geometry of an image-slice and thus it would be //## very strange when suddenly the image-slice changes its geometry). PlaneGeometry::Pointer m_CurrentWorldPlaneGeometry; //##Documentation //## Defines together with m_Slice which 2D geometry stored in m_WorldTimeGeometry //## is used as m_CurrentWorldPlaneGeometry: m_WorldTimeGeometry->GetPlaneGeometry(m_Slice, m_TimeStep). //## \sa m_WorldTimeGeometry unsigned int m_Slice; //##Documentation //## Defines together with m_TimeStep which 2D geometry stored in m_WorldTimeGeometry //## is used as m_CurrentWorldPlaneGeometry: m_WorldTimeGeometry->GetPlaneGeometry(m_Slice, m_TimeStep). //## \sa m_WorldTimeGeometry unsigned int m_TimeStep; //##Documentation //## @brief timestamp of last call of SetWorldGeometry itk::TimeStamp m_CurrentWorldPlaneGeometryUpdateTime; //##Documentation //## @brief timestamp of last change of the current time step itk::TimeStamp m_TimeStepUpdateTime; //##Documentation //## @brief Helper class which establishes connection between Interactors and Dispatcher via a common DataStorage. BindDispatcherInteractor *m_BindDispatcherInteractor; //##Documentation //## @brief Tells if the displayed region should be shifted or rescaled if the render window is resized. bool m_KeepDisplayedRegion; protected: void PrintSelf(std::ostream &os, itk::Indent indent) const override; //##Documentation //## Data object containing the m_CurrentWorldPlaneGeometry defined above. PlaneGeometryData::Pointer m_CurrentWorldPlaneGeometryData; //##Documentation //## DataNode objects containing the m_CurrentWorldPlaneGeometryData defined above. DataNode::Pointer m_CurrentWorldPlaneGeometryNode; //##Documentation //## @brief test only unsigned long m_CurrentWorldPlaneGeometryTransformTime; std::string m_Name; double m_Bounds[6]; bool m_EmptyWorldGeometry; typedef std::set LODEnabledMappersType; /** Number of mappers which are visible and have level-of-detail * rendering enabled */ unsigned int m_NumberOfVisibleLODEnabledMappers; // Local Storage Handling for mappers protected: std::list m_RegisteredLocalStorageHandlers; bool m_ConstrainZoomingAndPanning; public: void RemoveAllLocalStorages(); void RegisterLocalStorageHandler(mitk::BaseLocalStorageHandler *lsh); void UnregisterLocalStorageHandler(mitk::BaseLocalStorageHandler *lsh); }; } // namespace mitk #endif /* BASERENDERER_H_HEADER_INCLUDED_C1CCA0F4 */ diff --git a/Modules/Core/include/mitkLevelWindow.h b/Modules/Core/include/mitkLevelWindow.h index 9907b6af08..538fe6e56c 100644 --- a/Modules/Core/include/mitkLevelWindow.h +++ b/Modules/Core/include/mitkLevelWindow.h @@ -1,263 +1,263 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef LEVELWINDOW_H_HEADER_INCLUDED_C1F4F02C #define LEVELWINDOW_H_HEADER_INCLUDED_C1F4F02C #include "mitkNumericTypes.h" #include namespace mitk { class Image; /** * @brief The LevelWindow class Class to store level/window values. * * Current min and max value are stored in m_LowerWindowBound and m_UpperWindowBound. * m_DefaultLevel amd m_DefaultWindow store the initial Level/Window values for the image. * m_DefaultRangeMin and m_DefaultRangeMax store the initial minrange and maxrange for the image. * * The finite maximum and minimum of valid value range is stored in m_RangeMin and m_RangeMax. * If deduced from an image by default the minimum or maximum of it statistics is used. If one * of these values are infinite the 2nd extrimum (which is guaranteed to be finite), will be used. * * See documentation of SetAuto for information on how the level window is initialized from an image. * * @ingroup DataManagement * * @note If you want to apply the mitk::LevelWindow to an mitk::Image, make sure * to use the mitk::LevelWindowProperty and set the mitk::RenderingModeProperty * to a mode which supports level window (e.g. LEVELWINDOW_COLOR). * Make sure to check the documentation of the mitk::RenderingModeProperty. For a * code example how to use the mitk::LevelWindowProperty check the - * mitkImageVtkMapper2DLevelWindowTest.cpp in Core\Code\Testing. + * mitkImageVtkMapper2DLevelWindowTest.cpp in Core/Code/Testing. */ class MITKCORE_EXPORT LevelWindow { public: LevelWindow(ScalarType level = 127.5, ScalarType window = 255.0); LevelWindow(const mitk::LevelWindow &levWin); virtual ~LevelWindow(); /*! * \brief method that returns the level value, i.e. the center of * the current grey value interval */ ScalarType GetLevel() const; /*! * \brief returns the current window size, i.e the range size of the current grey value interval */ ScalarType GetWindow() const; /*! * \brief method returns the default level value for the image */ ScalarType GetDefaultLevel() const; /*! * \brief returns the default window size for the image */ ScalarType GetDefaultWindow() const; /*! * \brief Resets the level and the window value to the default values */ void ResetDefaultLevelWindow(); /*! * Returns the minimum Value of the window */ ScalarType GetLowerWindowBound() const; /*! * Returns the upper window bound value of the window */ ScalarType GetUpperWindowBound() const; /*! * To set the level and the window value */ void SetLevelWindow(ScalarType level, ScalarType window, bool expandRangesIfNecessary = true); /*! * Set the lower and upper bound of the window */ void SetWindowBounds(ScalarType lowerBound, ScalarType upperBound, bool expandRangesIfNecessary = true); /*! * sets the window to its maximum Size in scaleRange */ void SetToMaxWindowSize(); /*! * Set the range minimum and maximum value */ void SetRangeMinMax(ScalarType min, ScalarType max); /*! * Get the range minimum value */ ScalarType GetRangeMin() const; /*! * Get the range maximum value */ ScalarType GetRangeMax() const; /*! * Get the default range minimum value */ ScalarType GetDefaultLowerBound() const; /*! * Get the default range maximum value */ ScalarType GetDefaultUpperBound() const; /*! * \brief the default min and max range for image will be reset */ void ResetDefaultRangeMinMax(); /**! * \brief returns the size of the grey value range */ ScalarType GetRange() const; /*! * set the default level and window value */ void SetDefaultLevelWindow(ScalarType level, ScalarType window); /*! * set the default Bounderies */ void SetDefaultBoundaries(ScalarType low, ScalarType up); /**! * \brief sets level/window to optimize the contrast of the given Image */ void SetAuto(const Image *image, bool tryPicTags = true, bool guessByCentralSlice = true, unsigned selectedComponent = 0); /**! * \brief sets level/window to the min/max greyvalues of the given Image */ void SetToImageRange(const Image *image); /** * If a level window is set to fixed, the set and get methods won't accept * modifications to the level window settings anymore. This behaviour can * be turned of by setting fixed to false; */ void SetFixed(bool fixed); /** * Returns whether the level window settings are fixed (@see SetFixed(bool)) or not */ bool GetFixed() const; /** * Returns whether the level window settings are fixed (@see SetFixed(bool)) or not */ bool IsFixed() const; /*! * \brief equality operator implementation that allows to compare two level windows */ virtual bool operator==(const LevelWindow &levWin) const; /*! * \brief non equality operator implementation that allows to compare two level windows */ virtual bool operator!=(const LevelWindow &levWin) const; /*! * \brief implementation necessary because operator made * private in itk::Object */ virtual LevelWindow &operator=(const LevelWindow &levWin); /*! * \brief Shows if floating values are accepted */ bool IsFloatingValues() const; /*! * \brief Sets the floating image value */ void SetFloatingValues(bool value); protected: /*! * lower bound of current window */ ScalarType m_LowerWindowBound; /*! * upper bound of current window */ ScalarType m_UpperWindowBound; /*! * minimum gray value of the window */ ScalarType m_RangeMin; /*! * maximum gray value of the window */ ScalarType m_RangeMax; /*! * default minimum gray value of the window */ ScalarType m_DefaultLowerBound; /*! * default maximum gray value of the window */ ScalarType m_DefaultUpperBound; /*! * Image with floating values */ bool m_IsFloatingImage; /*! * Defines whether the level window settings may be changed after * initialization or not. */ bool m_Fixed; /*! * confidence tests * * if m_LowerWindowBound > m_UpperWindowBound, then the values for m_LowerWindowBound and m_UpperWindowBound will be * exchanged * * if m_LowerWindowBound < m_RangeMin, m_LowerWindowBound will be set to m_RangeMin. m_UpperWindowBound will be * decreased the same as m_LowerWindowBound will be increased, but minimum value for m_UpperWindowBound is also * m_RangeMin. * * if m_UpperWindowBound > m_RangeMax, m_UpperWindowBound will be set to m_RangeMax. m_LowerWindowBound will be * increased the same as m_UpperWindowBound will be decreased, but maximum value for m_LowerWindowBound is also * m_RangeMax. * */ inline void EnsureConsistency(); }; } // namespace mitk #endif /* LEVELWINDOW_H_HEADER_INCLUDED_C1F4F02C */ diff --git a/Modules/Core/include/mitkLevelWindowProperty.h b/Modules/Core/include/mitkLevelWindowProperty.h index 8fcf60c804..0faaec8b3b 100755 --- a/Modules/Core/include/mitkLevelWindowProperty.h +++ b/Modules/Core/include/mitkLevelWindowProperty.h @@ -1,85 +1,85 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKLEVELWINDOWPROPERTY_H_HEADER_INCLUDED_C10EEAA8 #define MITKLEVELWINDOWPROPERTY_H_HEADER_INCLUDED_C10EEAA8 #include "mitkBaseProperty.h" #include "mitkLevelWindow.h" namespace mitk { #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4522) #endif /** * @brief The LevelWindowProperty class Property for the mitk::LevelWindow * * @ingroup DataManagement * * @note If you want to apply the mitk::LevelWindowProperty to an mitk::Image, * make sure to set the mitk::RenderingModeProperty to a mode which supports * level window (e.g. LEVELWINDOW_COLOR). Make sure to check the documentation * of the mitk::RenderingModeProperty. For a code example how to use the * mitk::LevelWindowProperty check the mitkImageVtkMapper2DLevelWindowTest.cpp - * in Core\Code\Testing. + * in Core/Code/Testing. */ class MITKCORE_EXPORT LevelWindowProperty : public BaseProperty { protected: LevelWindow m_LevWin; LevelWindowProperty(); LevelWindowProperty(const LevelWindowProperty &other); LevelWindowProperty(const mitk::LevelWindow &levWin); public: mitkClassMacro(LevelWindowProperty, BaseProperty); itkFactorylessNewMacro(Self); itkCloneMacro(Self) mitkNewMacro1Param(LevelWindowProperty, const mitk::LevelWindow &); typedef LevelWindow ValueType; ~LevelWindowProperty() override; const mitk::LevelWindow &GetLevelWindow() const; const mitk::LevelWindow &GetValue() const; void SetLevelWindow(const LevelWindow &levWin); void SetValue(const ValueType &levWin); std::string GetValueAsString() const override; using BaseProperty::operator=; private: // purposely not implemented LevelWindowProperty &operator=(const LevelWindowProperty &); itk::LightObject::Pointer InternalClone() const override; bool IsEqual(const BaseProperty &property) const override; bool Assign(const BaseProperty &property) override; }; #ifdef _MSC_VER #pragma warning(pop) #endif } // namespace mitk #endif /* MITKLEVELWINDOWPROPERTY_H_HEADER_INCLUDED_C10EEAA8 */ diff --git a/Modules/Core/include/mitkLookupTable.h b/Modules/Core/include/mitkLookupTable.h index ef88aba897..5ab7de7dba 100644 --- a/Modules/Core/include/mitkLookupTable.h +++ b/Modules/Core/include/mitkLookupTable.h @@ -1,274 +1,274 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkLookupTable_h #define mitkLookupTable_h #include "mitkCommon.h" #include #include #include #include #include class vtkColorTransferFunction; class vtkPiecewiseFunction; namespace mitk { /** * @brief The LookupTable class mitk wrapper for a vtkLookupTable * @ingroup DataManagement * * This class can be used to color images with a LookupTable, such as the * vtkLookupTable. * @note If you want to use this as a property for an mitk::Image, make sure * to use the mitk::LookupTableProperty and set the mitk::RenderingModeProperty * to a mode which supports lookup tables (e.g. LOOKUPTABLE_COLOR). Make * sure to check the documentation of the mitk::RenderingModeProperty. For a * code example how to use the mitk::LookupTable check the - * mitkImageVtkMapper2DLookupTableTest.cpp in Core\Code\Testing. + * mitkImageVtkMapper2DLookupTableTest.cpp in Core/Code/Testing. */ class MITKCORE_EXPORT LookupTable : public itk::DataObject { public: /** * @brief RawLookupTableType raw lookuptable typedef for convenience. */ typedef unsigned char RawLookupTableType; mitkClassMacroItkParent(LookupTable, itk::DataObject); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** * @brief GetVtkLookupTable Getter for the internally wrapped vtkLookupTable. */ virtual vtkSmartPointer GetVtkLookupTable() const; /** * @brief GetRawLookupTable Getter for the raw lookuptable array. */ virtual RawLookupTableType *GetRawLookupTable() const; /** * @brief SetVtkLookupTable Setter for the internal lookuptable. * @param lut The lookuptable. */ virtual void SetVtkLookupTable(vtkSmartPointer lut); /** * @brief ChangeOpacityForAll Set the opacity for all table values. * @param opacity Opacity between 0.0 and 1.0. */ virtual void ChangeOpacityForAll(float opacity); /** * @brief ChangeOpacity Set the opacity for a specific table index. * @param index The lookuptable index. * @param opacity Opacity between 0.0 and 1.0. */ virtual void ChangeOpacity(int index, float opacity); /** * @brief GetColor convenience method wrapping the vtkLookupTable::GetColor() method. * * Map one value through the lookup table and return the color as an RGB array of doubles between 0 and 1. * @param value The value you want to map. * @param rgb RGB values between 0 and 1. */ virtual void GetColor(double value, double rgb[3]); /** * @brief GetTableValue convenience method wrapping the vtkLookupTable::GetTableValue() method. * @param index The index you want to get. * @param rgba RGB values between 0 and 1. */ virtual void GetTableValue(int index, double rgba[4]); /** * @brief SetTableValue convenience method wrapping the vtkLookupTable::SetTableValue() method. * @param index The index you want to set. * @param rgba RGB values between 0 and 1. */ virtual void SetTableValue(int index, double rgba[4]); itkSetMacro(Window, float); itkSetMacro(Level, float); itkSetMacro(Opacity, float); /** * @brief equality operator implementation */ virtual bool operator==(const mitk::LookupTable &LookupTable) const; /** * @brief non equality operator implementation */ virtual bool operator!=(const LookupTable &LookupTable) const; /** * @brief implementation necessary because operator made * private in itk::Object */ virtual LookupTable &operator=(const LookupTable &LookupTable); /** * @brief Updates the output information of the current object by calling * updateOutputInformation of the data objects source object. */ void UpdateOutputInformation() override; /** * @brief Sets the requested Region to the largest possible region. * This method is not implemented, since this is the default * behavior of the itk pipeline and we do not support the * requested-region mechanism for lookup-tables */ void SetRequestedRegionToLargestPossibleRegion() override; /** * @brief Checks, if the requested region lies outside of the buffered region by * calling verifyRequestedRegion(). */ bool RequestedRegionIsOutsideOfTheBufferedRegion() override; /** * @brief Checks if the requested region is completely contained in * the buffered region. Since we always want to process the lookup * table as a whole, this method always returns true */ bool VerifyRequestedRegion() override; /** * @brief This method has no effect for lookup tables, since we do * not support the region-mechanism */ void SetRequestedRegion(const itk::DataObject *data) override; LookupTable(); ~LookupTable() override; /** * \deprecatedSince{2014_03} Please use CreateColorTransferFunction() instead */ DEPRECATED(void CreateColorTransferFunction(vtkColorTransferFunction *&colorFunction)); /** * \deprecatedSince{2014_03} Please use CreateOpacityTransferFunction() instead */ DEPRECATED(void CreateOpacityTransferFunction(vtkPiecewiseFunction *&opacityFunction)); /** * \deprecatedSince{2014_03} Please use CreateGradientTransferFunction() instead */ DEPRECATED(void CreateGradientTransferFunction(vtkPiecewiseFunction *&gradientFunction)); vtkSmartPointer CreateColorTransferFunction(); vtkSmartPointer CreateOpacityTransferFunction(); vtkSmartPointer CreateGradientTransferFunction(); /** * @brief The LookupTableType enum for different predefined lookup tables. * * \li GRAYSCALE Our default level-window (sometimes referred to as window-level by other sources) setup for a test * image looks like this: * \image html ExampleLevelWindowColor.png * \li INVERSE_GRAYSCALE Inverse LookupTable of GRAYSCALE. * \li HOT_IRON A LookupTable for red colors. * \li JET A LookupTable for JET color rendering. * \li LEGACY_BINARY A LookupTable for binary images. * \li LEGACY_RAINBOW_COLOR A rainbow-like LookupTable. * \li MULTILABEL A LookupTable for multilabel images. * \li PET_COLOR A LookupTable for PET color rendering. * \li PET_20 A LookupTable for PET_20 color rendering. * * The different LookupTableTypes can be applied in the MitkWorkbench via right-clicking * on an image and choosing a color map. */ enum LookupTableType { GRAYSCALE, INVERSE_GRAYSCALE, HOT_IRON, JET, JET_TRANSPARENT, PLASMA, INFERNO, VIRIDIS, MAGMA, LEGACY_BINARY, LEGACY_RAINBOW_COLOR, MULTILABEL, PET_COLOR, PET_20 }; static std::vector typenameList; /** * @brief Set the look-up table type by enum (or integer). * @details Returns if the given type doesn't exist. Only changes the type if it is different * from the current one. */ virtual void SetType(const LookupTableType type); /** * @brief Set the look-up table type by string. * @details Returns if the given type doesn't exist. Only changes the type if it is different * from the current one. */ virtual void SetType(const std::string &typeName); /** * @brief Return the current look-up table type. */ virtual LookupTableType GetActiveType() const; /** * @brief Return the current look-up table type as a string. */ virtual std::string GetActiveTypeAsString() const; protected: void PrintSelf(std::ostream &os, itk::Indent indent) const override; LookupTable(const LookupTable &other); virtual void BuildGrayScaleLookupTable(); virtual void BuildLegacyBinaryLookupTable(); virtual void BuildLegacyRainbowColorLookupTable(); virtual void BuildInverseGrayScaleLookupTable(); virtual void BuildHotIronLookupTable(); virtual void BuildPlasmaLookupTable(); virtual void BuildInfernoLookupTable(); virtual void BuildViridisLookupTable(); virtual void BuildMagmaLookupTable(); virtual void BuildJetLookupTable(bool transparent = false); virtual void BuildPETColorLookupTable(); virtual void BuildPET20LookupTable(); virtual void BuildMultiLabelLookupTable(); vtkSmartPointer m_LookupTable; float m_Window; float m_Level; float m_Opacity; LookupTableType m_Type; private: itk::LightObject::Pointer InternalClone() const override; }; } // namespace mitk #endif /* mitkLookupTable_h */ diff --git a/Modules/Core/include/mitkLookupTableProperty.h b/Modules/Core/include/mitkLookupTableProperty.h index 7450b71adc..d9b795c780 100644 --- a/Modules/Core/include/mitkLookupTableProperty.h +++ b/Modules/Core/include/mitkLookupTableProperty.h @@ -1,84 +1,84 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKLookupTablePROPERTY_H_HEADER_INCLUDED_C10EEAA8 #define MITKLookupTablePROPERTY_H_HEADER_INCLUDED_C10EEAA8 #include "mitkBaseProperty.h" #include "mitkLookupTable.h" #include namespace mitk { #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4522) #endif /** * @brief The LookupTableProperty class Property to associate mitk::LookupTable * to an mitk::DataNode. * @ingroup DataManagement * * @note If you want to use this property to colorize an mitk::Image, make sure * to set the mitk::RenderingModeProperty to a mode which supports lookup tables * (e.g. LOOKUPTABLE_COLOR). Make sure to check the documentation of the * mitk::RenderingModeProperty. For a code example how to use the mitk::LookupTable * and this property check the mitkImageVtkMapper2DLookupTableTest.cpp in - * Core\Code\Testing. + * Core/Code/Testing. */ class MITKCORE_EXPORT LookupTableProperty : public BaseProperty { protected: LookupTable::Pointer m_LookupTable; LookupTableProperty(); LookupTableProperty(const LookupTableProperty &); LookupTableProperty(const mitk::LookupTable::Pointer lut); public: typedef LookupTable::Pointer ValueType; mitkClassMacro(LookupTableProperty, BaseProperty); itkFactorylessNewMacro(Self); itkCloneMacro(Self) mitkNewMacro1Param(LookupTableProperty, const mitk::LookupTable::Pointer); itkGetObjectMacro(LookupTable, LookupTable); ValueType GetValue() const; void SetLookupTable(const mitk::LookupTable::Pointer aLookupTable); void SetValue(const ValueType &); std::string GetValueAsString() const override; using BaseProperty::operator=; private: // purposely not implemented LookupTableProperty &operator=(const LookupTableProperty &); itk::LightObject::Pointer InternalClone() const override; bool IsEqual(const BaseProperty &property) const override; bool Assign(const BaseProperty &property) override; }; #ifdef _MSC_VER #pragma warning(pop) #endif } // namespace mitk #endif /* MITKLookupTablePROPERTY_H_HEADER_INCLUDED_C10EEAA8 */ diff --git a/Modules/Core/include/mitkLookupTables.h b/Modules/Core/include/mitkLookupTables.h index 5321bf8424..b2fea21567 100644 --- a/Modules/Core/include/mitkLookupTables.h +++ b/Modules/Core/include/mitkLookupTables.h @@ -1,35 +1,35 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKLOOKUPTABLES_H_HEADER_INCLUDED #define MITKLOOKUPTABLES_H_HEADER_INCLUDED #include "mitkGenericLookupTable.h" namespace mitk { /**Documentation * \brief specializations of GenericLookupTable * * This file contains specializations of mitk::GenericLookupTable * for bool, float, int and std::string lookuptables - * \WARN: you have to call the mitkSpecializeGenericLookupTableOperator macro + * \warning you have to call the mitkSpecializeGenericLookupTableOperator macro * in mitkLookupTables.cpp with each specialization to add an ostream << operator * for that lookuptable specialization. */ mitkSpecializeGenericLookupTable(BoolLookupTable, bool); mitkSpecializeGenericLookupTable(FloatLookupTable, float); mitkSpecializeGenericLookupTable(IntLookupTable, int); mitkSpecializeGenericLookupTable(StringLookupTable, std::string); } // namespace mitk #endif /* MITKLOOKUPTABLES_H_HEADER_INCLUDED*/ diff --git a/Modules/Core/include/mitkMaterial.h b/Modules/Core/include/mitkMaterial.h index 7bbffc603b..cfb2c36e4d 100644 --- a/Modules/Core/include/mitkMaterial.h +++ b/Modules/Core/include/mitkMaterial.h @@ -1,483 +1,453 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _MITK_MATERIAL_H_ #define _MITK_MATERIAL_H_ #include #include #include #include #include #include #include namespace mitk { /** * Encapsulates 3D visualization properties which are forwarded to vtk for * color mapping. This includes color, specular coefficient and power, opacity * interpolation type (flat, gouraud, phong) and representation (points, * wireframe or surface). * * @see vtkProperty */ class MITKCORE_EXPORT Material : public itk::Object { public: mitkClassMacroItkParent(Material, itk::Object); typedef itk::RGBPixel Color; enum InterpolationType { Flat, Gouraud, Phong }; enum RepresentationType { Points, Wireframe, Surface }; /** * Constructor. Materials are set to the following default values: * Color (0.5, 0.5, 0.5) color coefficient 1.0, specular color (1.0, 1.0, 1.0), * specular coefficient 1.0, specular power 10, opacity 1.0, interpolation * Gouraud, representation Surface. - * @param node optinally a data tree node may be defined to which the properties - * are forwarded. Please note, that if this node doesn't have the - * needed properties associated, they will be added. */ static Pointer New() { Pointer smartPtr = new Material(); smartPtr->UnRegister(); return smartPtr; } /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * @param color the material color in RGB. Each RGB value should be in the * range [0..1] * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. - * @param node optinally a data tree node may be defined to which the properties - * are forwarded. Please note, that if this node doesn't have the - * needed properties associated, they will be added. */ static Pointer New(Color color, double opacity = 1.0f) { Pointer smartPtr = new Material(color, opacity); smartPtr->UnRegister(); return smartPtr; } /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * @param red the red component of the materials color (range [0..1]) * @param green the green component of the materials color (range [0..1]) * @param blue the blue component of the materials color (range [0..1]) * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. - * @param node optionally a data tree node may be defined to which the properties - * are forwarded. Please note, that if this node doesn't have the - * needed properties associated, they will be added. */ static Pointer New(double red, double green, double blue, double opacity = 1.0f) { Pointer smartPtr = new Material(red, green, blue, opacity); smartPtr->UnRegister(); return smartPtr; } /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * @param red the red component of the materials color (range [0..1]) * @param green the green component of the materials color (range [0..1]) * @param blue the blue component of the materials color (range [0..1]) * @param colorCoefficient a scaling factor for the color coefficient which * will be multiplied with each color component (range [0..1]). * @param specularCoefficient controls in combination with the specular power * how shiny the material will appear (range [0..1]). * @param specularPower controls in combination with the specular coefficient * how shiny the material will appear (range [0..inf]). * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. - * @param node optionally a data tree node may be defined to which the properties - * are forwarded. Please note, that if this node doesn't have the - * needed properties associated, they will be added. */ static Pointer New(double red, double green, double blue, double colorCoefficient, double specularCoefficient, double specularPower, double opacity) { Pointer smartPtr = new Material(red, green, blue, colorCoefficient, specularCoefficient, specularPower, opacity); smartPtr->UnRegister(); return smartPtr; } /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * * @param color the material color in RGB. Each RGB value should be in the * range [0..1] * @param colorCoefficient a scaling factor for the color coefficient which * will be multiplied with each color component (range [0..1]). * @param specularCoefficient controls in combination with the specular power * how shiny the material will appear (range [0..1]). * @param specularPower controls in combination with the specular coefficient * how shiny the material will appear (range [0..inf]). * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. - * @param node optionally a data tree node may be defined to which the properties - * are forwarded. Please note, that if this node doesn't have the - * needed properties associated, they will be added. */ static Pointer New( Color color, double colorCoefficient, double specularCoefficient, double specularPower, double opacity) { Pointer smartPtr = new Material(color, colorCoefficient, specularCoefficient, specularPower, opacity); smartPtr->UnRegister(); return smartPtr; } /** * Copy constructor */ mitkNewMacro1Param(Material, const Material &); /** * Copy constructor, provided for convinience. The values are copied from property * and afterwards the values provided for red green blue and opacity are written into the object. */ static Pointer New( const Material &property, double red, double green, double blue, double opacity = 1.0, std::string name = "") { Pointer smartPtr = new Material(property, red, green, blue, opacity, name); smartPtr->UnRegister(); return smartPtr; } virtual bool Assignable(const Material &other) const; virtual Material &operator=(const Material &other); /* Sets the materials color in RGB space. The rgb components have to be * in the range [0..1] * @param color the new color of the material */ virtual void SetColor(Color color); /** * Sets the materials color in RGB space. The rgb components have to be * in the range [0..1] * @param red the red component of the materials color (range [0..1]) * @param green the green component of the materials color (range [0..1]) * @param blue the blue component of the materials color (range [0..1]) */ virtual void SetColor(double red, double green, double blue); /** * Sets a attenuation coefficient for the color. A value of 0 results in * a black object. VAlid range is [0..1] * @param coefficient the color attenuation coefficient */ virtual void SetColorCoefficient(double coefficient); /** * Sets the specular color * @param color the specular color in RGB. Each RGB value should be in the * range [0..1] */ virtual void SetSpecularColor(Color color); /** * Sets the specular color * @param red the red component of the specular color (range [0..1]) * @param green the green component of the specular color (range [0..1]) * @param blue the blue component of the specular color (range [0..1]) */ virtual void SetSpecularColor(double red, double green, double blue); /** * Sets the specular coefficient which controls the shininess of the object * together with the specular power * @param specularCoefficient the new specular coefficient. Valid range * is [0..1] */ virtual void SetSpecularCoefficient(double specularCoefficient); /** * Sets the specular power which controls the shininess of the object * together with the specular coefficient * @param specularCoefficient the new specular coefficient. Valid range * is [0..inf] */ virtual void SetSpecularPower(double specularPower); /** * Sets the opacity of the material, which controls how transparent the * object appears. Valid range is [0..1], where 0 means fully transparent * and 1 means a solid surface. * @param opacity the new opacity of the material */ virtual void SetOpacity(double opacity); /** * Sets the surface interpolation method of the object rendered using the * given materials. Valid Interopation types are Flat, Gouraud and Phong. * See any computer graphics book for their meaning * @param interpolation the interpolation method used for rendering of * surfaces. */ virtual void SetInterpolation(InterpolationType interpolation); /** * Sets the surface representation method of the object rendered using the * given materials. Valid Interopation types are Points, Wireframe and * Surface. * @param representation the representation method used for rendering of * surfaces. */ virtual void SetRepresentation(RepresentationType representation); /** * Set/Get the width of a Line. The width is expressed in screen units. The default is 1.0. */ virtual void SetLineWidth(float lineWidth); /** * @returns the color of the material */ virtual Color GetColor() const; /** * @returns the color coefficient of the material. Range is [0..1] */ virtual double GetColorCoefficient() const; /** * @returns the specular color of the material in rgb values, which * range from 0 .. 1 */ virtual Color GetSpecularColor() const; /** * @returns the specular coefficient used for rendering. Range is [0..1] */ virtual double GetSpecularCoefficient() const; /** * @returns the specular power. Ranges from 0 to infinity */ virtual double GetSpecularPower() const; /** * @returns the opacity of the material. Ranges from 0 to 1 */ virtual double GetOpacity() const; /** * @returns the interpolation method used for rendering. */ virtual InterpolationType GetInterpolation() const; /** * @returns the representation type used for rendering. */ virtual RepresentationType GetRepresentation() const; /** * @returns the interpolation method used for rendering using the predefined * vtk constants. */ virtual int GetVtkInterpolation() const; /** * @returns the representation type used for rendering using the predefined * vtk constants. */ virtual int GetVtkRepresentation() const; /** * @returns the line width used for wireframe rendering as a fraction of screen units */ virtual float GetLineWidth() const; /** * Fills the current materials with the properties of the * given material. * @param property the materials which should be copied in the * current materials */ virtual void Initialize(const Material &property); /** * comparison operator which uses the member variables for * comparison */ virtual bool operator==(const Material &property) const; /** * Dumps the properties to the out stream out */ void PrintSelf(std::ostream &os, itk::Indent) const override; /** * Sets an optional name which may be associated with the material property * Please note, that this name is NOT forwarded to the data tree node * as the node name */ itkSetMacro(Name, std::string); /** * returns the name associated with the material property */ itkGetConstMacro(Name, std::string); protected: /** * Constructor. Materials are set to the following default values: * Color (0.5, 0.5, 0.5) color coefficient 1.0, specular color (1.0, 1.0, 1.0), * specular coefficient 1.0, specular power 10, opacity 1.0, interpolation * Gouraud, representation Surface. - * @param node optinally a data tree node may be defined to which the properties - * are forwarded. Please note, that if this node doesn't have the - * needed properties associated, they will be added. */ Material(); /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * @param color the material color in RGB. Each RGB value should be in the * range [0..1] * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. - * @param node optinally a data tree node may be defined to which the properties - * are forwarded. Please note, that if this node doesn't have the - * needed properties associated, they will be added. */ Material(Color color, double opacity = 1.0f); /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * @param red the red component of the materials color (range [0..1]) * @param green the green component of the materials color (range [0..1]) * @param blue the blue component of the materials color (range [0..1]) * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. - * @param node optionally a data tree node may be defined to which the properties - * are forwarded. Please note, that if this node doesn't have the - * needed properties associated, they will be added. */ Material(double red, double green, double blue, double opacity = 1.0f); /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * @param red the red component of the materials color (range [0..1]) * @param green the green component of the materials color (range [0..1]) * @param blue the blue component of the materials color (range [0..1]) * @param colorCoefficient a scaling factor for the color coefficient which * will be multiplied with each color component (range [0..1]). * @param specularCoefficient controls in combination with the specular power * how shiny the material will appear (range [0..1]). * @param specularPower controls in combination with the specular coefficient * how shiny the material will appear (range [0..inf]). * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. - * @param node optionally a data tree node may be defined to which the properties - * are forwarded. Please note, that if this node doesn't have the - * needed properties associated, they will be added. */ Material(double red, double green, double blue, double colorCoefficient, double specularCoefficient, double specularPower, double opacity); /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * * @param color the material color in RGB. Each RGB value should be in the * range [0..1] * @param colorCoefficient a scaling factor for the color coefficient which * will be multiplied with each color component (range [0..1]). * @param specularCoefficient controls in combination with the specular power * how shiny the material will appear (range [0..1]). * @param specularPower controls in combination with the specular coefficient * how shiny the material will appear (range [0..inf]). * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. - * @param node optionally a data tree node may be defined to which the properties - * are forwarded. Please note, that if this node doesn't have the - * needed properties associated, they will be added. */ Material(Color color, double colorCoefficient, double specularCoefficient, double specularPower, double opacity); /** * Copy constructor */ Material(const Material &property); /** * Copy constructor, provided for convinience. The values are copied from property * and afterwards the values provided for red green blue and opacity are written into the object. */ Material( const Material &property, double red, double green, double blue, double opacity = 1.0, std::string name = ""); virtual void InitializeStandardValues(); virtual void Update(); std::string m_Name; Color m_Color; Color m_SpecularColor; double m_ColorCoefficient; double m_SpecularCoefficient; double m_SpecularPower; double m_Opacity; float m_LineWidth; InterpolationType m_Interpolation; RepresentationType m_Representation; }; typedef itk::VectorContainer MaterialVectorContainer; } #endif diff --git a/Modules/Core/include/mitkMimeType.h b/Modules/Core/include/mitkMimeType.h index 05381e7952..a64e7d9429 100644 --- a/Modules/Core/include/mitkMimeType.h +++ b/Modules/Core/include/mitkMimeType.h @@ -1,89 +1,89 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKMIMETYPE_H #define MITKMIMETYPE_H #include #include #include namespace mitk { class CustomMimeType; /** * @ingroup IO * * @brief The MimeType class represens a registered mime-type. It is an immutable wrapper for mitk::CustomMimeType * that makes memory handling easier by providing a stack-object for the user. * * If you want to register a new MimeType, use the CustomMimeType class instead. Wrapping will be performed for you * automatically. * In all other cases you should use mitk::MimeType when working with mime-types. */ class MITKCORE_EXPORT MimeType { public: MimeType(); MimeType(const MimeType &other); MimeType(const CustomMimeType &x, int rank, long id); ~MimeType(); MimeType &operator=(const MimeType &other); bool operator==(const MimeType &other) const; bool operator<(const MimeType &other) const; - /** @See mitk::CustomMimeType::GetName()*/ + /** @see mitk::CustomMimeType::GetName()*/ std::string GetName() const; - /** @See mitk::CustomMimeType::GetCategory()*/ + /** @see mitk::CustomMimeType::GetCategory()*/ std::string GetCategory() const; - /** @See mitk::CustomMimeType::GetExtensions()*/ + /** @see mitk::CustomMimeType::GetExtensions()*/ std::vector GetExtensions() const; - /** @See mitk::CustomMimeType::GetComment()*/ + /** @see mitk::CustomMimeType::GetComment()*/ std::string GetComment() const; - /** @See mitk::CustomMimeType::GetFileNameWithoutExtension()*/ + /** @see mitk::CustomMimeType::GetFileNameWithoutExtension()*/ std::string GetFilenameWithoutExtension(const std::string &path) const; - /** @See mitk::CustomMimeType::AppliesTo()*/ + /** @see mitk::CustomMimeType::AppliesTo()*/ bool AppliesTo(const std::string &path) const; - /** @See mitk::CustomMimeType::MatchesExtension()*/ + /** @see mitk::CustomMimeType::MatchesExtension()*/ bool MatchesExtension(const std::string &path) const; - /** @See mitk::CustomMimeType::IsValid()*/ + /** @see mitk::CustomMimeType::IsValid()*/ bool IsValid() const; - /** @See mitk::CustomMimeType::Swap()*/ + /** @see mitk::CustomMimeType::Swap()*/ void Swap(MimeType &m); private: struct Impl; // Use C++11 shared_ptr instead us::SharedDataPointer m_Data; }; MITKCORE_EXPORT void swap(MimeType &m1, MimeType &m2); MITKCORE_EXPORT std::ostream &operator<<(std::ostream &os, const MimeType &mimeType); } #endif // MITKMIMETYPE_H diff --git a/Modules/Core/include/mitkRenderingManager.h b/Modules/Core/include/mitkRenderingManager.h index 6c69b69c2c..bc47776433 100644 --- a/Modules/Core/include/mitkRenderingManager.h +++ b/Modules/Core/include/mitkRenderingManager.h @@ -1,402 +1,402 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKRENDERINGMANAGER_H_HEADER_INCLUDED_C135A197 #define MITKRENDERINGMANAGER_H_HEADER_INCLUDED_C135A197 #include #include #include #include #include #include "mitkProperties.h" #include "mitkPropertyList.h" #include "mitkTimeGeometry.h" #include class vtkRenderWindow; class vtkObject; namespace mitk { class RenderingManager; class RenderingManagerFactory; class BaseGeometry; class SliceNavigationController; class BaseRenderer; class DataStorage; /** * \brief Manager for coordinating the rendering process. * * RenderingManager is a central instance retrieving and executing * RenderWindow update requests. Its main purpose is to coordinate * distributed requests which cannot be aware of each other - lacking the * knowledge of whether they are really necessary or not. For example, two * objects might determine that a specific RenderWindow needs to be updated. * This would result in one unnecessary update, if both executed the update * on their own. * * The RenderingManager addresses this by letting each such object * request an update, and waiting for other objects to possibly * issue the same request. The actual update will then only be executed at a * well-defined point in the main event loop (this may be each time after * event processing is done). * * Convinience methods for updating all RenderWindows which have been * registered with the RenderingManager exist. If theses methods are not * used, it is not required to register (add) RenderWindows prior to using * the RenderingManager. * * The methods #ForceImmediateUpdate() and #ForceImmediateUpdateAll() can * be used to force the RenderWindow update execution without any delay, * bypassing the request functionality. * * The interface of RenderingManager is platform independent. Platform * specific subclasses have to be implemented, though, to supply an * appropriate event issueing for controlling the update execution process. * See method documentation for a description of how this can be done. * * \sa TestingRenderingManager An "empty" RenderingManager implementation which * can be used in tests etc. * */ class MITKCORE_EXPORT RenderingManager : public itk::Object { public: mitkClassMacroItkParent(RenderingManager, itk::Object); typedef std::vector RenderWindowVector; typedef std::vector FloatVector; typedef std::vector BoolVector; typedef itk::SmartPointer DataStoragePointer; enum RequestType { REQUEST_UPDATE_ALL = 0, REQUEST_UPDATE_2DWINDOWS, REQUEST_UPDATE_3DWINDOWS }; static Pointer New(); /** Set the object factory which produces the desired platform specific * RenderingManager singleton instance. */ static void SetFactory(RenderingManagerFactory *factory); /** Get the object factory which produces the platform specific * RenderingManager instances. */ static const RenderingManagerFactory *GetFactory(); /** Returns true if a factory has already been set. */ static bool HasFactory(); /** Get the RenderingManager singleton instance. */ static RenderingManager *GetInstance(); /** Returns true if the singleton instance does already exist. */ static bool IsInstantiated(); /** Adds a RenderWindow. This is required if the methods #RequestUpdateAll * or #ForceImmediateUpdate are to be used. */ void AddRenderWindow(vtkRenderWindow *renderWindow); /** Removes a RenderWindow. */ void RemoveRenderWindow(vtkRenderWindow *renderWindow); /** Get a list of all registered RenderWindows */ const RenderWindowVector &GetAllRegisteredRenderWindows(); /** Requests an update for the specified RenderWindow, to be executed as * soon as the main loop is ready for rendering. */ void RequestUpdate(vtkRenderWindow *renderWindow); /** Immediately executes an update of the specified RenderWindow. */ void ForceImmediateUpdate(vtkRenderWindow *renderWindow); /** Requests all currently registered RenderWindows to be updated. * If only 2D or 3D windows should be updated, this can be specified * via the parameter requestType. */ void RequestUpdateAll(RequestType type = REQUEST_UPDATE_ALL); /** Immediately executes an update of all registered RenderWindows. * If only 2D or 3D windows should be updated, this can be specified * via the parameter requestType. */ void ForceImmediateUpdateAll(RequestType type = REQUEST_UPDATE_ALL); /** Initializes the windows specified by requestType to the geometry of the * given DataStorage. */ // virtual bool InitializeViews( const DataStorage *storage, const DataNode* node = nullptr, // RequestType type = REQUEST_UPDATE_ALL, bool preserveRoughOrientationInWorldSpace = false ); /** Initializes the windows specified by requestType to the given * geometry. PLATFORM SPECIFIC. TODO: HOW IS THIS PLATFORM SPECIFIC? * Throws an exception if bounding box has 0 extent due to exceeding * double precision range. */ virtual bool InitializeViews(const BaseGeometry *geometry, RequestType type = REQUEST_UPDATE_ALL, bool preserveRoughOrientationInWorldSpace = false); virtual bool InitializeViews(const TimeGeometry *geometry, RequestType type = REQUEST_UPDATE_ALL, bool preserveRoughOrientationInWorldSpace = false); /** Initializes the windows to the default viewing direction * (geomtry information is NOT changed). PLATFORM SPECIFIC. */ virtual bool InitializeViews(RequestType type = REQUEST_UPDATE_ALL); /** Initializes the specified window to the geometry of the given * DataNode. Set "initializeGlobalTimeSNC" to true in order to use this * geometry as global TimeGeometry. PLATFORM SPECIFIC. */ // virtual bool InitializeView( vtkRenderWindow *renderWindow, const DataStorage* ds, const DataNode* node = nullptr, // bool initializeGlobalTimeSNC = false ); /** Initializes the specified window to the given geometry. Set * "initializeGlobalTimeSNC" to true in order to use this geometry as * global TimeGeometry. PLATFORM SPECIFIC. */ virtual bool InitializeView(vtkRenderWindow *renderWindow, const BaseGeometry *geometry, bool initializeGlobalTimeSNC = false); virtual bool InitializeView(vtkRenderWindow *renderWindow, const TimeGeometry *geometry, bool initializeGlobalTimeSNC = false); /** Initializes the specified window to the default viewing direction * (geomtry information is NOT changed). PLATFORM SPECIFIC. */ virtual bool InitializeView(vtkRenderWindow *renderWindow); /** * @brief Initializes the renderwindows by the aggregated geometry of * all objects that are held in the data storage. * This is basically a global reinit - * @param The data storage from which the bounding object can be retrieved + * @param dataStorage The data storage from which the bounding object can be retrieved */ - virtual void InitializeViewsByBoundingObjects(const DataStorage *); + virtual void InitializeViewsByBoundingObjects(const DataStorage *dataStorage); /** Gets the (global) SliceNavigationController responsible for * time-slicing. */ const SliceNavigationController *GetTimeNavigationController() const; /** Gets the (global) SliceNavigationController responsible for * time-slicing. */ SliceNavigationController *GetTimeNavigationController(); ~RenderingManager() override; /** Executes all pending requests. This method has to be called by the * system whenever a RenderingManager induced request event occurs in * the system pipeline (see concrete RenderingManager implementations). */ virtual void ExecutePendingRequests(); bool IsRendering() const; void AbortRendering(); /** En-/Disable LOD increase globally. */ itkSetMacro(LODIncreaseBlocked, bool); /** En-/Disable LOD increase globally. */ itkGetMacro(LODIncreaseBlocked, bool); /** En-/Disable LOD increase globally. */ itkBooleanMacro(LODIncreaseBlocked); /** En-/Disable LOD abort mechanism. */ itkSetMacro(LODAbortMechanismEnabled, bool); /** En-/Disable LOD abort mechanism. */ itkGetMacro(LODAbortMechanismEnabled, bool); /** En-/Disable LOD abort mechanism. */ itkBooleanMacro(LODAbortMechanismEnabled); /** Force a sub-class to start a timer for a pending hires-rendering request */ virtual void StartOrResetTimer(){}; /** To be called by a sub-class from a timer callback */ void ExecutePendingHighResRenderingRequest(); virtual void DoStartRendering(){}; virtual void DoMonitorRendering(){}; virtual void DoFinishAbortRendering(){}; int GetNextLOD(BaseRenderer *renderer); /** Set current LOD (nullptr means all renderers)*/ void SetMaximumLOD(unsigned int max); void SetShading(bool state, unsigned int lod); bool GetShading(unsigned int lod); void SetClippingPlaneStatus(bool status); bool GetClippingPlaneStatus(); void SetShadingValues(float ambient, float diffuse, float specular, float specpower); FloatVector &GetShadingValues(); /** Returns a property list */ PropertyList::Pointer GetPropertyList() const; /** Returns a property from m_PropertyList */ BaseProperty *GetProperty(const char *propertyKey) const; /** Sets or adds (if not present) a property in m_PropertyList */ void SetProperty(const char *propertyKey, BaseProperty *propertyValue); /** * \brief Setter / Getter for internal DataStorage * * Sets / returns the mitk::DataStorage that is used internally. This instance holds all mitk::DataNodes that are * rendered by the registered BaseRenderers. * * If this DataStorage is changed at runtime by calling SetDataStorage(), * all currently registered BaseRenderers are automatically given the correct instance. * When a new BaseRenderer is added, it is automatically initialized with the currently active DataStorage. */ void SetDataStorage(mitk::DataStorage *storage); /** * \brief Setter / Getter for internal DataStorage * * Sets / returns the mitk::DataStorage that is used internally. This instance holds all mitk::DataNodes that are * rendered by the registered BaseRenderers. * * If this DataStorage is changed at runtime by calling SetDataStorage(), * all currently registered BaseRenderers are automatically given the correct instance. * When a new BaseRenderer is added, it is automatically initialized with the currently active DataStorage. */ mitk::DataStorage *GetDataStorage(); /** * @brief Sets a flag to the given renderwindow to indicated that it has the focus e.g. has been clicked recently. * @param focusWindow */ void SetRenderWindowFocus(vtkRenderWindow *focusWindow); itkGetMacro(FocusedRenderWindow, vtkRenderWindow *); itkSetMacro(ConstrainedPanningZooming, bool); itkGetMacro(AntiAliasing, AntiAliasing); void SetAntiAliasing(AntiAliasing antiAliasing); protected: enum { RENDERING_INACTIVE = 0, RENDERING_REQUESTED, RENDERING_INPROGRESS }; RenderingManager(); /** Abstract method for generating a system specific event for rendering * request. This method is called whenever an update is requested */ virtual void GenerateRenderingRequestEvent() = 0; virtual void InitializePropertyList(); bool m_UpdatePending; typedef std::map RendererIntMap; typedef std::map RendererBoolMap; RendererBoolMap m_RenderingAbortedMap; RendererIntMap m_NextLODMap; unsigned int m_MaxLOD; bool m_LODIncreaseBlocked; bool m_LODAbortMechanismEnabled; BoolVector m_ShadingEnabled; bool m_ClippingPlaneEnabled; FloatVector m_ShadingValues; static void RenderingStartCallback(vtkObject *caller, unsigned long eid, void *clientdata, void *calldata); static void RenderingProgressCallback(vtkObject *caller, unsigned long eid, void *clientdata, void *calldata); static void RenderingEndCallback(vtkObject *caller, unsigned long eid, void *clientdata, void *calldata); typedef std::map RenderWindowList; RenderWindowList m_RenderWindowList; RenderWindowVector m_AllRenderWindows; struct RenderWindowCallbacks { vtkCallbackCommand *commands[3u]; }; typedef std::map RenderWindowCallbacksList; RenderWindowCallbacksList m_RenderWindowCallbacksList; itk::SmartPointer m_TimeNavigationController; static RenderingManager::Pointer s_Instance; static RenderingManagerFactory *s_RenderingManagerFactory; PropertyList::Pointer m_PropertyList; DataStoragePointer m_DataStorage; bool m_ConstrainedPanningZooming; private: void InternalViewInitialization(mitk::BaseRenderer *baseRenderer, const mitk::TimeGeometry *geometry, bool boundingBoxInitialized, int mapperID); vtkRenderWindow *m_FocusedRenderWindow; AntiAliasing m_AntiAliasing; }; #pragma GCC visibility push(default) itkEventMacro(RenderingManagerEvent, itk::AnyEvent); itkEventMacro(RenderingManagerViewsInitializedEvent, RenderingManagerEvent); #pragma GCC visibility pop itkEventMacroDeclaration(FocusChangedEvent, itk::AnyEvent); /** * Generic RenderingManager implementation for "non-rendering-plattform", * e.g. for tests. Its factory (TestingRenderingManagerFactory) is * automatically on start-up and is used by default if not other * RenderingManagerFactory is instantiated explicitly thereafter. * (see mitkRenderingManager.cpp) */ class MITKCORE_EXPORT TestingRenderingManager : public RenderingManager { public: mitkClassMacro(TestingRenderingManager, RenderingManager); itkFactorylessNewMacro(Self); itkCloneMacro(Self); protected: void GenerateRenderingRequestEvent() override {}; }; } // namespace mitk #endif /* MITKRenderingManager_H_HEADER_INCLUDED_C135A197 */ diff --git a/Modules/Core/include/mitkRestorePlanePositionOperation.h b/Modules/Core/include/mitkRestorePlanePositionOperation.h index 7a2c7f0dd6..80b67b70a7 100644 --- a/Modules/Core/include/mitkRestorePlanePositionOperation.h +++ b/Modules/Core/include/mitkRestorePlanePositionOperation.h @@ -1,74 +1,78 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkRestorePlanePositionOperation_h_Included #define mitkRestorePlanePositionOperation_h_Included #include "mitkCommon.h" #include "mitkNumericTypes.h" #include "mitkPointOperation.h" namespace mitk { //##Documentation //## TODO class MITKCORE_EXPORT RestorePlanePositionOperation : public Operation { public: //##Documentation //##@brief Operation that handles all actions on one Point. //## //## @param operationType is the type of the operation (see mitkOperation.h; e.g. move or add; Information for // StateMachine::ExecuteOperation()); - //## @param point is the information of the point to add or is the information to change a point into - //## @param index is e.g. the position in a list which describes the element to change + //## @param width + //## @param height + //## @param spacing + //## @param pos + //## @param direction + //## @param transform // PointOperation(OperationType operationType, Point3D point, int index = -1, bool selected = true, // PointSpecificationType type = PTUNDEFINED); RestorePlanePositionOperation(OperationType operationType, ScalarType width, ScalarType height, Vector3D spacing, unsigned int pos, Vector3D direction, AffineTransform3D::Pointer transform); ~RestorePlanePositionOperation() override; Vector3D GetDirectionVector(); ScalarType GetWidth(); ScalarType GetHeight(); Vector3D GetSpacing(); unsigned int GetPos(); AffineTransform3D::Pointer GetTransform(); private: Vector3D m_Spacing; Vector3D m_DirectionVector; ScalarType m_Width; ScalarType m_Height; unsigned int m_Pos; AffineTransform3D::Pointer m_Transform; }; } // namespace mitk #endif diff --git a/Modules/Core/include/mitkSinglePointDataInteractor.h b/Modules/Core/include/mitkSinglePointDataInteractor.h index 95aea60401..d29f51ffd8 100644 --- a/Modules/Core/include/mitkSinglePointDataInteractor.h +++ b/Modules/Core/include/mitkSinglePointDataInteractor.h @@ -1,61 +1,61 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkSinglePointDataInteractor_h_ #define mitkSinglePointDataInteractor_h_ #include "itkObject.h" #include "itkObjectFactory.h" #include "itkSmartPointer.h" #include "mitkCommon.h" #include "mitkPointSetDataInteractor.h" #include #include namespace mitk { /** * Class SinglePointDataInteractor * \brief Implementation of the single point interaction * * Interactor operates on a single point set, when a data node is set, its containing point set is clear for * initialization. */ // Inherit from DataInteratcor, this provides functionality of a state machine and configurable inputs. class MITKCORE_EXPORT SinglePointDataInteractor : public PointSetDataInteractor { public: mitkClassMacro(SinglePointDataInteractor, PointSetDataInteractor); itkFactorylessNewMacro(Self); itkCloneMacro(Self); protected : SinglePointDataInteractor(); ~SinglePointDataInteractor() override; /** Adds a point at the given coordinates. * This function overwrites the behavior of PointSetDataInteractor such that instead of adding new points * the first points position is updated. All other interaction (move,delete) is still handled by * PointSetDataInteractor. */ void AddPoint(StateMachineAction *, InteractionEvent *event) override; /** * @brief SetMaxPoints Sets the maximal number of points for the pointset * Overwritten, per design this class will always have a maximal number of one. * @param maxNumber */ - virtual void SetMaxPoints(unsigned int /*maxNumber*/ = 0) {} + virtual void SetMaxPoints(unsigned int maxNumber = 0) {} void DataNodeChanged() override; }; } #endif diff --git a/Modules/Core/include/mitkSlicedGeometry3D.h b/Modules/Core/include/mitkSlicedGeometry3D.h index 27f09a6086..573541b549 100644 --- a/Modules/Core/include/mitkSlicedGeometry3D.h +++ b/Modules/Core/include/mitkSlicedGeometry3D.h @@ -1,327 +1,328 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKSLICEDGEOMETRY3D_H_HEADER_INCLUDED_C1EBD0AD #define MITKSLICEDGEOMETRY3D_H_HEADER_INCLUDED_C1EBD0AD #include "mitkBaseGeometry.h" #include "mitkPlaneGeometry.h" namespace mitk { class SliceNavigationController; class NavigationController; /** \brief Describes the geometry of a data object consisting of slices. * * A PlaneGeometry can be requested for each slice. In the case of * \em evenly-spaced, \em plane geometries (m_EvenlySpaced==true), * only the 2D-geometry of the first slice has to be set (to an instance of * PlaneGeometry). The 2D geometries of the other slices are calculated * by shifting the first slice in the direction m_DirectionVector by * m_Spacing.z * sliceNumber. The m_Spacing member (which is only * relevant in the case m_EvenlySpaced==true) descibes the size of a voxel * (in mm), i.e., m_Spacing.x is the voxel width in the x-direction of the * plane. It is derived from the reference geometry of this SlicedGeometry3D, * which usually would be the global geometry describing how datasets are to * be resliced. * * By default, slices are oriented in the direction of one of the main axes * (x, y, z). However, by means of rotation, it is possible to realign the * slices in any possible direction. In case of an inclined plane, the spacing * is derived as a product of the (regular) geometry spacing and the direction * vector of the plane. * * SlicedGeometry3D and the associated PlaneGeometries have to be initialized in * the method GenerateOutputInformation() of BaseProcess (or CopyInformation / * UpdateOutputInformation of BaseData, if possible, e.g., by analyzing pic * tags in Image) subclasses. See also * * \sa itk::ProcessObject::GenerateOutputInformation(), * \sa itk::DataObject::CopyInformation() and * \a itk::DataObject::UpdateOutputInformation(). * * Rule: everything is in mm (or ms for temporal information) if not * stated otherwise. * * \warning The hull (i.e., transform, bounding-box and * time-bounds) is only guaranteed to be up-to-date after calling * UpdateInformation(). * * \ingroup Geometry */ class MITKCORE_EXPORT SlicedGeometry3D : public mitk::BaseGeometry { public: mitkClassMacro(SlicedGeometry3D, BaseGeometry); /** Method for creation through the object factory. */ itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** * \brief Returns the PlaneGeometry of the slice (\a s). * * If (a) m_EvenlySpaced==true, (b) we don't have a PlaneGeometry stored * for the requested slice, and (c) the first slice (s=0) * is a PlaneGeometry instance, then we calculate the geometry of the * requested as the plane of the first slice shifted by m_Spacing[3]*s * in the direction of m_DirectionVector. * * \warning The PlaneGeometries are not necessarily up-to-date and not even * initialized. * * The PlaneGeometries have to be initialized in the method * GenerateOutputInformation() of BaseProcess (or CopyInformation / * UpdateOutputInformation of BaseData, if possible, e.g., by analyzing * pic tags in Image) subclasses. See also * * \sa itk::ProcessObject::GenerateOutputInformation(), * \sa itk::DataObject::CopyInformation() and * \sa itk::DataObject::UpdateOutputInformation(). */ virtual mitk::PlaneGeometry *GetPlaneGeometry(int s) const; /** * \deprecatedSince{2014_10} Please use GetPlaneGeometry */ DEPRECATED(const PlaneGeometry *GetGeometry2D(int s)) { return GetPlaneGeometry(s); } /** * \deprecatedSince{2014_10} Please use SetPlaneGeometry */ DEPRECATED(void SetGeometry2D(PlaneGeometry *geo, int s)) { SetPlaneGeometry(geo, s); } //##Documentation //## @brief When switching from an Image Geometry to a normal Geometry (and the other way around), you have to //change // the origin as well (See Geometry Documentation)! This function will change the "isImageGeometry" bool flag and // changes the origin respectively. void ChangeImageGeometryConsideringOriginOffset(const bool isAnImageGeometry) override; // virtual void SetTimeBounds( const mitk::TimeBounds& timebounds ); const mitk::BoundingBox *GetBoundingBox() const override; /** * \brief Get the number of slices */ itkGetConstMacro(Slices, unsigned int); /** * \brief Set PlaneGeometry of slice \a s. */ virtual bool SetPlaneGeometry(mitk::PlaneGeometry *geometry2D, int s); /** * \brief Check whether a slice exists */ virtual bool IsValidSlice(int s = 0) const; virtual const BaseGeometry* GetReferenceGeometry() const; virtual void SetReferenceGeometry(const BaseGeometry *referenceGeometry); bool HasReferenceGeometry() const; /** * \brief Set the SliceNavigationController corresponding to this sliced * geometry. * * The SNC needs to be informed when the number of slices in the geometry * changes, which can occur whenthe slices are re-oriented by rotation. */ virtual void SetSliceNavigationController(mitk::SliceNavigationController *snc); mitk::SliceNavigationController *GetSliceNavigationController(); /** * \brief Set/Get whether the SlicedGeometry3D is evenly-spaced * (m_EvenlySpaced) * * If (a) m_EvenlySpaced==true, (b) we don't have a PlaneGeometry stored for * the requested slice, and (c) the first slice (s=0) is a PlaneGeometry * instance, then we calculate the geometry of the requested as the plane * of the first slice shifted by m_Spacing.z * s in the direction of * m_DirectionVector. * * \sa GetPlaneGeometry */ itkGetConstMacro(EvenlySpaced, bool); virtual void SetEvenlySpaced(bool on = true); /** * \brief Set/Get the vector between slices for the evenly-spaced case * (m_EvenlySpaced==true). * * If the direction-vector is (0,0,0) (the default) and the first * 2D geometry is a PlaneGeometry, then the direction-vector will be * calculated from the plane normal. * * \sa m_DirectionVector */ virtual void SetDirectionVector(const mitk::Vector3D &directionVector); itkGetConstMacro(DirectionVector, const mitk::Vector3D &); itk::LightObject::Pointer InternalClone() const override; #ifndef SWIG static const std::string SLICES; const static std::string DIRECTION_VECTOR; const static std::string EVENLY_SPACED; #endif // !SWIG /** * \brief Tell this instance how many PlaneGeometries it shall manage. Bounding * box and the PlaneGeometries must be set additionally by calling the respective * methods! * * \warning Bounding box and the 2D-geometries must be set additionally: use * SetBounds(), SetGeometry(). */ virtual void InitializeSlicedGeometry(unsigned int slices); /** * \brief Completely initialize this instance as evenly-spaced with slices * parallel to the provided PlaneGeometry that is used as the first slice and * for spacing calculation. * * Initializes the bounding box according to the width/height of the * PlaneGeometry and \a slices. The spacing is calculated from the PlaneGeometry. */ virtual void InitializeEvenlySpaced(mitk::PlaneGeometry *geometry2D, unsigned int slices); /** * \brief Completely initialize this instance as evenly-spaced with slices * parallel to the provided PlaneGeometry that is used as the first slice and * for spacing calculation (except z-spacing). * * Initializes the bounding box according to the width/height of the * PlaneGeometry and \a slices. The x-/y-spacing is calculated from the * PlaneGeometry. */ virtual void InitializeEvenlySpaced(mitk::PlaneGeometry *geometry2D, mitk::ScalarType zSpacing, unsigned int slices); /** * \brief Completely initialize this instance as evenly-spaced plane slices * parallel to a side of the provided BaseGeometry and using its spacing * information. * * Initializes the bounding box according to the width/height of the * BaseGeometry and the number of slices according to * BaseGeometry::GetExtent(2). * + * \param geometry3D * \param planeorientation side parallel to which the slices will be oriented * \param top if \a true, create plane at top, otherwise at bottom * (for PlaneOrientation Axial, for other plane locations respectively) * \param frontside defines the side of the plane (the definition of * front/back is somewhat arbitrary) * - * \param rotate rotates the plane by 180 degree around its normal (the + * \param rotated rotates the plane by 180 degree around its normal (the * definition of rotated vs not rotated is somewhat arbitrary) */ virtual void InitializePlanes(const mitk::BaseGeometry *geometry3D, mitk::PlaneGeometry::PlaneOrientation planeorientation, bool top = true, bool frontside = true, bool rotated = false); void SetImageGeometry(const bool isAnImageGeometry) override; void ExecuteOperation(Operation *operation) override; static double CalculateSpacing(const mitk::Vector3D &spacing, const mitk::Vector3D &d); protected: SlicedGeometry3D(); SlicedGeometry3D(const SlicedGeometry3D &other); ~SlicedGeometry3D() override; /** * Reinitialize plane stack after rotation. More precisely, the first plane * of the stack needs to spatially aligned, in two respects: * * 1. Re-alignment with respect to the dataset center; this is necessary * since the distance from the first plane to the center could otherwise * continuously decrease or increase. * 2. Re-alignment with respect to a given reference point; the reference * point is a location which the user wants to be exactly touched by one * plane of the plane stack. The first plane is minimally shifted to * ensure this touching. Usually, the reference point would be the * point around which the geometry is rotated. */ virtual void ReinitializePlanes(const Point3D ¢er, const Point3D &referencePoint); ScalarType GetLargestExtent(const BaseGeometry *geometry); void PrintSelf(std::ostream &os, itk::Indent indent) const override; /** Calculate "directed spacing", i.e. the spacing in directions * non-orthogonal to the coordinate axes. This is done via the * ellipsoid equation. */ double CalculateSpacing(const mitk::Vector3D &direction) const; /** The extent of the slice stack, i.e. the number of slices, depends on the * plane normal. For rotated geometries, the geometry's transform needs to * be accounted in this calculation. */ mitk::Vector3D AdjustNormal(const mitk::Vector3D &normal) const; /** * Container for the 2D-geometries contained within this SliceGeometry3D. */ mutable std::vector m_PlaneGeometries; /** * If (a) m_EvenlySpaced==true, (b) we don't have a PlaneGeometry stored * for the requested slice, and (c) the first slice (s=0) * is a PlaneGeometry instance, then we calculate the geometry of the * requested as the plane of the first slice shifted by m_Spacing.z*s * in the direction of m_DirectionVector. * * \sa GetPlaneGeometry */ bool m_EvenlySpaced; /** * Vector between slices for the evenly-spaced case (m_EvenlySpaced==true). * If the direction-vector is (0,0,0) (the default) and the first * 2D geometry is a PlaneGeometry, then the direction-vector will be * calculated from the plane normal. */ mutable mitk::Vector3D m_DirectionVector; /** Number of slices this SliceGeometry3D is descibing. */ unsigned int m_Slices; /** Underlying BaseGeometry for this SlicedGeometry */ const mitk::BaseGeometry *m_ReferenceGeometry; /** SNC correcsponding to this geometry; used to reflect changes in the * number of slices due to rotation. */ // mitk::NavigationController *m_NavigationController; mitk::SliceNavigationController *m_SliceNavigationController; //##Documentation //## @brief PreSetSpacing //## //## These virtual function allows a different beahiour in subclasses. //## Do implement them in every subclass of BaseGeometry. If not needed, use //## {Superclass::PreSetSpacing();}; void PreSetSpacing(const mitk::Vector3D &aSpacing) override; }; } // namespace mitk #endif /* MITKSLICEDGEOMETRY3D_H_HEADER_INCLUDED_C1EBD0AD */ diff --git a/Modules/Core/include/mitkStateMachineTransition.h b/Modules/Core/include/mitkStateMachineTransition.h index f1ca8cdc98..4c67ca3020 100755 --- a/Modules/Core/include/mitkStateMachineTransition.h +++ b/Modules/Core/include/mitkStateMachineTransition.h @@ -1,105 +1,105 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef SMTRANSITION_H_HEADER_INCLUDED #define SMTRANSITION_H_HEADER_INCLUDED #include "mitkCommon.h" #include "mitkInteractionEvent.h" #include "mitkStateMachineAction.h" #include "mitkStateMachineCondition.h" #include #include #include "MitkCoreExports.h" namespace mitk { class StateMachineState; typedef std::vector ActionVectorType; typedef std::vector ConditionVectorType; typedef itk::SmartPointer SpStateMachineState; /** * \class StateMachineTransition * \brief Connects two states, and holds references to corresponding actions and conditions. * * This class represents a transition between two states of a statemachine. It holds a * list of conditions that have to be fulfilled in order to be executed correctly. * It also holds a list of actions that will be executed if all conditions are fulfilled. * * \ingroup Interaction **/ class MITKCORE_EXPORT StateMachineTransition : public itk::LightObject { friend class StateMachineFactory; friend class StateMachineContainer; public: mitkClassMacroItkParent(StateMachineTransition, itk::LightObject); mitkNewMacro3Param(Self, const std::string &, const std::string &, const std::string &); SpStateMachineState GetNextState() const; std::string GetNextStateName() const; /** * Check for equality. Equality is given if event variant is the same and * classes are the same or the first argument is a superclass of the second. - * \warn Here the order of arguments matters. ! + * \warning Here the order of arguments matters. ! */ bool operator==(const StateMachineTransition &transition) const; /** * @brief Get an iterator on the first action in list. **/ ActionVectorType GetActions() const; const ConditionVectorType &GetConditions() const; /** * @brief Set the next state of this object. **/ void SetNextState(const SpStateMachineState &nextState); protected: StateMachineTransition(const std::string &nextStateName, const std::string &eventClass, const std::string &eventVariant); ~StateMachineTransition() override; // Triggering Event std::string m_EventClass; std::string m_EventVariant; private: void AddAction(const StateMachineAction::Pointer &action); void AddCondition(const StateMachineCondition &condition); SpStateMachineState m_NextState; std::string m_NextStateName; InteractionEvent::Pointer m_TransitionEvent; /** * @brief The list of actions, that are executed if this transition is done. **/ std::vector m_Actions; ConditionVectorType m_Conditions; }; } // namespace mitk #endif /* SMTRANSITION_H_HEADER_INCLUDED */ diff --git a/Modules/Core/include/mitkTemporoSpatialStringProperty.h b/Modules/Core/include/mitkTemporoSpatialStringProperty.h index e261df1331..99a145cc8d 100644 --- a/Modules/Core/include/mitkTemporoSpatialStringProperty.h +++ b/Modules/Core/include/mitkTemporoSpatialStringProperty.h @@ -1,136 +1,136 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKTEMPOROSPATIALSTRINGPROPERTY_H_HEADER #define MITKTEMPOROSPATIALSTRINGPROPERTY_H_HEADER #include #include "mitkBaseProperty.h" #include #include "mitkTimeGeometry.h" #include namespace mitk { #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4522) #endif /** * @brief Property for time and space resolved string values * @ingroup DataManagement */ class MITKCORE_EXPORT TemporoSpatialStringProperty : public BaseProperty { public: typedef ::itk::IndexValueType IndexValueType; typedef std::string ValueType; mitkClassMacro(TemporoSpatialStringProperty, BaseProperty); itkFactorylessNewMacro(Self); itkCloneMacro(Self); mitkNewMacro1Param(TemporoSpatialStringProperty, const char*); mitkNewMacro1Param(TemporoSpatialStringProperty, const std::string &); /**Returns the value of the first time point in the first slice. * If now value is set it returns an empty string.*/ ValueType GetValue() const; /**Returns the value of the passed time step and slice. If it does not exist and allowedClosed is true * it will look for the closest value. If nothing could be found an empty string will be returned.*/ ValueType GetValue(const TimeStepType &timeStep, const IndexValueType &zSlice, bool allowCloseTime = false, bool allowCloseSlice = false) const; ValueType GetValueBySlice(const IndexValueType &zSlice, bool allowClose = false) const; ValueType GetValueByTimeStep(const TimeStepType &timeStep, bool allowClose = false) const; bool HasValue() const; bool HasValue(const TimeStepType &timeStep, const IndexValueType &zSlice, bool allowCloseTime = false, bool allowCloseSlice = false) const; bool HasValueBySlice(const IndexValueType &zSlice, bool allowClose = false) const; bool HasValueByTimeStep(const TimeStepType &timeStep, bool allowClose = false) const; /** return all slices stored for the specified timestep.*/ std::vector GetAvailableSlices(const TimeStepType& timeStep) const; /** return all time steps stored for the specified slice.*/ std::vector GetAvailableTimeSteps(const IndexValueType& slice) const; /** return all time steps stored in the property.*/ std::vector GetAvailableTimeSteps() const; - /** return all slices stored in the property. @Remark not all time steps may contain all slices.*/ + /** return all slices stored in the property. @remark not all time steps may contain all slices.*/ std::vector GetAvailableSlices() const; void SetValue(const TimeStepType &timeStep, const IndexValueType &zSlice, const ValueType &value); void SetValue(const ValueType &value); std::string GetValueAsString() const override; /** Inidicates of all values (all time steps, all slices) are the same, or if at least one value stored in the property is different. If IsUniform==true one can i.a. use GetValueAsString() without the loss of information to retrieve the stored value.*/ bool IsUniform() const; using BaseProperty::operator=; protected: typedef std::map SliceMapType; typedef std::map TimeMapType; TimeMapType m_Values; TemporoSpatialStringProperty(const char *string = nullptr); TemporoSpatialStringProperty(const std::string &s); TemporoSpatialStringProperty(const TemporoSpatialStringProperty &); std::pair CheckValue(const TimeStepType &timeStep, const IndexValueType &zSlice, bool allowCloseTime = false, bool allowCloseSlice = false) const; private: // purposely not implemented TemporoSpatialStringProperty &operator=(const TemporoSpatialStringProperty &); itk::LightObject::Pointer InternalClone() const override; bool IsEqual(const BaseProperty &property) const override; bool Assign(const BaseProperty &property) override; }; namespace PropertyPersistenceSerialization { /** Serialization of a TemporoSpatialStringProperty into a JSON string.*/ MITKCORE_EXPORT::std::string serializeTemporoSpatialStringPropertyToJSON(const mitk::BaseProperty *prop); } namespace PropertyPersistenceDeserialization { /**Deserialize a passed JSON string into a TemporoSpatialStringProperty.*/ MITKCORE_EXPORT mitk::BaseProperty::Pointer deserializeJSONToTemporoSpatialStringProperty(const std::string &value); } #ifdef _MSC_VER #pragma warning(pop) #endif } // namespace mitk #endif diff --git a/Modules/Core/include/mitkTransferFunction.h b/Modules/Core/include/mitkTransferFunction.h index 4416927203..9bcd312590 100644 --- a/Modules/Core/include/mitkTransferFunction.h +++ b/Modules/Core/include/mitkTransferFunction.h @@ -1,195 +1,195 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITK_TRANSFER_FUNCTION_H_HEADER_INCLUDED #define MITK_TRANSFER_FUNCTION_H_HEADER_INCLUDED #include "mitkHistogramGenerator.h" #include "mitkImage.h" #include #include #include #include #include #include #include #include #include #include namespace mitk { /** * @brief The TransferFunction class A wrapper class for VTK scalar opacity, * gradient opacity, and color transfer functions. * @ingroup DataManagement * * Holds a copy of each of the three standard VTK transfer functions (scalar * opacity, gradient opacity, color) and provides an interface for manipulating * their control points. Each original function can be retrieved by a Get() * method. * * @note Currently, transfer function initialization based on histograms or * computed-tomography-presets is also provided by this class, but will likely * be separated into a specific initializer class. * * @note If you want to use this as a property for an mitk::Image, make sure * to use the mitk::TransferFunctionProperty and set the mitk::RenderingModeProperty * to a mode which supports transfer functions (e.g. COLORTRANSFERFUNCTION_COLOR). * Make sure to check the documentation of the mitk::RenderingModeProperty. For a * code example how to use the mitk::TransferFunction check the - * mitkImageVtkMapper2DTransferFunctionTest.cpp in Core\Code\Testing. + * mitkImageVtkMapper2DTransferFunctionTest.cpp in Core/Code/Testing. */ class MITKCORE_EXPORT TransferFunction : public itk::Object { public: typedef std::vector> ControlPoints; typedef std::vector>> RGBControlPoints; mitkClassMacroItkParent(TransferFunction, itk::DataObject); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** \brief Get/Set min/max of transfer function range for initialization. */ itkSetMacro(Min, int); /** \brief Get/Set min/max of transfer function range for initialization. */ itkSetMacro(Max, int); /** \brief Get/Set min/max of transfer function range for initialization. */ itkGetMacro(Min, int); /** \brief Get/Set min/max of transfer function range for initialization. */ itkGetMacro(Max, int); /** \brief Get/Set wrapped vtk transfer function. */ itkGetMacro(ScalarOpacityFunction, vtkPiecewiseFunction *); /** \brief Get/Set wrapped vtk transfer function. */ itkGetMacro(GradientOpacityFunction, vtkPiecewiseFunction *); /** \brief Get/Set wrapped vtk transfer function. */ itkGetMacro(ColorTransferFunction, vtkColorTransferFunction *); itkSetMacro(ColorTransferFunction, vtkSmartPointer); /** \brief Get histogram used for transfer function initialization. */ itkGetConstObjectMacro(Histogram, HistogramGenerator::HistogramType); /** \brief Initialize transfer function based on the histogram of an mitk::Image. */ void InitializeByMitkImage(const mitk::Image *image); /** \brief Initialize transfer function based on the specified histogram. */ void InitializeByItkHistogram(const itk::Statistics::Histogram *histogram); /** \brief Initialize the internal histogram and min/max range based on the * specified mitk::Image. */ void InitializeHistogram(const mitk::Image *image); /** \brief Insert control points and values into the scalar opacity transfer * function. */ void SetScalarOpacityPoints(TransferFunction::ControlPoints points); /** \brief Insert control points and values into the gradient opacity transfer * function. */ void SetGradientOpacityPoints(TransferFunction::ControlPoints points); /** \brief Insert control points and RGB values into the color transfer * function. */ void SetRGBPoints(TransferFunction::RGBControlPoints rgbpoints); /** \brief Add a single control point to the scalar opacity transfer function. */ void AddScalarOpacityPoint(double x, double value); /** \brief Add a single control point to the gradient opacity transfer function. */ void AddGradientOpacityPoint(double x, double value); /** \brief Add a single control point to the color opacity transfer function. */ void AddRGBPoint(double x, double r, double g, double b); /** \brief Get a copy of the scalar opacity transfer function control-points. */ TransferFunction::ControlPoints &GetScalarOpacityPoints(); /** \brief Get a copy of the gradient opacity transfer function control-points. */ TransferFunction::ControlPoints &GetGradientOpacityPoints(); /** \brief Get a copy of the color transfer function control-points. */ TransferFunction::RGBControlPoints &GetRGBPoints(); /** \brief Remove the specified control point from the scalar opacity transfer * function. */ int RemoveScalarOpacityPoint(double x); /** \brief Remove the specified control point from the gradient opacity transfer * function. */ int RemoveGradientOpacityPoint(double x); /** \brief Remove the specified control point from the color transfer function. */ int RemoveRGBPoint(double x); /** \brief Removes all control points from the scalar opacity transfer function. */ void ClearScalarOpacityPoints(); /** \brief Removes all control points from the gradient opacity transfer * function. */ void ClearGradientOpacityPoints(); /** \brief Removes all control points from the color transfer function. */ void ClearRGBPoints(); bool operator==(Self &other); protected: TransferFunction(); ~TransferFunction() override; TransferFunction(const TransferFunction &other); itk::LightObject::Pointer InternalClone() const override; void PrintSelf(std::ostream &os, itk::Indent indent) const override; /** Wrapped VTK scalar opacity transfer function */ vtkSmartPointer m_ScalarOpacityFunction; /** Wrapped VTK gradient opacity transfer function */ vtkSmartPointer m_GradientOpacityFunction; /** Wrapped VTK color transfer function */ vtkSmartPointer m_ColorTransferFunction; /** Current range of transfer function (used for initialization) */ int m_Min; /** Current range of transfer function (used for initialization) */ int m_Max; /** Specified or calculated histogram (used for initialization) */ mitk::HistogramGenerator::HistogramType::ConstPointer m_Histogram; private: /** Temporary STL style copy of VTK internal control points */ TransferFunction::ControlPoints m_ScalarOpacityPoints; /** Temporary STL style copy of VTK internal control points */ TransferFunction::ControlPoints m_GradientOpacityPoints; /** Temporary STL style copy of VTK internal control points */ TransferFunction::RGBControlPoints m_RGBPoints; }; } #endif /* MITK_TRANSFER_FUNCTION_H_HEADER_INCLUDED */ diff --git a/Modules/Core/include/mitkTransferFunctionProperty.h b/Modules/Core/include/mitkTransferFunctionProperty.h index 2cb10185eb..4366e2ea8a 100644 --- a/Modules/Core/include/mitkTransferFunctionProperty.h +++ b/Modules/Core/include/mitkTransferFunctionProperty.h @@ -1,79 +1,79 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKTRANFERFUNCTIONPROPERTY_H_HEADER_INCLUDED #define MITKTRANFERFUNCTIONPROPERTY_H_HEADER_INCLUDED #include "mitkBaseProperty.h" #include "mitkTransferFunction.h" namespace mitk { #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4522) #endif /** * @brief The TransferFunctionProperty class Property class for the mitk::TransferFunction. * @ingroup DataManagement * * @note If you want to use this property for an mitk::Image, make sure * to set the mitk::RenderingModeProperty to a mode which supports transfer * functions (e.g. COLORTRANSFERFUNCTION_COLOR). Make sure to check the * documentation of the mitk::RenderingModeProperty. For a code example how * to use the mitk::TransferFunction check the - * mitkImageVtkMapper2DTransferFunctionTest.cpp in Core\Code\Testing. + * mitkImageVtkMapper2DTransferFunctionTest.cpp in Core/Code/Testing. */ class MITKCORE_EXPORT TransferFunctionProperty : public BaseProperty { public: typedef mitk::TransferFunction::Pointer ValueType; mitkClassMacro(TransferFunctionProperty, BaseProperty); itkFactorylessNewMacro(Self); itkCloneMacro(Self) mitkNewMacro1Param(TransferFunctionProperty, mitk::TransferFunction::Pointer); itkSetMacro(Value, mitk::TransferFunction::Pointer); itkGetConstMacro(Value, mitk::TransferFunction::Pointer); std::string GetValueAsString() const override; using BaseProperty::operator=; protected: mitk::TransferFunction::Pointer m_Value; TransferFunctionProperty(); TransferFunctionProperty(const TransferFunctionProperty &other); TransferFunctionProperty(mitk::TransferFunction::Pointer value); private: // purposely not implemented TransferFunctionProperty &operator=(const TransferFunctionProperty &); itk::LightObject::Pointer InternalClone() const override; bool IsEqual(const BaseProperty &property) const override; bool Assign(const BaseProperty &property) override; }; #ifdef _MSC_VER #pragma warning(pop) #endif } // namespace mitk #endif /* MITKTRANFERFUNCTIONPROPERTY_H_HEADER_INCLUDED */ diff --git a/Modules/IGT/Common/mitkIGTTimeStamp.h b/Modules/IGT/Common/mitkIGTTimeStamp.h index 5cc3223c6b..0a030dd564 100644 --- a/Modules/IGT/Common/mitkIGTTimeStamp.h +++ b/Modules/IGT/Common/mitkIGTTimeStamp.h @@ -1,186 +1,186 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKTIMESTAMP_H_HEADER_INCLUDED_ #define MITKTIMESTAMP_H_HEADER_INCLUDED_ #include #include #include #include "mitkRealTimeClock.h" namespace mitk { /** * \brief Time stamp in milliseconds * * This class provides a timestamp in milliseconds. * It is a Singleton class, that internally uses a mitkRealTimeClock() for * time-acquisition. * * First you have to call Start() in order to set the reference-time to the current time. * If the user has not created and set his own "RealTimeClock", initialize() will be called and a * default mitkRealTimeClock() is created. * In addition the TimeStamp() saves a pointer to the device calling and the respective offset-time. * The first device will have an offset of 0, the following's offset will be the time elapsed since the * starting of the first device. This offset can be prompted by calling GetOffset(); * * You can always get the time elapsed since calling Start() with GetElapsed(). It returns the * time spent in milliseconds as a double. * * When the TimeStamp is no longer used, you can call Stop(). This erases the pointer to the device * and the offset. When all devices have "stopped tracking" the reference-time and the current-time are reset to 0. * * \ingroup IGT */ class MITKIGT_EXPORT IGTTimeStamp : public itk::Object { public: mitkClassMacroItkParent(IGTTimeStamp, itk::Object); /** * \brief creates a new instance of mitkTimeStamp * * This method returns a pointer to the currently existing TimeStamp. * If there is no exisiting instance, a new one is created and returned automatically * * DECREPATED: Use GetInstance instead */ static IGTTimeStamp* CreateInstance(); /** * \brief returns a pointer to the current instance of mitkTimeStamp * * This method returns a pointer to the currently existing TimeStamp. * If there is no exisiting instance, a new one is created and returned automatically */ static IGTTimeStamp* GetInstance(); /** * \brief starts the time-acquisition * * Each device is to call this method when it starts tracking. * The current time is saved as a reference-value (m_Time = 0). * Internally the device (pointer) and its offset are saved in a map, so that * no device can call this method twice. * If the user has not set its own RealTimeClock, a default one is created dependant on the OS * in use. * */ void Start( itk::Object::Pointer device ); /** * \brief stops the time-acqusition * * Each device has to call Stop() when it has finished and its * pointer will be erased from the map. When the last device has "stopped" * the reference-time and the current-time will be reset to 0. * */ void Stop( itk::Object::Pointer device ); /** * \brief returns the time elapsed since calling Start() for the first time in milliseconds * * GetElapsed() returns the time elapsed since Start() has been called first, no matter * which itk::Object did the call. * This method-call can be used if you want to need to have several processes you want to * monitor and need timestamps in the same space of time, e.g. when using two tracking-devices * on the same experiment. */ double GetElapsed(); /** * \brief returns the time elapsed since 'device' called Start() in milliseconds * * GetElapsed(itk::Object device) returns the time elapsed since the given itk::Object called * Start(). * This overloaded method should be used when you only have one independent process to keep * track of, e.g. when you want to measure how long it takes to execute a piece of code. */ double GetElapsed(itk::Object::Pointer device); /** * \brief returns the offset of this device's starting-time to the * reference-time in ms * * Device 'A' is the first device to call Start(). Device 'B' calls Start() * some time later. This time-difference is the offset, that each device has realtive to the * device that started the time-acquisition. * Each device's offset is stored in a map with a pointer to the device. * * If this device has not been or is no longer saved in the map of devices, * -1 will be returned. * * * only used internally */ double GetOffset(itk::Object::Pointer Device); /** * \brief setter for the internally used RealTimeClock() * * If you want to use a "third-party" RealTimeClock, e.g PocoRealTimeClock, BoostRealTimeClock * or ITKRealTimeClock, you can set it using this method: - * mitk::RealTimeClock::Pointer RealTimeClock = mitk::RealTimeClock::New(); + * auto RealTimeClock = mitk::RealTimeClock::New(); * mitk::TimeStamp::GetInstance()->SetRealTimeClock(RealTimeClock); * * Right now, none of these RealTimeClocks have been implemented!! * * Notice: The mitk-implementation of an os-dependant RealTimeClock is used * by default. */ void SetRealTimeClock(mitk::RealTimeClock::Pointer Clock); /** * \brief creates a new RealTimeClock * * Instanciates a new RealTimeClock, that will be specific for the Operating System. * This will only be called internally when no other RealTimeClock has been set * by the user. * */ void Initialize(); protected: IGTTimeStamp(); ~IGTTimeStamp() override; double GetCurrentStamp(); /* the current timestamp when GetCurrentStamp() is called. */ double m_Time; /* the timestamp in ms acquired when Start() was called. */ double m_ReferenceTime; /* pointer to the RealTimeClock used internally */ mitk::RealTimeClock::Pointer m_RealTimeClock; /* pointer to the current instance */ static mitk::IGTTimeStamp::Pointer s_Instance; /* map, in which pointer to all devices calling Start(), are saved */ std::map m_DeviceMap; std::map::iterator m_MapIterator; }; } // namespace mitk #endif /* MITKTIMESTAMP_H_HEADER_INCLUDED_ */ diff --git a/Modules/IGT/TrackingDevices/mitkTrackingVolumeGenerator.h b/Modules/IGT/TrackingDevices/mitkTrackingVolumeGenerator.h index 2f0bcb232d..bb0c798f32 100644 --- a/Modules/IGT/TrackingDevices/mitkTrackingVolumeGenerator.h +++ b/Modules/IGT/TrackingDevices/mitkTrackingVolumeGenerator.h @@ -1,104 +1,104 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKTRACKINGVOLUMEGENERATOR_H #define MITKTRACKINGVOLUMEGENERATOR_H #include "MitkIGTExports.h" #include #include "mitkTrackingTypes.h" #include "mitkTrackingDevice.h" namespace mitk { /**Documentation * \brief An instance of this class represents a generator wich generates the tracking volume of a * given tracking device as a mitk:Surface. * * To generate the specific dimensions of the tracking volume of a tracking device * the methods SetTrackingDeviceType(trackingdevicetype) or SetTrackingDevice (tracker) have to be called first. Otherwise * the TrackingDeviceType is set to "TrackingSystemNotSpecified". * After setting the trackingdevice type, the update() method has to be called. * Now the method GetOutput() delivers the generatet TrackingVolume as mitk:Surface * * The coordinate system of die TrackingVolume is the same as the coordination system of the tracking device. * * For tracking devices that have a modifiable tracking volume (e.g. VirtualTrackingDevice, * this class produces a tracking volume with default values. * * \ingroup IGT */ class MITKIGT_EXPORT TrackingVolumeGenerator : public mitk::SurfaceSource { public: mitkClassMacro(TrackingVolumeGenerator, mitk::SurfaceSource); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** * \brief Deprecated! Use set DeviceData instead. * Sets the tracking device type of the volume. Warning: there are different possible volumes for some device types. * In this case a default volume is chosen automatically. All tracking volumes are defined by TrackingDeviceData * objects (see file mitkTrackingTypes.h) for a list. * * After setting the device type the tracking volume gets generated (by a default volume for this type as mentioned above) * and set to the correct dimensions in the correct coordinate system. The TV of a VirtualTrackingDevice is always a 400*400 cube. - * \param type The type of the tracking device (currently supported:NDIAurora, NDIPolaris, ClaronMicron, IntuitiveDaVinci and the VirtualTracker; see file mitkTrackingTypes.h for a always up to date list). + * \param deviceType The type of the tracking device (currently supported:NDIAurora, NDIPolaris, ClaronMicron, IntuitiveDaVinci and the VirtualTracker; see file mitkTrackingTypes.h for a always up to date list). */ void SetTrackingDeviceType(mitk::TrackingDeviceType deviceType); /** * \return Returns the tracking device type of the current device. Warning: there are different possible volumes for some device types. * Use GetTrackingDeviceData to get a unambiguous assignment to a tracking volume. */ mitk::TrackingDeviceType GetTrackingDeviceType() const; /** * \brief Sets the tracking device data object which will be used to generate the volume. Each tracking device data object * has an unambiguous assignment to a tracking volume. See file mitkTrackingTypes.h for a list of all availiable object. */ void SetTrackingDeviceData(mitk::TrackingDeviceData deviceData); /** * \return Returns the current tracking device data of the generator. See file mitkTrackingTypes.h for the definition of tracking device data objects. */ mitk::TrackingDeviceData GetTrackingDeviceData() const; /** * \brief Deprecated! Use set DeviceData instead. Sets the tracking device type of the volume. After doing this * the tracking volume gets generated and is set to the correct dimensions in the correct * coordinate system. The TV of a VirtualTrackingDevice is always a 400*400 cube. * \param tracker The tracking device the tracking volume has to be created for (currently supported: NDIAurora, NDIPolaris, ClaronMicron, IntuitiveDaVinci and the VirtualTracker; see file mitkTrackingTypes.h for a always up to date list). */ void SetTrackingDevice(mitk::TrackingDevice::Pointer tracker); protected: TrackingVolumeGenerator(); /** \brief Holds the current tracking device data object, which is used to generate the volume. */ mitk::TrackingDeviceData m_Data; void GenerateData() override; }; } #endif // MITKTRACKINGVOLUMEGENERATOR_H diff --git a/Modules/IGT/TrackingDevices/mitkVirtualTrackingDevice.h b/Modules/IGT/TrackingDevices/mitkVirtualTrackingDevice.h index 4787c43cea..704f0ca810 100644 --- a/Modules/IGT/TrackingDevices/mitkVirtualTrackingDevice.h +++ b/Modules/IGT/TrackingDevices/mitkVirtualTrackingDevice.h @@ -1,215 +1,215 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKVIRTUALTRACKINGDEVICE_H_HEADER_INCLUDED_ #define MITKVIRTUALTRACKINGDEVICE_H_HEADER_INCLUDED_ #include #include #include #include #include "itkFastMutexLock.h" #include namespace mitk { /** Documentation * \brief Class representing a tracking device which generates random positions / orientations. * No hardware is needed for tracking device. * * This TrackingDevice class does not interface with a physical tracking device. It simulates * a tracking device by moving the tools on a randomly generated spline path. * * \ingroup IGT */ class MITKIGT_EXPORT VirtualTrackingDevice : public TrackingDevice { public: mitkClassMacro(VirtualTrackingDevice, TrackingDevice); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** * \brief Sets the refresh rate of the virtual tracking device in ms * \warning This refresh rate is not guaranteed. A thread is used to refresh the positions * of the virtual tools. However, this thread may not run at all during this refresh time period. * \return Sets the refresh rate of the virtual tracking device in ms */ itkSetMacro(RefreshRate, unsigned int); /** * \brief Returns the refresh rate in ms. * \return Returns the refresh rate in ms. */ itkGetConstMacro(RefreshRate, unsigned int); /** * \brief Starts the tracking. * * After StartTracking() is called, * the tools will move on their spline paths with a constant velocity that can be set with * SetToolSpeed(). The standard velocity is 10 seconds for one complete cycle along the spline path. * \warning tool speed is not yet used in the current version * \return Returns true if the tracking is started. Returns false if there was an error. */ bool StartTracking() override; /** * \brief Stops the tracking. * \return Returns true if the tracking is stopped. Returns false if there was an error. */ bool StopTracking() override; /** * \brief Opens the connection to the device. This have to be done before the tracking is started. * @throw mitk::IGTException Throws an exception if there are two less control points to start the the virtual device. */ bool OpenConnection() override; /** * \brief Closes the connection and clears all resources. */ bool CloseConnection() override; /** * \return Returns the number of tools which have been added to the device. */ unsigned int GetToolCount() const override; /** * \param toolNumber The number of the tool which should be given back. * \return Returns the tool which the number "toolNumber". Returns nullptr, if there is * no tool with this number. */ TrackingTool* GetTool(unsigned int toolNumber) const override; /** * \brief Adds a tool to the tracking device. * * The tool will have a random path on which it will move around. The path is created with a * spline function and random control points inside the tracking volume. * * \param toolName The tool which will be added. * \return Returns true if the tool has been added, false otherwise. */ TrackingTool* AddTool(const char* toolName); /** * \brief Set the tracking volume bounds * * This will set the tracking volume as an axis aligned bounding box * defined by the six bounds values xMin, xMax, yMin, yMax, zMin, zMax. * Note that the random path of existing tools will not be updated with the new * tracking volume. Tools that are created after calling SetBounds() will use the * new tracking volume */ itkSetVectorMacro(Bounds, mitk::ScalarType, 6); /** * \brief return the tracking volume bounds * * This will return the tracking volume as an axis aligned bounding box * defined by the six bounds values xMin, xMax, yMin, yMax, zMin, zMax */ const mitk::ScalarType* GetBounds() const { return m_Bounds; }; /** * \brief return the approximate length of the spline for tool with index idx in millimeter * * if the index idx is not a * valid tool index, a std::invalid_argument exception is thrown. * GetSplineChordLength() returns the distance between all control points of the * spline in millimeter. This can be used as an approximation for the length of the spline path. */ mitk::ScalarType GetSplineChordLength(unsigned int idx); /** * \brief sets the speed of the tool idx in rounds per second * * The virtual tools will travel along a closed spline path. * This method sets the speed of a tool as a factor of how many rounds per second * the tool should move. A setting of 1.0 will indicate one complete round per second. * Together with GetSplineChordLength(), the speed in millimeter per second can be estimated. * roundsPerSecond must be positive and larger than 0.0001. * \warning Tool speed is currently not used. - * \TODO: use tool speed + * \todo use tool speed */ void SetToolSpeed(unsigned int idx, mitk::ScalarType roundsPerSecond); /** * \brief enable addition of Gaussian Noise to tracking coordinates */ void EnableGaussianNoise(); /** * \brief disable addition of Gaussian Noise to Trackin coordinates */ void DisableGaussianNoise(); /** * \brief sets the mean distribution and the standard deviation for the Gaussian Noise * */ void SetParamsForGaussianNoise(double meanDistribution, double deviationDistribution); /** * \brief returns the mean distribution for the Gaussian Noise */ double GetMeanDistribution(); /** * \brief returns the deviation distribution for the Gaussian Noise */ double GetDeviationDistribution(); protected: VirtualTrackingDevice(); ~VirtualTrackingDevice() override; /** * \brief This method tracks tools as long as the variable m_Mode is set to "Tracking". * Tracking tools means generating random numbers for the tool position and orientation. * @throw mitk::IGTException Throws an mitk::IGTException if there is an error during virtual tool tracking. */ void TrackTools(); void InitializeSpline(mitk::VirtualTrackingTool* t); ///< initializes the spline path of the tool t with random control points inside the current tracking volume static ITK_THREAD_RETURN_TYPE ThreadStartTracking(void* data); ///< static start method for tracking thread typedef mitk::VirtualTrackingTool::SplineType::ControlPointType ControlPointType; ControlPointType GetRandomPoint(); ///< returns a random position inside the tracking volume (defined by m_Bounds) mitk::VirtualTrackingTool* GetInternalTool(unsigned int idx); typedef std::vector ToolContainer; ///< container type for tracking tools ToolContainer m_AllTools; ///< container for all tracking tools itk::FastMutexLock::Pointer m_ToolsMutex; ///< mutex for coordinated access of tool container itk::MultiThreader::Pointer m_MultiThreader; ///< MultiThreader that starts continuous tracking update int m_ThreadID; unsigned int m_RefreshRate; ///< refresh rate of the internal tracking thread in milliseconds (NOT refreshs per second!) unsigned int m_NumberOfControlPoints; ///< number of control points for the random path generation mitk::ScalarType m_Bounds[6]; ///< bounding box of the tracking volume stored as {xMin, xMax, yMin, yMax, zMin, zMax} bool m_GaussianNoiseEnabled; ///< adding Gaussian Noise to tracking coordinates or not, false by default double m_MeanDistributionParam; /// mean distribution for Gaussion Noise, 0.0 by default double m_DeviationDistributionParam; ///< deviation distribution for Gaussian Noise, 1.0 by default }; }//mitk #endif /* MITKVIRTUALTRACKINGDEVICE_H_HEADER_INCLUDED_ */ diff --git a/Modules/IGTBase/include/mitkStaticIGTHelperFunctions.h b/Modules/IGTBase/include/mitkStaticIGTHelperFunctions.h index 17af38482e..dba34e2ce8 100644 --- a/Modules/IGTBase/include/mitkStaticIGTHelperFunctions.h +++ b/Modules/IGTBase/include/mitkStaticIGTHelperFunctions.h @@ -1,49 +1,51 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include #include #include #include "MitkIGTBaseExports.h" #include #include #include namespace mitk { class MITKIGTBASE_EXPORT StaticIGTHelperFunctions { public: /** Computes the angle in the plane perpendicular to the rotation axis of the two quaterions. * Therefore, a vector is rotated with the difference of both rotations and the angle is computed. * In some cases you might want to define this vector e.g., if working with 5D tools. For NDI Aurora * 5D tools you need to defined this vector along the Z-axis. * @return Returns the angle in degrees. **/ static double GetAngleBetweenTwoQuaterions(mitk::Quaternion a, mitk::Quaternion b, itk::Vector rotationVector); /** Computes difference between two quaternions in degree, which is the minimum rotation angle between * these two quaternions. * The used formula is described here: https://fgiesen.wordpress.com/2013/01/07/small-note-on-quaternion-distance-metrics/ * @return Returns the angle in degrees. **/ static double GetAngleBetweenTwoQuaterions(mitk::Quaternion a, mitk::Quaternion b); /** Converts euler angles (in degrees) to a rotation matrix. */ static itk::Matrix ConvertEulerAnglesToRotationMatrix(double alpha, double beta, double gamma); /** @brief Computes the fiducial registration error out of two sets of fiducials. * The two sets must have the same size and the points must correspond to each other. + * @param imageFiducials + * @param realWorldFiducials * @param transform This transform is applied to the image fiducials before the FRE calculation if it is given. * @return Returns the FRE. Returns -1 if there was an error. */ static double ComputeFRE(mitk::PointSet::Pointer imageFiducials, mitk::PointSet::Pointer realWorldFiducials, vtkSmartPointer transform = nullptr); }; } diff --git a/Modules/ModelFit/include/mitkModelFitCmdAppsHelper.h b/Modules/ModelFit/include/mitkModelFitCmdAppsHelper.h index c1803478a4..5cc65983a5 100644 --- a/Modules/ModelFit/include/mitkModelFitCmdAppsHelper.h +++ b/Modules/ModelFit/include/mitkModelFitCmdAppsHelper.h @@ -1,56 +1,56 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _MITK_MODEL_FIT_CMD_APPS_HELPER_H_ #define _MITK_MODEL_FIT_CMD_APPS_HELPER_H_ // std includes #include // itk includes #include "itksys/SystemTools.hxx" // MITK includes #include #include #include #include #include "MitkModelFitExports.h" namespace mitk { /** Helper function that generates the file path that would be used to store an result image. The output path will be determined given the outputPathTemplate (which determines the directory, the basic file name and the file formate). The output file name is: _.*/ MITKMODELFIT_EXPORT std::string generateModelFitResultImagePath(const std::string& outputPathTemplate, const std::string& parameterName); /** Helper function that takes the given image and stores it based on a template path. The real output path will be determined given the outputPathTemplate (which determines the directory, the basic file name and the file formate). The output file name is: _.*/ MITKMODELFIT_EXPORT void storeParameterResultImage(const std::string& outputPathTemplate, const std::string& parameterName, mitk::Image* image, mitk::modelFit::Parameter::Type parameterType = mitk::modelFit::Parameter::ParameterType); /** Helper function that takes the given image, sets its properties according to the fit session and stores it. The output path will be determined given the outputPathTemplate (which determines the directory, - the basic file name and the file formate). The output file name is: _.*/ + the basic file name and the file formate). The output file name is: \_\.\*/ MITKMODELFIT_EXPORT void storeModelFitResultImage(const std::string& outputPathTemplate, const std::string& parameterName, mitk::Image* image, mitk::modelFit::Parameter::Type nodeType, const mitk::modelFit::ModelFitInfo* modelFitInfo); /** Helper function that stores all results of the passed generator according to the passed outputPathTemplate. For further information regarding the output file path, please see storeModelFitResultImage().*/ MITKMODELFIT_EXPORT void storeModelFitGeneratorResults(const std::string& outputPathTemplate, mitk::ParameterFitImageGeneratorBase* generator, const mitk::modelFit::ModelFitInfo* fitSession); /** Helper function that outputs on the std::cout the result images the generator would produces.*/ MITKMODELFIT_EXPORT void previewModelFitGeneratorResults(const std::string& outputPathTemplate, mitk::ParameterFitImageGeneratorBase* generator); } #endif diff --git a/Modules/ModelFit/include/mitkModelFitInfo.h b/Modules/ModelFit/include/mitkModelFitInfo.h index fd88278c91..b9e849c7b9 100644 --- a/Modules/ModelFit/include/mitkModelFitInfo.h +++ b/Modules/ModelFit/include/mitkModelFitInfo.h @@ -1,199 +1,198 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkModelFitInfo_h #define mitkModelFitInfo_h #include #include #include #include "mitkModelFitConstants.h" #include "mitkModelFitParameter.h" #include "mitkModelFitStaticParameterMap.h" #include "mitkScalarListLookupTable.h" #include "mitkModelParameterizerBase.h" #include "mitkModelTraitsInterface.h" #include "MitkModelFitExports.h" namespace mitk { namespace modelFit { /** * @brief Data class that stores all information about a modelfit that is relevant to the * visualization and stored as properties in the result nodes. */ class MITKMODELFIT_EXPORT ModelFitInfo : public itk::LightObject { public: typedef std::string UIDType; typedef std::vector ParamListType; typedef ParamListType::const_iterator ConstIterType; mitkClassMacroItkParent(ModelFitInfo, itk::LightObject); itkSimpleNewMacro(ModelFitInfo); ModelFitInfo() : x(mitk::ModelFitConstants::MODEL_X_VALUE_DEFAULT()), xAxisName(mitk::ModelFitConstants::XAXIS_NAME_VALUE_DEFAULT()), yAxisName(mitk::ModelFitConstants::YAXIS_NAME_VALUE_DEFAULT()) { } /** * @brief Adds the given parameter to this fit's parameter list if it doesn't * exist already. * @param p The param that should be added to this fit's parameter list. */ void AddParameter(Parameter::Pointer p); /** * @brief Searches for the parameter with the given name and type in the fit's * parameter list and returns it. * @param name The name of the desired parameter. * @param type The type of the desired parameter. * @return The parameter with the given name on success or NULL otherwise. */ Parameter::ConstPointer GetParameter(const std::string& name, const Parameter::Type& type) const; /** * @brief Searches for the parameter with the given name and type in the fit's * parameter list and deletes it if it exists. * @param name The name of the desired parameter. * @param type The type of the desired parameter. */ void DeleteParameter(const std::string& name, const Parameter::Type& type); /**Return const reference to the parameter list.*/ const ParamListType& GetParameters() const; /** ModelFitConstants::MODEL_NAME_PROPERTY_NAME */ std::string modelName; /** ModelFitConstants::MODEL_TYPE_PROPERTY_NAME */ std::string modelType; /** ModelFitConstants::MODEL_FUNCTION_PROPERTY_NAME */ std::string function; /** ModelFitConstants::MODEL_FUNCTION_CLASS_PROPERTY_NAME */ std::string functionClassID; /** ModelFitConstants::MODEL_X_PROPERTY_NAME */ std::string x; /** ModelFitConstants::XAXIS_NAME_PROPERTY_NAME */ std::string xAxisName; /** ModelFitConstants::XAXIS_UNIT_PROPERTY_NAME */ std::string xAxisUnit; /** ModelFitConstants::YAXIS_NAME_PROPERTY_NAME */ std::string yAxisName; /** ModelFitConstants::YAXIS_UNIT_PROPERTY_NAME */ std::string yAxisUnit; /** ModelFitConstants::FIT_UID_PROPERTY_NAME */ UIDType uid; /** ModelFitConstants::FIT_NAME_PROPERTY_NAME */ std::string fitName; /** ModelFitConstants::FIT_TYPE_PROPERTY_NAME */ std::string fitType; /** ModelFitConstants::FIT_STATIC_PARAMETERS_PROPERTY_NAME */ StaticParameterMap staticParamMap; /** ModelFitConstants::FIT_INPUT_ROIUID_PROPERTY_NAME */ UIDType roiUID; /** ModelFitConstants::FIT_INPUT_DATA_PROPERTY_NAME */ ScalarListLookupTable inputData; mitk::Image::ConstPointer inputImage; private: typedef ParamListType::iterator IterType; typedef itk::MutexLockHolder LockType; ParamListType parameterList; itk::SimpleFastMutexLock mutex; }; /** * @brief Reads the string property with the given name from the data of the given node * and returns its value. Throws a ModelFitException if the property doesn't exist. * @param node The node whose property value should be returned. * @param prop The name of the property that should be read. * @return The value of the found property. * @throw ModelFitException If the property doesn't exist or returns an empty string. */ MITKMODELFIT_EXPORT const std::string GetMandatoryProperty(const mitk::DataNode* node, const std::string& prop); /** * @brief Reads the string property with the given name from the given base data and * returns its value. Throws a ModelFitException if the property doesn't exist. * @param data The data whose property value should be returned. * @param prop The name of the property that should be read. * @return The value of the found property. * @throw ModelFitException If the property doesn't exist or returns an empty string. */ MITKMODELFIT_EXPORT const std::string GetMandatoryProperty(const mitk::BaseData* data, const std::string& prop); /** * @brief Creates a new ModelFitInfo instance from the nodes in the passed storage. * The fit will be identified by the passed UID. Returns the instance on * success. * @param uid The uid of the fit that should get its ModelFitInfo created and which identifies the nodes in the storage. * @param storage Pointer to the data storage containing any potential relevantThe nodes. * @return The newly created modelfit on success or NULL otherwise. */ MITKMODELFIT_EXPORT ModelFitInfo::Pointer CreateFitInfoFromNode(const ModelFitInfo::UIDType& uid, const mitk::DataStorage* storage); /** creates a new ModelFitInfo instance from a passed modal instance and his traits instance* - * @param usedModel Pointer to a model which was used for a fit, which should get a fit info created. - * @param modelTraits Pointer to traits interface for the model that was used for the fit. + * @param usedParameterizer Pointer to a model which was used for a fit, which should get a fit info created. * @param inputImage Pointer to the input image. If it has no UID yet, a property will be added to the node. * @param fitType String identifying the type of the fit (e.g. ROI based or voxel based) * @param fitName Optional human readable name of the fit. * @param roiUID UID of the ROI, if one was used. * @return The newly created modelfit on success or NULL otherwise.*/ MITKMODELFIT_EXPORT ModelFitInfo::Pointer CreateFitInfoFromModelParameterizer( const ModelParameterizerBase* usedParameterizer, mitk::BaseData* inputImage, const std::string& fitType, const std::string& fitName = "", const ModelFitInfo::UIDType& roiUID = ""); /** @overload Overloaded version that allows additional definition of optional input data for the fit.*/ MITKMODELFIT_EXPORT ModelFitInfo::Pointer CreateFitInfoFromModelParameterizer( const ModelParameterizerBase* usedParameterizer, mitk::BaseData* inputImage, const std::string& fitType, const ScalarListLookupTable& inputData, const std::string& fitName = "", const ModelFitInfo::UIDType& roiUID = ""); /** Returns all nodes that belong to the fit indicated by the passed UID. * @param fitUID The uid of the fit that is relevant for the query. * @param storage Pointer to the data storage containing any potential relevant nodes. * @return The set of found nodes or null if storage is not valid. */ MITKMODELFIT_EXPORT DataStorage::SetOfObjects::ConstPointer GetNodesOfFit( const ModelFitInfo::UIDType& fitUID, const mitk::DataStorage* storage); typedef std::set NodeUIDSetType; /** Returns the UIDs of all fits that are derived (directly or indirectly from the passed node). * @param node The node which defines the parent node. It will be searched in his derived nodes for fits. * @param storage Pointer to the data storage containing any potential relevant nodes. * @return The set of found uid will be returned. */ MITKMODELFIT_EXPORT NodeUIDSetType GetFitUIDsOfNode(const mitk::DataNode* node, const mitk::DataStorage* storage); } } #endif // mitkModelFit_h diff --git a/Modules/ModelFit/include/mitkModelFitStaticParameterMap.h b/Modules/ModelFit/include/mitkModelFitStaticParameterMap.h index ab8bf7e9c9..170f08326e 100644 --- a/Modules/ModelFit/include/mitkModelFitStaticParameterMap.h +++ b/Modules/ModelFit/include/mitkModelFitStaticParameterMap.h @@ -1,146 +1,146 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkModelFitStaticParameterMap_h #define mitkModelFitStaticParameterMap_h #include #include #include #include "MitkModelFitExports.h" #include "mitkModelBase.h" namespace mitk { namespace modelFit { /** Data structure that is used to store information about the static parameters of a model fit*/ class MITKMODELFIT_EXPORT StaticParameterMap { private: /** @brief Type of the map key */ typedef ModelBase::ParameterNameType KeyType; public: /** @brief Type of the map value */ typedef ModelBase::StaticParameterValuesType ValueType; /** @brief Type of a variable, consisting of name and value list */ typedef std::pair StaticParameterType; private: /** @brief Type of the map */ typedef ModelBase::StaticParameterMapType MapType; /* @brief Stores the variables with their value lists */ MapType m_map; /** * @brief Stores the number of values that each list (which contains more than one * value) contains. */ unsigned int m_numValues; public: /** @brief Needed for 'foreach' support */ typedef MapType::const_iterator const_iterator; StaticParameterMap() : m_numValues(1) {} /** * @brief Adds the given value list under the given variable name if the name * doesn't exist already. If it does exist, nothing is added. * @pre The given list must contain either 1 or n values, where n is the * amount of values that lists contain which are already part of the * map (and contain more than one value). That means if the map is * empty or contains only lists that have only one value each, this * rule doesn't apply. An exception is thrown otherwise. * @param name The name of the variable to which the values should be added. * @param newList The value list that should be added. * @throw ModelFitException If the given list contains an amount of values that is * greater than 1 and doesn't match the amount of values * of the lists that are already part of the map (see * pre-condition). */ void Add(const std::string& name, const ValueType& newList); /** * @brief Returns the values of the given variable name. * @param name The name of the variables whose values should be returned. * @return The values of the given variable name. * @throw std::range_error If the variable name doesn't exist. */ const ValueType& Get(const std::string& name) const; MapType::size_type Size() const { return m_map.size(); } const_iterator begin() const { return m_map.begin(); } const_iterator end() const { return m_map.end(); } /** * @brief Sorts the values of the given variable name in ascending order. The * values of all other variables will also be switched in that specific * order. If name is empty or the variable could not be found, the map is * ordered by the first variable that contains more than one value (also in * ascending order). * @details Example: - *
  • Before sorting: - * "A": [3, 2, 5, 1, 4] - * "B": [0] - * "C": [3, 4, 1, 5, 2] - *
  • Sort(): - * "A": [1, 2, 3, 4, 5] - * "B": [0] - * "C": [5, 4, 3, 2, 1] - *
  • Sort("B"): - * "A": [5, 4, 3, 2, 1] - * "B": [0] - * "C": [1, 2, 3, 4, 5] - *
  • Sort("X"): - * "A": [1, 2, 3, 4, 5] - * "B": [0] - * "C": [5, 4, 3, 2, 1] + * - Before sorting: + * - "A": [3, 2, 5, 1, 4] + * - "B": [0] + * - "C": [3, 4, 1, 5, 2] + * - Sort(): + * - "A": [1, 2, 3, 4, 5] + * - "B": [0] + * - "C": [5, 4, 3, 2, 1] + * - Sort("B"): + * - "A": [5, 4, 3, 2, 1] + * - "B": [0] + * - "C": [1, 2, 3, 4, 5] + * - Sort("X"): + * - "A": [1, 2, 3, 4, 5] + * - "B": [0] + * - "C": [5, 4, 3, 2, 1] * @param name The name of the variable the map should be sorted by. */ void Sort(const std::string& name = ""); /** * @brief Resets the map, so it's empty. */ void Clear(); }; /** * @brief Compares two var lists and returns true if the first list's first item is * lower than the second one's. * @param a The first list to compare the other one to. * @param b The other list to compare the first one to. * @return True if the first list's first item is smaller than the second one's. */ inline bool operator<(const StaticParameterMap::ValueType& a, const StaticParameterMap::ValueType& b) { return (a.front() < b.front()); } } } #endif // mitkModelFitStaticParameterMap_h diff --git a/Modules/Pharmacokinetics/include/mitkConvolutionHelper.h b/Modules/Pharmacokinetics/include/mitkConvolutionHelper.h index 86b1538d1d..2951af672c 100644 --- a/Modules/Pharmacokinetics/include/mitkConvolutionHelper.h +++ b/Modules/Pharmacokinetics/include/mitkConvolutionHelper.h @@ -1,153 +1,154 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkConvolutionHelper_h #define mitkConvolutionHelper_h #include "itkArray.h" #include "mitkAIFBasedModelBase.h" #include #include "MitkPharmacokineticsExports.h" namespace mitk { /** @namespace convolution * @brief Helper for itk implementation of vnl fourier transformation * This namespace provides functions for the preperation of vnl_fft_1d, including a wrapper * for wrapping the convolution kernel (turning it inside out) and a function for zeropadding * to avoid convolution artefacts. */ namespace convolution { /** Some typedefs concerning data structures needed for vnl_fft_1d, which has vnl_vector< vcl_complex< double > > * as output typ of the forward transformation fwd_transform. Input is of type vnl_vector< vcl_complex< T > > * but since itk::Array is derived from vnl_vector, this works as well*/ /** @brief Function that wraps the kernel */ inline itk::Array wrap1d(itk::Array kernel) { int dim = kernel.GetNumberOfElements(); itk::Array wrappedKernel(dim); wrappedKernel.fill(0.); for(int i=0; i< dim; ++i) { wrappedKernel.SetElement(i, kernel.GetElement((i+(dim/2))%dim)); } return wrappedKernel; } /** @brief Fuction for zeropadding (adding zeros) of an Array/vnl_vector, so that is has size paddedDimensions - * @param paddedDimensions Dimensions that the Array should have after padding (convolution dimensions) + * @param unpaddedSpectrum + * @param paddedDimension Dimensions that the Array should have after padding (convolution dimensions) * \remark dim = Dimensions of padded image --> PaddedDimension * \remark m dimensions of larger image * \remark n dimensions of image to be padded --> InitialDimension*/ inline itk::Array zeropadding1d(itk::Array unpaddedSpectrum, int paddedDimension) { int initialDimension = unpaddedSpectrum.GetNumberOfElements(); itk::Array paddedSpectrum(paddedDimension); paddedSpectrum.fill(0.); if(paddedDimension > initialDimension) { unsigned int padding = paddedDimension - initialDimension; for(int i=0; i unpadAndScale(itk::Array convolutionResult, int initialDimension) { int transformationDimension = convolutionResult.size(); unsigned int padding = transformationDimension - initialDimension; itk::Array scaledResult(initialDimension); scaledResult.fill(0.0); for(int i = 0; i >, ready to * be entered in fwd_transform*/ inline void prepareConvolution(const itk::Array& kernel, const itk::Array& spectrum, itk::Array& preparedKernel, itk::Array& preparedSpectrum ){ int convolutionDimensions = kernel.GetSize() + spectrum.GetSize(); // itk::Array paddedKernel = zeropadding1d(kernel,convolutionDimensions); preparedKernel=zeropadding1d(kernel,convolutionDimensions); preparedSpectrum = zeropadding1d(spectrum,convolutionDimensions); // preparedKernel = wrap1d(paddedKernel); } } inline itk::Array convoluteAIFWithExponential(mitk::ModelBase::TimeGridType timeGrid, mitk::AIFBasedModelBase::AterialInputFunctionType aif, double lambda) { /** @brief Iterative Formula to Convolve aif(t) with an exponential Residuefunction R(t) = exp(lambda*t) **/ typedef itk::Array ConvolutionResultType; ConvolutionResultType convolution(timeGrid.GetSize()); convolution.fill(0.0); convolution(0) = 0; for(unsigned int i = 0; i< (timeGrid.GetSize()-1); ++i) { double dt = timeGrid(i+1) - timeGrid(i); double m = (aif(i+1) - aif(i))/dt; double edt = exp(-lambda *dt); convolution(i+1) =edt * convolution(i) + (aif(i) - m*timeGrid(i))/lambda * (1 - edt ) + m/(lambda * lambda) * ((lambda * timeGrid(i+1) - 1) - edt*(lambda*timeGrid(i) -1)); } return convolution; } inline itk::Array convoluteAIFWithConstant(mitk::ModelBase::TimeGridType timeGrid, mitk::AIFBasedModelBase::AterialInputFunctionType aif, double constant) { /** @brief Iterative Formula to Convolve aif(t) with a constant value by linear interpolation of the Aif between sampling points **/ typedef itk::Array ConvolutionResultType; ConvolutionResultType convolution(timeGrid.GetSize()); convolution.fill(0.0); convolution(0) = 0; for(unsigned int i = 0; i< (timeGrid.GetSize()-1); ++i) { double dt = timeGrid(i+1) - timeGrid(i); double m = (aif(i+1) - aif(i))/dt; convolution(i+1) = convolution(i) + constant * (aif(i)*dt + m*timeGrid(i)*dt + m/2*(timeGrid(i+1)*timeGrid(i+1) - timeGrid(i)*timeGrid(i))); } return convolution; } } #endif // mitkConvolutionHelper_h diff --git a/Modules/Pharmacokinetics/include/mitkTwoTissueCompartmentModelFactoryBase.h b/Modules/Pharmacokinetics/include/mitkTwoTissueCompartmentModelFactoryBase.h index fe8a4bf029..9a8b81a4bc 100644 --- a/Modules/Pharmacokinetics/include/mitkTwoTissueCompartmentModelFactoryBase.h +++ b/Modules/Pharmacokinetics/include/mitkTwoTissueCompartmentModelFactoryBase.h @@ -1,81 +1,81 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKTWOTISSUECOMPARTMENTFACTORYBASE_H #define MITKTWOTISSUECOMPARTMENTFACTORYBASE_H #include "mitkConcreteAIFBasedModelFactory.h" #include "mitkAIFBasedModelParameterizerBase.h" #include "mitkSimpleBarrierConstraintChecker.h" namespace mitk { template class TwoTissueCompartmentModelFactoryBase : public mitk::ConcreteAIFBasedModelFactory< TModelParameterizer > { public: mitkClassMacro(TwoTissueCompartmentModelFactoryBase, ConcreteAIFBasedModelFactory< TModelParameterizer >); itkFactorylessNewMacro(Self); typedef typename Superclass::ModelType ModelType; typedef typename Superclass::ModelParameterizerType ModelParameterizerType; typedef typename Superclass::ParametersType ParametersType; ConstraintCheckerBase::Pointer CreateDefaultConstraints() const override { SimpleBarrierConstraintChecker::Pointer constraints = SimpleBarrierConstraintChecker::New(); - /**@TODO: Mit Charlie klaren ob es eine sinnvolle default Einstellung gibt.*/ + /**@todo Mit Charlie klaren ob es eine sinnvolle default Einstellung gibt.*/ constraints->SetLowerBarrier(ModelType::POSITION_PARAMETER_K1, 0, 0); constraints->SetLowerBarrier(ModelType::POSITION_PARAMETER_k2, 0, 0); constraints->SetLowerBarrier(ModelType::POSITION_PARAMETER_k3, 0, 0); constraints->SetLowerBarrier(ModelType::POSITION_PARAMETER_k4, 0, 0); constraints->SetLowerBarrier(ModelType::POSITION_PARAMETER_VB, 0, 0); constraints->SetUpperBarrier(ModelType::POSITION_PARAMETER_VB, 1, 0); constraints->SetUpperBarrier(ModelType::POSITION_PARAMETER_K1, 1.0, 0); constraints->SetUpperBarrier(ModelType::POSITION_PARAMETER_k2, 1.0, 0); constraints->SetUpperBarrier(ModelType::POSITION_PARAMETER_k3, 1.0, 0); constraints->SetUpperBarrier(ModelType::POSITION_PARAMETER_k4, 1.0, 0); return constraints.GetPointer(); }; ParametersType GetDefaultInitialParameterization() const override { typename ModelParameterizerType::Pointer modelParameterizer = ModelParameterizerType::New(); return modelParameterizer->GetDefaultInitialParameterization(); }; protected: TwoTissueCompartmentModelFactoryBase() { }; ~TwoTissueCompartmentModelFactoryBase() override { }; private: //No copy constructor allowed TwoTissueCompartmentModelFactoryBase(const Self& source); void operator=(const Self&); //purposely not implemented }; } #endif // MITKTWOCOMPARTMENTEXCHANGEMODELFACTORY_H diff --git a/Modules/PhotoacousticsLib/include/mitkPAComposedVolume.h b/Modules/PhotoacousticsLib/include/mitkPAComposedVolume.h index b41915ef83..da76c63790 100644 --- a/Modules/PhotoacousticsLib/include/mitkPAComposedVolume.h +++ b/Modules/PhotoacousticsLib/include/mitkPAComposedVolume.h @@ -1,86 +1,86 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKPHOTOACOUSTICCOMPOSEDVOLUME_H #define MITKPHOTOACOUSTICCOMPOSEDVOLUME_H #include #include #include #include //Includes for smart pointer usage #include "mitkCommon.h" #include "itkLightObject.h" namespace mitk { namespace pa { /** * @brief The ComposedVolume class provides the means to systematically collect nrrd files that correspond to * different simulation slices of the same InSilicoTissueVolume. * * An instance of this class is needed for the SlicedVolumeGenerator */ class MITKPHOTOACOUSTICSLIB_EXPORT ComposedVolume : public itk::Object { public: mitkClassMacroItkParent(ComposedVolume, itk::Object); mitkNewMacro1Param(Self, InSilicoTissueVolume::Pointer); /** * @brief fluenceYOffsetPair * - * @param nrrdFile path to the nrrd file on hard drive + * @param fluenceYOffsetPair */ void AddSlice(mitk::pa::FluenceYOffsetPair::Pointer fluenceYOffsetPair); /** * @brief GetNumberOfFluenceComponents * @return the number of fluence components encapsuled by this ComposedVolume. */ int GetNumberOfFluenceComponents(); /** * @brief GetFluenceValue * @param fluenceComponent * @param x * @param y * @param z * @return the fluence value for a specific fluence component index at the given 3D location. */ double GetFluenceValue(int fluenceComponent, int x, int y, int z); /** * @brief GetYOffsetForFluenceComponentInPixels * @param fluenceComponent * @return the y-offset value for a given fluence component index. */ int GetYOffsetForFluenceComponentInPixels(int fluenceComponent); void Sort(); itkGetMacro(GroundTruthVolume, InSilicoTissueVolume::Pointer); protected: ComposedVolume(InSilicoTissueVolume::Pointer groundTruthVolume); ~ComposedVolume() override; private: int m_FluenceComponents; InSilicoTissueVolume::Pointer m_GroundTruthVolume; std::vector m_FluenceValues; }; } } #endif // MITKPHOTOACOUSTICCOMPOSEDVOLUME_H diff --git a/Modules/PhotoacousticsLib/include/mitkPAIOUtil.h b/Modules/PhotoacousticsLib/include/mitkPAIOUtil.h index bc86c01a38..d2a5d01b19 100644 --- a/Modules/PhotoacousticsLib/include/mitkPAIOUtil.h +++ b/Modules/PhotoacousticsLib/include/mitkPAIOUtil.h @@ -1,119 +1,120 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKPHOTOACOUSTICIO_H #define MITKPHOTOACOUSTICIO_H #include "MitkPhotoacousticsLibExports.h" #include #include #include //Includes for smart pointer usage #include "mitkCommon.h" #include "itkLightObject.h" #include "mitkPAVolume.h" #include #include namespace mitk { namespace pa { class MITKPHOTOACOUSTICSLIB_EXPORT IOUtil final { public: struct Position { int x, z; bool operator <(const Position& rhs) const { return (x < rhs.x || ((x == rhs.x) && z < rhs.z)); } }; /** * @brief LoadFluenceContributionMaps loads multiple nrrd files from a given folder * and sorts them into a position map if such meta information is available in * the filename. * * As this method was specifically designed to load many fluence files, the * naming convention for the position values is: * * *_pN,N,NFluence*.nrrd * * @param foldername * @param blur * @param progress + * @param log10 * * @return */ static std::map LoadFluenceContributionMaps( std::string foldername, double blur, int* progress, bool log10 = false); /** * @brief loads a nrrd file from a given filename. * @param filename * @param sigma * @return nullptr if the given filename was invalid. */ static Volume::Pointer LoadNrrd(std::string filename, double sigma = 0); /** *@brief returns the number of .nrrd files in a given directory */ static int GetNumberOfNrrdFilesInDirectory(std::string directory); /** *@brief returns a list of all .nrrd files in a given directory */ static std::vector GetListOfAllNrrdFilesInDirectory( std::string directory, bool keepFileFormat = false); /** *@brief convenience method to check wether a given strings ends on a given substring. *@return false if the substring is longer than the string or if the strings are empty. */ static bool DoesFileHaveEnding(std::string const &fullString, std::string const &ending); /** *@brief returns all child folders from a folder if there is no .nrrd file in the folder * If there IS a .nrrd file in the folder this method will return the given folder path. */ static std::vector GetAllChildfoldersFromFolder(std::string folderPath); /** *@brief loads an in silico tissue volume from a saved nrrd file. */ static InSilicoTissueVolume::Pointer LoadInSilicoTissueVolumeFromNrrdFile(std::string filePath); /** * @brief LoadFluenceSimulation * Adds a MC Simulation nrrd file to this composed volume. * The given file needs to contain the meta information "y-offset". * This method ensures that all added slices are in the correct order * corresponding to their y-offset. * - * @param nrrdFile path to the nrrd file on hard drive + * @param fluenceSimulation path to the nrrd file on hard drive */ static FluenceYOffsetPair::Pointer LoadFluenceSimulation(std::string fluenceSimulation); private: IOUtil(); ~IOUtil(); }; } } #endif // MITKPHOTOACOUSTICIO_H diff --git a/Modules/PhotoacousticsLib/include/mitkPALinearSpectralUnmixingFilter.h b/Modules/PhotoacousticsLib/include/mitkPALinearSpectralUnmixingFilter.h index fa03b40789..c62b88d87b 100644 --- a/Modules/PhotoacousticsLib/include/mitkPALinearSpectralUnmixingFilter.h +++ b/Modules/PhotoacousticsLib/include/mitkPALinearSpectralUnmixingFilter.h @@ -1,100 +1,100 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKLINEARPHOTOACOUSTICSPECTRALUNMIXINGFILTER_H #define MITKLINEARPHOTOACOUSTICSPECTRALUNMIXINGFILTER_H #include #include namespace mitk { namespace pa { /** * \brief This filter is subclass of the spectral unmixing filter base. All algorithms in this class are * based on the Eigen open source c++ library. It takes a multispectral pixel as input and returns a vector * with the unmixing result. * * Input: * - endmemberMatrix Eigen Matrix with number of chromophores colums and number of wavelengths rows so matrix element (i,j) contains * the absorbtion of chromophore j @ wavelength i taken from the database by PropertyElement method. * - inputVector Eigen Vector containing values of one pixel of XY-plane image with number of wavelength rows (z-dimension of a sequenece) * so the pixelvalue of the first wavelength is stored in inputVector[0] and so on. * * Output: * - Eigen vector with unmixing result of one multispectral pixel. The ith element of the vector corresponds to the ith entry of the * m_Chromophore vector. * * Algorithms (see AlgortihmType enum): * - HOUSEHOLDERQR computes the solution by QR decomposition * - COLPIVHOUSEHOLDERQR computes the solution by QR decomposition * - FULLPIVHOUSEHOLDERQR computes the solution by QR decomposition * - LDLT computes the solution by Cholesky decomposition * - LLT computes the solution by Cholesky decomposition * - JACOBISVD computes the solution by singular value decomposition uses least square solver * * Possible exceptions: * - "algorithm not working": doesn't work now (2018/06/19) * - "404 VIGRA ALGORITHM NOT FOUND": Algorithm not implemented */ class MITKPHOTOACOUSTICSLIB_EXPORT LinearSpectralUnmixingFilter : public SpectralUnmixingFilterBase { public: mitkClassMacro(LinearSpectralUnmixingFilter, SpectralUnmixingFilterBase); itkFactorylessNewMacro(Self); /** * \brief Contains all implemented Eigen algorithms for spectral unmixing. For detailed information of the algorithms look at the * mitkPALinearSpectralUnmixingFilter.h documentation (section Algorithms). */ enum AlgortihmType { HOUSEHOLDERQR, LDLT, LLT, COLPIVHOUSEHOLDERQR, JACOBISVD, FULLPIVLU, FULLPIVHOUSEHOLDERQR }; /** * \brief Takes a mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType and fix it for usage at the "SpectralUnmixingAlgorithm" method. - * @param algorithmName has to be a mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType + * @param inputAlgorithmName has to be a mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType */ void SetAlgorithm(AlgortihmType inputAlgorithmName); protected: LinearSpectralUnmixingFilter(); ~LinearSpectralUnmixingFilter() override; /** * \brief overrides the baseclass method with a mehtod to calculate the spectral unmixing result vector. Herain the class performs the * algorithm set by the "SetAlgorithm" method and writes the result into a Eigen vector which is the return value. * @param endmemberMatrix Matrix with number of chromophores colums and number of wavelengths rows so matrix element (i,j) contains * the absorbtion of chromophore j @ wavelength i taken from the database by PropertyElement method. * @param inputVector Vector containing values of one pixel of XY-plane image with number of wavelength rows (z-dimension of a sequenece) * so the pixelvalue of the first wavelength is stored in inputVector[0] and so on. * @throws if the algorithmName is not a member of the enum VigraAlgortihmType * @throws if one chooses the ldlt/llt solver which doens't work yet */ Eigen::VectorXf SpectralUnmixingAlgorithm(Eigen::Matrix endmemberMatrix, Eigen::VectorXf inputVector) override; private: AlgortihmType algorithmName; }; } } #endif // MITKLINEARPHOTOACOUSTICSPECTRALUNMIXINGFILTER_H diff --git a/Modules/PhotoacousticsLib/include/mitkPASpectralUnmixingFilterBase.h b/Modules/PhotoacousticsLib/include/mitkPASpectralUnmixingFilterBase.h index 9dc1fcdf0c..80fc069e09 100644 --- a/Modules/PhotoacousticsLib/include/mitkPASpectralUnmixingFilterBase.h +++ b/Modules/PhotoacousticsLib/include/mitkPASpectralUnmixingFilterBase.h @@ -1,194 +1,194 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKPHOTOACOUSTICSPECTRALUNMIXINGFILTERBASE_H #define MITKPHOTOACOUSTICSPECTRALUNMIXINGFILTERBASE_H #include "mitkImageToImageFilter.h" #include //Includes for smart pointer usage #include "mitkCommon.h" #include "itkLightObject.h" // Includes for AddEnmemberMatrix #include "mitkPAPropertyCalculator.h" #include namespace mitk { namespace pa { /** * \brief The spectral unmixing filter base is designed as superclass for several spectral unmixing filter eg. Eigen- or Vigrabased ones. * One can add wavelengths and chromophores and get a unmixed output images out of one MITK input image using algorithms from the subclasses. * * Input: * The unmixing input has to be a 3D MITK image where the XY-plane is a image and the Z-direction represents recordings for different * wavelengths. Herein a XY-plane for a specific Z-direction will be called "image". Every image has to be assigned to a certain wavelength. * The "AddWavelength" uses "push_back" to write float values into a vector. The first wavelength will correspond to the first image!!! * If there a more input images 'I' then added wavelengths 'w' the filter base interprets the next x images as repetition sequence of the same * wavelengths. If I % w !=0 the surplus image(s) will be dropped. * Addtionaly one has to add chromophores from the property calculator class enum "ChromophoreType" with the "AddChromophore" method. * This method as well uses "push_back" but the chosen (arbitary) order will be the order of the outputs. * * Output: * The output will be one MITK image per chosen chromophore. Where the XY-plane is a image and the Z-direction represents recordings for different * sequences. Furthermore it is possible to creat an output image that contains the information about the relative error between unmixing result * and the input image. * * Subclasses: * - mitkPASpectralUnmixingFilterVigra * - mitkPALinearSpectralUnmixingFilter (uses Eigen algorithms) * - mitkPASpectralUnmixingFilterSimplex * * Possible exceptions: * - "PIXELTYPE ERROR! FLOAT 32 REQUIRED": The MITK input image has to consist out of floats. * - "ERROR! REMOVE WAVELENGTHS!": One needs at least the same amount of images (z-dimension) then added wavelengths. * - "ADD MORE WAVELENGTHS!": One needs at least the same amount of wavelengths then added chromophores. * - "WAVELENGTH XXX nm NOT SUPPORTED!": The wavelength is not part of the proptery calculater data base. The data base can be found @ - * [...]\mitk\Modules\PhotoacousticsLib\Resources\spectralLIB.dat + * [...]/mitk/Modules/PhotoacousticsLib/Resources/spectralLIB.dat * - "ADD OUTPUTS HAS TO BE LARGER THEN ZERO!" * - "NO WAVELENGHTS/CHROMOPHORES SELECZED! * - "INDEX ERROR! NUMBER OF OUTPUTS DOESN'T FIT TO OTHER SETTIGNS!" */ class MITKPHOTOACOUSTICSLIB_EXPORT SpectralUnmixingFilterBase : public mitk::ImageToImageFilter { public: mitkClassMacro(SpectralUnmixingFilterBase, mitk::ImageToImageFilter); /** * \brief AddChromophore takes mitk::pa::PropertyCalculator::ChromophoreType and writes them at the end of the m_Chromophore vector. * The call of the method sets the order of the GetOutput method! * * @param chromophore has to be element of porperty calculater enum chromophore type * @return for wavelength smaller then 300nm and larger then 1000nm the return will be 0, because not at the data base (2018/06/19) */ void AddChromophore(mitk::pa::PropertyCalculator::ChromophoreType chromophore); /** * \brief AddWavelength takes integers and writes them at the end of the m_Wavelength vector. The first call of the method then * corresponds to the first input image and so on. * @param wavelength database supports integers between 300 and 1000 nm */ void AddWavelength(int wavelength); /* * \brief Verbose gives more information to the console. Default value is false. * @param verbose is the boolian to activate the MITK_INFO logged to the console */ virtual void Verbose(bool verbose); /** * \brief AddOutputs takes an integer and sets indexed outputs * @param outputs integer correponds to the number of output images * @throws if outputs == 0 */ virtual void AddOutputs(unsigned int outputs); /* * \brief RelativeError returns a image which compare the L2 norm of the input vector with the unmixing result * @param relativeError is the boolian to activate this tool */ virtual void RelativeError(bool relativeError); /** * \brief AddRelativeErrorSettings takes integers and writes them at the end of the m_RelativeErrorSettings vector. * @param value has to be a integer */ virtual void AddRelativeErrorSettings(int value); ofstream myfile; // just for testing purposes; has to be removeed protected: /** * \brief Constructor creats proptery calculater smart pointer new() */ SpectralUnmixingFilterBase(); ~SpectralUnmixingFilterBase() override; /** * \brief The subclasses will override the mehtod to calculate the spectral unmixing result vector. * @param endmemberMatrix Matrix with number of chromophores colums and number of wavelengths rows so matrix element (i,j) contains * the absorbtion of chromophore j @ wavelength i taken from the database by PropertyElement method. * @param inputVector Vector containing values of one pixel of XY-plane image with number of wavelength rows (z-dimension of a sequenece) * so the pixelvalue of the first wavelength is stored in inputVector[0] and so on. * @throws if algorithm implementiation fails (implemented for the algorithms with critical requirements) */ virtual Eigen::VectorXf SpectralUnmixingAlgorithm(Eigen::Matrix endmemberMatrix, Eigen::VectorXf inputVector) = 0; bool m_Verbose = false; bool m_RelativeError = false; std::vector m_Chromophore; std::vector m_Wavelength; std::vector m_RelativeErrorSettings; private: /* * \brief Initialized output images with the same XY-plane size like the input image and total size in z-direction equals number of sequences. * The pixel type is set to float. * @param totalNumberOfSequences = (unsigned int) (numberOfInputImages / numberOfWavelength) >= 1 */ virtual void InitializeOutputs(unsigned int totalNumberOfSequences); /* * \brief Checks if there are a suitable amount of wavelengths and if the input image consists of floats. * @param input pointer on the MITK input image * @throws if there are more wavelength then images * @throws if there are more chromophores then wavelengths * @throws if the pixel type is not float 32 * @throws if no chromophores or wavelengths selected as input * @throws if the number of indexed outputs does'nt fit to the expected number */ virtual void CheckPreConditions(mitk::Image::Pointer input); /* * \brief Inherit from the "ImageToImageFilter" Superclass. Herain it calls InitializeOutputs, CalculateEndmemberMatrix and * CheckPreConditions methods and enables pixelwise access to do spectral unmixing with the "SpectralUnmixingAlgorithm" * method. In the end the method writes the results into the new MITK output images. */ void GenerateData() override; /* * \brief Creats a Matrix with number of chromophores colums and number of wavelengths rows so matrix element (i,j) contains * the absorbtion of chromophore j @ wavelength i. The absorbtion values are taken from the "PropertyElement" method. * @param m_Chromophore is a vector of "PropertyCalculator::ChromophoreType" containing all selected chromophores for the unmixing * @param m_Wavelength is a vector of integers containing all wavelengths of one sequence */ virtual Eigen::Matrix CalculateEndmemberMatrix( std::vector m_Chromophore, std::vector m_Wavelength); /* * \brief "PropertyElement" is the tool to access the absorbtion values out of the database using mitk::pa::PropertyCalculator::GetAbsorptionForWavelengt * and checks if the requested wavelength is part of the database (not zero values). The "ONEENDMEMBER" is a pseudo absorber with static absorbtion 1 * at every wavelength and is therefor not part of the database. If this one is the selected chromophore the return value is 1 for every wavelength. * @param wavelength has to be integer between 300 and 1000 nm * @param chromophore has to be a mitk::pa::PropertyCalculator::ChromophoreType * @throws if mitk::pa::PropertyCalculator::GetAbsorptionForWavelengt returns 0, because this means that the delivered wavelength is not in the database. */ virtual float PropertyElement(mitk::pa::PropertyCalculator::ChromophoreType, int wavelength); /* * \brief calculates the relative error between the input image and the unmixing result in the L2 norm * @param endmemberMatrix is a Eigen matrix containing the endmember information * @param inputVector is a Eigen vector containing the multispectral information of one pixel * @param resultVector is a Eigen vector containing the spectral unmmixing result */ float CalculateRelativeError(Eigen::Matrix endmemberMatrix, Eigen::VectorXf inputVector, Eigen::VectorXf resultVector); PropertyCalculator::Pointer m_PropertyCalculatorEigen; }; } } #endif // MITKPHOTOACOUSTICSPECTRALUNMIXINGFILTERBASE_ diff --git a/Modules/PhotoacousticsLib/include/mitkPASpectralUnmixingFilterVigra.h b/Modules/PhotoacousticsLib/include/mitkPASpectralUnmixingFilterVigra.h index 24b8cae547..f6d8f638b3 100644 --- a/Modules/PhotoacousticsLib/include/mitkPASpectralUnmixingFilterVigra.h +++ b/Modules/PhotoacousticsLib/include/mitkPASpectralUnmixingFilterVigra.h @@ -1,104 +1,104 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKPHOTOACOUSTICSPECTRALUNMIXINGFILTERVIGRA_H #define MITKPHOTOACOUSTICSPECTRALUNMIXINGFILTERVIGRA_H #include #include #include namespace mitk { namespace pa { /** * \brief This filter is subclass of the spectral unmixing filter base. All algorithms in this class are * based on the vigra open source c++ library. It takes a multispectral pixel as input and returns a vector * with the unmixing result. * * Input: * - endmemberMatrix Eigen Matrix with number of chromophores colums and number of wavelengths rows so matrix element (i,j) contains * the absorbtion of chromophore j @ wavelength i taken from the database by PropertyElement method. * - inputVector Eigen Vector containing values of one pixel of XY-plane image with number of wavelength rows (z-dimension of a sequenece) * so the pixelvalue of the first wavelength is stored in inputVector[0] and so on. * * Output: * - Eigen vector with unmixing result of one multispectral pixel. The ith element of the vector corresponds to the ith entry of the * m_Chromophore vector. * * Algorithms (see VigraAlgortihmType enum): * - LARS algorithm minimizes (A*x-b)^2 s.t. x>=0 using least angle regression * - GOLDFARB minimizes (A*x-b)^2 s.t. x>=0 using the Goldfarb-Idnani algorithm * - WEIGHTED minimizes transpose(A*x-b)*diag(weights)*(A*x-b) using QR decomposition * - LS minimizes (A*x-b)^2 using QR decomposition * * Possible exceptions: * - "404 VIGRA ALGORITHM NOT FOUND": Algorithm not implemented */ class MITKPHOTOACOUSTICSLIB_EXPORT SpectralUnmixingFilterVigra : public SpectralUnmixingFilterBase { public: mitkClassMacro(SpectralUnmixingFilterVigra, SpectralUnmixingFilterBase); itkFactorylessNewMacro(Self); /** * \brief Contains all implemented Vigra algorithms for spectral unmixing. For detailed information of the algorithms look at the * mitkPASpectralUnmixingFilterVigra.h documentation (section Algorithms). */ enum VigraAlgortihmType { LARS, GOLDFARB, WEIGHTED, LS }; /** * \brief AddWeight takes integers and writes them at the end of the weightsvec vector. The first call of the method then * corresponds to the first input image/wavelength and so on. * @param weight is a percentage (integer) between 1 and 100 */ void AddWeight(unsigned int weight); /** * \brief Takes a mitk::pa::SpectralUnmixingFilterVigra::VigraAlgortihmType and fix it for usage at the "SpectralUnmixingAlgorithm" * method. - * @param algorithmName has to be a mitk::pa::SpectralUnmixingFilterVigra::VigraAlgortihmType + * @param inputAlgorithmName has to be a mitk::pa::SpectralUnmixingFilterVigra::VigraAlgortihmType */ void SetAlgorithm(VigraAlgortihmType inputAlgorithmName); protected: SpectralUnmixingFilterVigra(); ~SpectralUnmixingFilterVigra() override; /** * \brief overrides the baseclass method with a mehtod to calculate the spectral unmixing result vector. Herain it first converts the * Eigen inputs to the Vigra class. Afterwards the class performs the algorithm set by the "SetAlgorithm" method and writes the result * into a Eigen vector which is the return value. - * @param endmemberMatrix Matrix with number of chromophores colums and number of wavelengths rows so matrix element (i,j) contains + * @param EndmemberMatrix Matrix with number of chromophores colums and number of wavelengths rows so matrix element (i,j) contains * the absorbtion of chromophore j @ wavelength i taken from the database by PropertyElement method. * @param inputVector Vector containing values of one pixel of XY-plane image with number of wavelength rows (z-dimension of a sequenece) * so the pixelvalue of the first wavelength is stored in inputVector[0] and so on. * @throws if the algorithmName is not a member of the enum VigraAlgortihmType */ Eigen::VectorXf SpectralUnmixingAlgorithm(Eigen::Matrix EndmemberMatrix, Eigen::VectorXf inputVector) override; private: std::vector weightsvec; SpectralUnmixingFilterVigra::VigraAlgortihmType algorithmName; }; } } #endif // MITKPHOTOACOUSTICSPECTRALUNMIXINGFILTERVIGRA_H diff --git a/Modules/PhotoacousticsLib/include/mitkPASpectralUnmixingSO2.h b/Modules/PhotoacousticsLib/include/mitkPASpectralUnmixingSO2.h index 4104269af6..a1b90efcf6 100644 --- a/Modules/PhotoacousticsLib/include/mitkPASpectralUnmixingSO2.h +++ b/Modules/PhotoacousticsLib/include/mitkPASpectralUnmixingSO2.h @@ -1,112 +1,112 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKPHOTOACOUSTICSPECTRALUNMIXINGSO2_H #define MITKPHOTOACOUSTICSPECTRALUNMIXINGSO2_H #include "mitkImageToImageFilter.h" #include //Includes for smart pointer usage #include "mitkCommon.h" #include "itkLightObject.h" namespace mitk { namespace pa { /** * \brief derives out of two identical sized MITK images the oxygen saturation and return one MITK image as result. Furthermore * it is possible to set settings that the result shows just SO2 values above a threshold, or above a input value for Hb, HbO2 to * get just a oxygen saturation image of interessting structures. * * Input: * The input has to be two 3D MITK images. The order of the inputs matter! The first input has to be the Hb image the second input * has to be the HbO2 image. The settings are integer values. The SO2 threshold therefore is percentage value. * * Output: * The output will be one MITK image. Where one can see the oxygen saturation of all pixels above the set threholds. If a pixel is * below a threhold or NAN then the value will be set to zero. * * UPDATE: SO2 Filter will get an second output, the total hemoglobin value with ->GetOutput(1). */ class MITKPHOTOACOUSTICSLIB_EXPORT SpectralUnmixingSO2 : public mitk::ImageToImageFilter { public: mitkClassMacro(SpectralUnmixingSO2, mitk::ImageToImageFilter); itkFactorylessNewMacro(Self); /** * \brief AddSO2Settings takes integers and writes them at the end of the m_SO2Settings vector. * @param value of the Setting */ virtual void AddSO2Settings(int value); /** * \brief Verbose gives more information to the console. Default value is false. - * @param m_Verbose is the boolian to activate the MITK_INFO logged to the console + * @param verbose is the boolian to activate the MITK_INFO logged to the console */ virtual void Verbose(bool verbose); protected: /** * \brief Constructor sets number of input images to two and number of output images to one, respectively. */ SpectralUnmixingSO2(); ~SpectralUnmixingSO2() override; std::vector m_SO2Settings; bool m_Verbose = false; private: /** * \brief Inherit from the "ImageToImageFilter" Superclass. Herain it calls InitializeOutputs and the CheckPreConditions * methods and enables pixelwise access to the inputs to calculate the oxygen saturation via the "calculate SO2" method. */ void GenerateData() override; /** * \brief Initialized output images with the same size like the input image. The pixel type is set to float. */ virtual void InitializeOutputs(); /** * \brief Checks if the dimensions of the input images are equal and made out of floating poinhts. * @throws if the inputs don't have the same size * @throws if input images don't consist of floats */ virtual void CheckPreConditions(mitk::Image::Pointer inputHbO2, mitk::Image::Pointer inputHb); /** * \brief calculates HbO2 / (Hb + HbO2) and afterwards checks if the result is significant (SO2ValueNotSiginificant method). * If not the method returns zero otherwise it returns the calculated result. * @param pixelHb is the pixel value of the Hb input. * @param pixelHb is the pixel value of the Hb input. * @warn if the sO2 value is NAN (in patricular if Hb == -HbO2), but result will be set to zero */ float CalculateSO2(float pixelHb, float pixelHbO2); /** * \brief calculates (Hb + HbO2). * @param pixelHb is the pixel value of the Hb input. * @param pixelHb is the pixel value of the Hb input. * @warn if the tHb value is NAN (in patricular if Hb == -HbO2), but result will be set to zero */ float CalculateTHb(float pixelHb, float pixelHbO2); /** * \brief return true if SO2 result is not significant by checking if the input values are above the threshold of the settings */ bool SO2ValueNotSiginificant(float Hb, float HbO2, float result); }; } } #endif // MITKPHOTOACOUSTICSPECTRALUNMIXINGSO2_ diff --git a/Modules/PhotoacousticsLib/include/mitkPAVector.h b/Modules/PhotoacousticsLib/include/mitkPAVector.h index 0134624acd..3b25bf6b1c 100644 --- a/Modules/PhotoacousticsLib/include/mitkPAVector.h +++ b/Modules/PhotoacousticsLib/include/mitkPAVector.h @@ -1,132 +1,137 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKSMARTVECTOR_H #define MITKSMARTVECTOR_H #include #include #include //Includes for smart pointer usage #include "mitkCommon.h" #include "itkLightObject.h" namespace mitk { namespace pa { class MITKPHOTOACOUSTICSLIB_EXPORT Vector : public itk::LightObject { public: mitkClassMacroItkParent(Vector, itk::LightObject); itkFactorylessNewMacro(Self); /** * @brief GetNorm calculates the length of this vector. * @return the euclidean norm */ double GetNorm(); double GetElement(unsigned short index); void SetElement(unsigned short index, double value); /** * @brief Normalize normalizes this vector. After calling this GetNorm() will return 1. */ void Normalize(); void SetValue(Vector::Pointer value); /** * @brief RandomizeByPercentage alters this vector randomly by [-percentage, percentage] of the bendingFactor. * * @param percentage * @param bendingFactor + * @param rng */ void RandomizeByPercentage(double percentage, double bendingFactor, std::mt19937* rng); /** * @brief Randomize randomizes this vector to be [lowerLimit, upperLimit] in each element * * @param xLowerLimit * @param xUpperLimit * @param yLowerLimit * @param yUpperLimit * @param zLowerLimit * @param zUpperLimit + * @param rng */ void Randomize(double xLowerLimit, double xUpperLimit, double yLowerLimit, double yUpperLimit, double zLowerLimit, double zUpperLimit, std::mt19937* rng); /** * @brief Randomize randomizes this vector to be [0, limit] in each element * * @param xLimit * @param yLimit * @param zLimit + * @param rng */ void Randomize(double xLimit, double yLimit, double zLimit, std::mt19937* rng); /** * @brief Randomize randomizes this vector to be [-1, 1] in each element + * + * @param rng */ void Randomize(std::mt19937* rng); /** * @brief Rotate rotates this Vector around the x, y and z axis with the given angles in radians * - * @param thetaChange rotation of the inclination angle in radians - * @param phiChange rotation of the azimuthal angle in radians + * @param xAngle rotation of the inclination angle in radians + * @param yAngle rotation of the azimuthal angle in radians */ void Rotate(double xAngle, double yAngle); /** * @brief Scale scales this Vector with the given factor * * @param factor the scaling factor * * If a negative number is provided, the direction of the vector will be inverted. */ void Scale(double factor); /** * @brief Clone create a deep copy of this vector * * @return a new vector with the same values. */ Vector::Pointer Clone(); void Subtract(Vector::Pointer other); void Add(Vector::Pointer other); protected: Vector(); ~Vector() override; void PrintSelf(std::ostream& os, itk::Indent indent) const override; private: mitk::Vector3D m_Vector; }; /** * @brief Equal A function comparing two vectors for beeing equal * * @param rightHandSide A Vector to be compared * @param leftHandSide A Vector to be compared * @param eps tolarence for comparison. You can use mitk::eps in most cases. * @param verbose flag indicating if the user wants detailed console output or not. * @return true, if all subsequent comparisons are true, false otherwise */ MITKPHOTOACOUSTICSLIB_EXPORT bool Equal(const Vector::Pointer leftHandSide, const Vector::Pointer rightHandSide, double eps, bool verbose); } } #endif // MITKSMARTVECTOR_H diff --git a/Modules/PhotoacousticsLib/include/mitkPAVessel.h b/Modules/PhotoacousticsLib/include/mitkPAVessel.h index 18e929d23a..d75d0ed68c 100644 --- a/Modules/PhotoacousticsLib/include/mitkPAVessel.h +++ b/Modules/PhotoacousticsLib/include/mitkPAVessel.h @@ -1,113 +1,114 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKVESSEL_H #define MITKVESSEL_H #include "mitkVector.h" #include "mitkPAVesselMeanderStrategy.h" #include "mitkPAInSilicoTissueVolume.h" #include "mitkPAVector.h" #include "mitkPAVesselProperties.h" #include "mitkPAVesselDrawer.h" #include //Includes for smart pointer usage #include "mitkCommon.h" #include "itkLightObject.h" namespace mitk { namespace pa { class MITKPHOTOACOUSTICSLIB_EXPORT Vessel : public itk::LightObject { public: mitkClassMacroItkParent(Vessel, itk::LightObject); mitkNewMacro1Param(Self, VesselProperties::Pointer); /** * Callback function definition of a VesselMeanderStrategy */ typedef void (VesselMeanderStrategy::*CalculateNewVesselPositionCallback) (Vector::Pointer, double, std::mt19937*); /** * @brief ExpandVessel makes this Vessel expand one step in its current direction. * After expanding, the vessel will draw itself into the given InSilicoTissueVolume. * * @param volume volume for the vessel to draw itself in * @param calculateNewPosition a callback function of the VesselMeanderStrategy class. * It is used to calculate the final position after taking the step. * @param bendingFactor a metric of how much the Vessel should bend. If set to 0 the vessel will go in a straight line. + * @param rng */ void ExpandVessel(mitk::pa::InSilicoTissueVolume::Pointer volume, CalculateNewVesselPositionCallback calculateNewPosition, double bendingFactor, std::mt19937* rng); /** * @brief CanBifurcate * @return true if the Vessel is ready to Bifurcate() */ bool CanBifurcate(); /** * @brief Bifurcate bifurcates this vessel into two new ones. Makes sure that the volume of the vessels stays the same. * * @return a new vessel split up from the current one. */ Vessel::Pointer Bifurcate(std::mt19937* rng); /** * @brief IsFinished * @return true if the vessel cannot expand any further */ bool IsFinished(); itkGetConstMacro(VesselProperties, VesselProperties::Pointer); protected: Vessel(VesselProperties::Pointer parameters); ~Vessel() override; private: const double MINIMUM_VESSEL_RADIUS = 0.1; const double NEW_RADIUS_MINIMUM_RELATIVE_SIZE = 0.6; const double NEW_RADIUS_MAXIMUM_RELATIVE_SIZE = 0.8; VesselMeanderStrategy::Pointer m_VesselMeanderStrategy; bool m_Finished; double m_WalkedDistance; std::uniform_real_distribution<> m_RangeDistribution; std::uniform_real_distribution<> m_SignDistribution; std::uniform_real_distribution<> m_RadiusRangeDistribution; int GetSign(std::mt19937* rng); VesselProperties::Pointer m_VesselProperties; VesselDrawer::Pointer m_VesselDrawer; }; /** * @brief Equal A function comparing two vessels for beeing equal * * @param rightHandSide A vessel to be compared * @param leftHandSide A vessel to be compared * @param eps tolarence for comparison. You can use mitk::eps in most cases. * @param verbose flag indicating if the user wants detailed console output or not. * @return true, if all subsequent comparisons are true, false otherwise */ MITKPHOTOACOUSTICSLIB_EXPORT bool Equal(const Vessel::Pointer leftHandSide, const Vessel::Pointer rightHandSide, double eps, bool verbose); } } #endif // MITKVESSEL_H diff --git a/Modules/PhotoacousticsLib/include/mitkPAVesselMeanderStrategy.h b/Modules/PhotoacousticsLib/include/mitkPAVesselMeanderStrategy.h index e6b249c8a5..f8f551ba83 100644 --- a/Modules/PhotoacousticsLib/include/mitkPAVesselMeanderStrategy.h +++ b/Modules/PhotoacousticsLib/include/mitkPAVesselMeanderStrategy.h @@ -1,58 +1,60 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKVESSELMEANDERSTRATEGY_H #define MITKVESSELMEANDERSTRATEGY_H #include "mitkVector.h" #include "mitkPAVector.h" #include //Includes for smart pointer usage #include "mitkCommon.h" #include "itkLightObject.h" namespace mitk { namespace pa { class MITKPHOTOACOUSTICSLIB_EXPORT VesselMeanderStrategy : public itk::LightObject { public: mitkClassMacroItkParent(VesselMeanderStrategy, itk::LightObject); itkFactorylessNewMacro(Self); /** * @brief CalculateNewPositionInStraightLine calculates the new position by just following the direction vector. * @param direction * @param bendingFactor + * @param rng */ void CalculateNewDirectionVectorInStraightLine(Vector::Pointer direction, double bendingFactor, std::mt19937* rng); /** * @brief CalculateRandomlyDivergingPosition calculates the new position by modifying the direction vector randomly, * proportional to the selected bendingFactor. This means, that the vessels will bend in each expansion step, * if bendingFactor > 0. * * @param direction * @param bendingFactor + * @param rng */ void CalculateNewRandomlyDivergingDirectionVector(Vector::Pointer direction, double bendingFactor, std::mt19937* rng); protected: VesselMeanderStrategy(); ~VesselMeanderStrategy() override; const double RANDOMIZATION_PERCENTAGE = 0.4; }; } } #endif // MITKVESSELMEANDERSTRATEGY_H diff --git a/Modules/PhotoacousticsLib/include/mitkPAVesselTree.h b/Modules/PhotoacousticsLib/include/mitkPAVesselTree.h index 5a51cd2823..dbef42e6d9 100644 --- a/Modules/PhotoacousticsLib/include/mitkPAVesselTree.h +++ b/Modules/PhotoacousticsLib/include/mitkPAVesselTree.h @@ -1,66 +1,67 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKVESSELSTRUCTURE_H #define MITKVESSELSTRUCTURE_H //std includes #include //mitk includes #include "mitkPAVessel.h" #include "mitkPAInSilicoTissueVolume.h" #include //Includes for smart pointer usage #include "mitkCommon.h" #include "itkLightObject.h" namespace mitk { namespace pa { class MITKPHOTOACOUSTICSLIB_EXPORT VesselTree : public itk::LightObject { public: mitkClassMacroItkParent(VesselTree, itk::LightObject); mitkNewMacro1Param(Self, VesselProperties::Pointer); /** * @brief Step Performs a simulation step, in which all subvessels of this VesselTree are expanded. * * @param volume * @param calculateNewPosition * @param bendingFactor + * @param rng */ void Step(InSilicoTissueVolume::Pointer volume, Vessel::CalculateNewVesselPositionCallback calculateNewPosition, double bendingFactor, std::mt19937* rng); /** * @brief IsFinished * @return true if no subvessel can be expanded. */ bool IsFinished(); itkGetConstMacro(CurrentSubvessels, std::vector*); protected: VesselTree(VesselProperties::Pointer initialProperties); ~VesselTree() override; private: std::vector* m_CurrentSubvessels; }; MITKPHOTOACOUSTICSLIB_EXPORT bool Equal(const VesselTree::Pointer leftHandSide, const VesselTree::Pointer rightHandSide, double eps, bool verbose); } } #endif // MITKVESSELSTRUCTURE_H diff --git a/Modules/PhotoacousticsLib/include/mitkPAVolume.h b/Modules/PhotoacousticsLib/include/mitkPAVolume.h index 1984519645..059b4df280 100644 --- a/Modules/PhotoacousticsLib/include/mitkPAVolume.h +++ b/Modules/PhotoacousticsLib/include/mitkPAVolume.h @@ -1,146 +1,147 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKPHOTOACOUSTIC3dVOLUME_H #define MITKPHOTOACOUSTIC3dVOLUME_H #include "MitkPhotoacousticsLibExports.h" //Includes for smart pointer usage #include #include namespace mitk { namespace pa { /** * @brief The Volume class is designed to encapsulate volumetric information and to provide convenience methods * for data access and image conversions. */ class MITKPHOTOACOUSTICSLIB_EXPORT Volume : public itk::LightObject { public: mitkClassMacroItkParent(Volume, itk::LightObject); /** *@brief returns smartpointer reference to a new instance of this objects. * The given data array will be freed upon calling this constructor. *@param data *@param xDim *@param yDim *@param zDim *@param spacing *@return smartpointer reference to a new instance of this object */ static Volume::Pointer New(double* data, unsigned int xDim, unsigned int yDim, unsigned int zDim, double spacing); static Volume::Pointer New(mitk::Image::Pointer image); /** * @brief GetData. Returns data at wanted position. For performance reasons, this method will not check, * if the specified position it within the array. Please use the GetXDim(), GetYDim() and GetZDim() methods * to check for yourself if necessary. * * @param x * @param y * @param z * @return the data contained within the data array held by this Volume at * positon x|y|z. */ double GetData(unsigned int x, unsigned int y, unsigned int z); /** * Returns a const reference to the data encapsuled by this class. */ double* GetData() const; /** * @brief SetData * @param data * @param x * @param y * @param z */ void SetData(double data, unsigned int x, unsigned int y, unsigned int z); /** * @brief GetXDim * @return size of x dimension of this Volume */ unsigned int GetXDim(); /** * @brief GetYDim * @return size of y dimension of this Volume */ unsigned int GetYDim(); /** * @brief GetZDim * @return size of z dimension of this Volume */ unsigned int GetZDim(); /** *@brief returns the Volume instance as an mitk image */ Image::Pointer AsMitkImage(); /** * @brief DeepCopy * @return a deep copy of this Volume. the old volume remains intact and memory is NOT shared * between the objects. */ Volume::Pointer DeepCopy(); /** *@brief convenience method to enable consistent access to the dat array *@return a 1d index from 3d pixel coordinates */ long long GetIndex(unsigned int x, unsigned int y, unsigned int z); double GetSpacing(); void SetSpacing(double spacing); protected: /** * @brief Initialize initializes this volume with the given pointer to the data array. * It is assumed, that the array is of dimension xDim|yDim|zDim. * The Photoacoustic3DVolume will handle memory management of the array and delete it on * constructor call. * * @param data a pointer to the data array * @param xDim x dimension of the data * @param yDim y dimension of the data * @param zDim z dimension of the data + * @param spacing spacing of the data */ Volume(double* data, unsigned int xDim, unsigned int yDim, unsigned int zDim, double spacing); Volume(mitk::Image::Pointer image); ~Volume() override; const int NUMBER_OF_SPATIAL_DIMENSIONS = 3; Image::Pointer m_InternalMitkImage; // this data is kept to enable fast access unsigned int m_XDim; unsigned int m_YDim; unsigned int m_ZDim; double* m_FastAccessDataPointer; }; } } #endif // MITKPHOTOACOUSTIC3dVOLUME_H diff --git a/Modules/Remeshing/mitkACVD.h b/Modules/Remeshing/mitkACVD.h index c775d58853..ca83919d84 100644 --- a/Modules/Remeshing/mitkACVD.h +++ b/Modules/Remeshing/mitkACVD.h @@ -1,101 +1,102 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkACVD_h #define mitkACVD_h #include #include #include namespace mitk { namespace ACVD { /** \brief Remesh a surface and store the result in a new surface. * * The %ACVD library is used for remeshing which is based on the paper "Approximated Centroidal Voronoi Diagrams for * Uniform Polygonal Mesh Coarsening" by S. Valette, and J. M. Chassery. * There are a few rules of thumbs regarding the ranges of parameters to gain high quality remeshed surfaces: * *
      *
    • numVertices is exact, however, if boundaryFixing is enabled, additional vertices are generated at * boundaries *
    • %Set gradation to zero in case you want polygons of roughly the same size all over the remeshed surface; * start with 1 otherwise *
    • subsampling has direct influence on the quality of the remeshed surface (higher values take more time) *
    • edgeSplitting is useful for surfaces that contain long and thin triangles but takes a long time *
    • Leave optimizationLevel set to 1 as greater values result in degenerated polygons *
    • Irregular shrinking of boundaries during remeshing can be avoided by boundaryFixing, however this results * in additional, lower quality polygons at boundaries *
    * * \param[in] surface Input surface. * \param[in] t Time step of a four-dimensional input surface, zero otherwise. * \param[in] numVertices Desired number of vertices in the remeshed surface, set to zero to keep original vertex * count. * \param[in] gradation Influence of surface curvature on polygon size. * \param[in] subsampling Subsample input surface until number of vertices exceeds initial count times this * parameter. * \param[in] edgeSplitting Recursively split edges that are longer than the average edge length times this * parameter. * \param[in] optimizationLevel Minimize distance between input surface and remeshed surface. + * \param[in] forceManifold * \param[in] boundaryFixing Keep original surface boundaries by adding additional polygons. * \return Returns the remeshed surface or nullptr if input surface is invalid. */ MITKREMESHING_EXPORT Surface::Pointer Remesh(Surface::ConstPointer surface, unsigned int t, int numVertices, double gradation, int subsampling = 10, double edgeSplitting = 0.0, int optimizationLevel = 1, bool forceManifold = false, bool boundaryFixing = false); /** \brief Encapsulates mitk::ACVD::Remesh function as filter. */ class MITKREMESHING_EXPORT RemeshFilter : public mitk::SurfaceToSurfaceFilter { public: mitkClassMacro(RemeshFilter, SurfaceToSurfaceFilter); itkFactorylessNewMacro(Self); itkCloneMacro(Self); itkSetMacro(TimeStep, unsigned int); itkSetMacro(NumVertices, int); itkSetMacro(Gradation, double); itkSetMacro(Subsampling, int); itkSetMacro(EdgeSplitting, double); itkSetMacro(OptimizationLevel, int); itkSetMacro(ForceManifold, bool); itkSetMacro(BoundaryFixing, bool); protected: void GenerateData() override; private: RemeshFilter(); ~RemeshFilter() override; unsigned int m_TimeStep; int m_NumVertices; double m_Gradation; int m_Subsampling; double m_EdgeSplitting; int m_OptimizationLevel; bool m_ForceManifold; bool m_BoundaryFixing; }; } } #endif diff --git a/Modules/SceneSerialization/include/mitkSceneIO.h b/Modules/SceneSerialization/include/mitkSceneIO.h index 9cdcbe8fbc..66be8b16f1 100644 --- a/Modules/SceneSerialization/include/mitkSceneIO.h +++ b/Modules/SceneSerialization/include/mitkSceneIO.h @@ -1,134 +1,134 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkSceneIO_h_included #define mitkSceneIO_h_included #include #include "mitkDataStorage.h" #include "mitkNodePredicateBase.h" #include class TiXmlElement; namespace mitk { class BaseData; class PropertyList; class MITKSCENESERIALIZATION_EXPORT SceneIO : public itk::Object { public: mitkClassMacroItkParent(SceneIO, itk::Object); itkFactorylessNewMacro(Self); itkCloneMacro(Self); typedef DataStorage::SetOfObjects FailedBaseDataListType; /** * \brief Load a scene of objects from file * \return DataStorage with all scene objects and their relations. If loading failed, query GetFailedNodes() and * GetFailedProperties() for more detail. * * Attempts to read the provided file and create objects with * parent/child relations into a DataStorage. * * \param filename full filename of the scene file * \param storage If given, this DataStorage is used instead of a newly created one * \param clearStorageFirst If set, the provided DataStorage will be cleared before populating it with the loaded * objects */ virtual DataStorage::Pointer LoadScene(const std::string &filename, DataStorage *storage = nullptr, bool clearStorageFirst = false); /** * \brief Load a scene of objects from directory. * \return DataStorage with all scene objects and their relations. If loading failed, query GetFailedNodes() and * GetFailedProperties() for more detail. * * Does the same like LoadScene, but assumes that the given filename is the index.xml of the scene and the working directory * is the directory of the given filename. This function can be used to load an already unpacked scene and create objects with * parent/child relations into a DataStorage. * - * \param filename full filename of the scene index file + * \param indexfilename full filename of the scene index file * \param storage If given, this DataStorage is used instead of a newly created one * \param clearStorageFirst If set, the provided DataStorage will be cleared before populating it with the loaded * objects */ virtual DataStorage::Pointer LoadSceneUnzipped(const std::string &indexfilename, DataStorage *storage = nullptr, bool clearStorageFirst = false); /** * \brief Save a scene of objects to file * \return True if complete success, false if any problem occurred. Note that a scene file might still be written if false is returned, it just will not contain every node/property. If writing failed, query GetFailedNodes() and GetFailedProperties() for more detail. * * Attempts to write a scene file, which contains the nodes of the * provided DataStorage, their parent/child relations, and properties. * + * \param sceneNodes * \param storage a DataStorage containing all nodes that should be saved - * \param filename full filename of the scene file - * \param predicate defining which items of the datastorage to use and which not + * \param filename */ virtual bool SaveScene(DataStorage::SetOfObjects::ConstPointer sceneNodes, const DataStorage *storage, const std::string &filename); /** * \brief Get a list of nodes (BaseData containers) that failed to be read/written. * * FailedBaseDataListType hold all those nodes that contain BaseData objects * which could not be read or written during the last call to LoadScene or SaveScene. */ const FailedBaseDataListType *GetFailedNodes(); /** * \brief Get a list of properties that failed to be read/written. * * Each entry corresponds to a property which could not * be (de)serialized. The properties may come from either of *
      *
    • The BaseData's PropertyList *
    • The DataNodes's PropertyList *
    • Any of a DataNodes's render window specific PropertyLists *
    */ const PropertyList *GetFailedProperties(); protected: SceneIO(); ~SceneIO() override; std::string CreateEmptyTempDirectory(); TiXmlElement *SaveBaseData(BaseData *data, const std::string &filenamehint, bool &error); TiXmlElement *SavePropertyList(PropertyList *propertyList, const std::string &filenamehint); void OnUnzipError(const void *pSender, std::pair &info); void OnUnzipOk(const void *pSender, std::pair &info); FailedBaseDataListType::Pointer m_FailedNodes; PropertyList::Pointer m_FailedProperties; std::string m_WorkingDirectory; unsigned int m_UnzipErrors; }; } #endif diff --git a/Modules/SceneSerialization/src/mitkSceneReaderV1.h b/Modules/SceneSerialization/src/mitkSceneReaderV1.h index 900026b4b4..9ba5964e93 100644 --- a/Modules/SceneSerialization/src/mitkSceneReaderV1.h +++ b/Modules/SceneSerialization/src/mitkSceneReaderV1.h @@ -1,74 +1,74 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkSceneReader.h" namespace mitk { class SceneReaderV1 : public SceneReader { public: mitkClassMacro(SceneReaderV1, SceneReader); itkFactorylessNewMacro(Self); itkCloneMacro(Self); bool LoadScene(TiXmlDocument &document, const std::string &workingDirectory, DataStorage *storage) override; protected: /** \brief tries to create one DataNode from a given XML \ element */ DataNode::Pointer LoadBaseDataFromDataTag(TiXmlElement *dataElement, const std::string &workingDirectory, bool &error); /** \brief reads all the properties from the XML document and recreates them in node */ bool DecorateNodeWithProperties(DataNode *node, TiXmlElement *nodeElement, const std::string &workingDirectory); /** \brief Clear a default property list and handle some exceptions. Called after assigning a BaseData object to a fresh DataNode via SetData(). This call to SetData() would create default properties that have not been there when saving the scene. Since they can produce problems, we clear the list and use only those properties that we read from the scene file. This method also handles some exceptions for backwards compatibility. Those exceptions are documented directly in the code of the method. */ void ClearNodePropertyListWithExceptions(DataNode &node, PropertyList &propertyList); /** \brief reads all properties assigned to a base data element and assigns the list to the base data object - The baseDataNodeElem is supposed to be the element. + The baseDataNodeElem is supposed to be the \c \ element. */ bool DecorateBaseDataWithProperties(BaseData::Pointer data, TiXmlElement *baseDataNodeElem, const std::string &workingDir); typedef std::pair> NodesAndParentsPair; typedef std::list OrderedNodesList; typedef std::map IDToNodeMappingType; typedef std::map NodeToIDMappingType; OrderedNodesList m_OrderedNodePairs; IDToNodeMappingType m_NodeForID; NodeToIDMappingType m_IDForNode; UIDGenerator m_UIDGen; }; } diff --git a/Modules/Segmentation/Controllers/mitkSegmentationInterpolationController.h b/Modules/Segmentation/Controllers/mitkSegmentationInterpolationController.h index 53673f57e1..30a9f8489c 100644 --- a/Modules/Segmentation/Controllers/mitkSegmentationInterpolationController.h +++ b/Modules/Segmentation/Controllers/mitkSegmentationInterpolationController.h @@ -1,220 +1,217 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkSegmentationInterpolationController_h_Included #define mitkSegmentationInterpolationController_h_Included #include "mitkCommon.h" #include "mitkImage.h" #include #include #include #include #include namespace mitk { class Image; /** \brief Generates interpolations of 2D slices. \sa QmitkSlicesInterpolator \sa QmitkInteractiveSegmentation \ingroup ToolManagerEtAl This class keeps track of the contents of a 3D segmentation image. \attention mitk::SegmentationInterpolationController assumes that the image contains pixel values of 0 and 1. After you set the segmentation image using SetSegmentationVolume(), the whole image is scanned for pixels other than 0. SegmentationInterpolationController registers as an observer to the segmentation image, and repeats the scan whenvever the image is modified. You can prevent this (time consuming) scan if you do the changes slice-wise and send difference images to SegmentationInterpolationController. For this purpose SetChangedSlice() should be used. mitk::OverwriteImageFilter already does this every time it changes a slice of an image. There is a static method InterpolatorForImage(), which can be used to find out if there already is an interpolator instance for a specified image. OverwriteImageFilter uses this to get to know its interpolator. SegmentationInterpolationController needs to maintain some information about the image slices (in every dimension). This information is stored internally in m_SegmentationCountInSlice, which is basically three std::vectors (one for each dimension). - Each item describes one image dimension, each vector item holds the count of pixels in "its" slice. This is perhaps - better to understand - from the following picture (where red items just mean to symbolize "there is some segmentation" - in reality there - is an integer count). - - \image html slice_based_segmentation_interpolator.png + Each item describes one image dimension, each vector item holds the count of pixels in "its" slice. $Author$ */ class MITKSEGMENTATION_EXPORT SegmentationInterpolationController : public itk::Object { public: mitkClassMacroItkParent(SegmentationInterpolationController, itk::Object); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** \brief Find interpolator for a given image. \return nullptr if there is no interpolator yet. This method is useful if several "clients" modify the same image and want to access the interpolations. Then they can share the same object. */ static SegmentationInterpolationController *InterpolatorForImage(const Image *); /** \brief Block reaction to an images Modified() events. Blocking the scan of the whole image is especially useful when you are about to change a single slice of the image. Then you would send a difference image of this single slice to SegmentationInterpolationController but call image->Modified() anyway. Before calling image->Modified() you should block SegmentationInterpolationController's reactions to this modified by using this method. */ void BlockModified(bool); /** \brief Initialize with a whole volume. Will scan the volume for segmentation pixels (values other than 0) and fill some internal data structures. You don't have to call this method every time something changes, but only when several slices at once change. When you change a single slice, call SetChangedSlice() instead. */ void SetSegmentationVolume(const Image *segmentation); /** \brief Set a reference image (original patient image) - optional. If this volume is set (must exactly match the dimensions of the segmentation), the interpolation algorithm may consider image content to improve the interpolated (estimated) segmentation. */ void SetReferenceVolume(const Image *segmentation); /** \brief Update after changing a single slice. \param sliceDiff is a 2D image with the difference image of the slice determined by sliceDimension and sliceIndex. The difference is (pixel value in the new slice minus pixel value in the old slice). \param sliceDimension Number of the dimension which is constant for all pixels of the meant slice. \param sliceIndex Which slice to take, in the direction specified by sliceDimension. Count starts from 0. \param timeStep Which time step is changed */ void SetChangedSlice(const Image *sliceDiff, unsigned int sliceDimension, unsigned int sliceIndex, unsigned int timeStep); void SetChangedVolume(const Image *sliceDiff, unsigned int timeStep); /** \brief Generates an interpolated image for the given slice. \param sliceDimension Number of the dimension which is constant for all pixels of the meant slice. \param sliceIndex Which slice to take, in the direction specified by sliceDimension. Count starts from 0. + \param currentPlane + \param timeStep Which time step to use */ Image::Pointer Interpolate(unsigned int sliceDimension, unsigned int sliceIndex, const mitk::PlaneGeometry *currentPlane, unsigned int timeStep); void OnImageModified(const itk::EventObject &); /** * Activate/Deactivate the 2D interpolation. */ void Activate2DInterpolation(bool); /** \brief Get existing instance or create a new one */ static SegmentationInterpolationController *GetInstance(); protected: /** \brief Protected class of mitk::SegmentationInterpolationController. Don't use (you shouldn't be able to do so)! */ class MITKSEGMENTATION_EXPORT SetChangedSliceOptions { public: SetChangedSliceOptions( unsigned int sd, unsigned int si, unsigned int d0, unsigned int d1, unsigned int t, const void *pixels) : sliceDimension(sd), sliceIndex(si), dim0(d0), dim1(d1), timeStep(t), pixelData(pixels) { } unsigned int sliceDimension; unsigned int sliceIndex; unsigned int dim0; unsigned int dim1; unsigned int timeStep; const void *pixelData; }; typedef std::vector DirtyVectorType; // typedef std::vector< DirtyVectorType[3] > TimeResolvedDirtyVectorType; // cannot work with C++, so next line is // used for implementation typedef std::vector> TimeResolvedDirtyVectorType; typedef std::map InterpolatorMapType; SegmentationInterpolationController(); // purposely hidden ~SegmentationInterpolationController() override; /// internal scan of a single slice template void ScanChangedSlice(const itk::Image *, const SetChangedSliceOptions &options); template void ScanChangedVolume(const itk::Image *, unsigned int timeStep); template void ScanWholeVolume(const itk::Image *, const Image *volume, unsigned int timeStep); void PrintStatus(); /** An array of flags. One for each dimension of the image. A flag is set, when a slice in a certain dimension has at least one pixel that is not 0 (which would mean that it has to be considered by the interpolation algorithm). E.g. flags for axial slices are stored in m_SegmentationCountInSlice[0][index]. Enhanced with time steps it is now m_SegmentationCountInSlice[timeStep][0][index] */ TimeResolvedDirtyVectorType m_SegmentationCountInSlice; static InterpolatorMapType s_InterpolatorForImage; Image::ConstPointer m_Segmentation; Image::ConstPointer m_ReferenceImage; bool m_BlockModified; bool m_2DInterpolationActivated; }; } // namespace #endif diff --git a/Modules/Segmentation/Controllers/mitkSliceBasedInterpolationController.h b/Modules/Segmentation/Controllers/mitkSliceBasedInterpolationController.h index 4f8996d593..eee623f932 100644 --- a/Modules/Segmentation/Controllers/mitkSliceBasedInterpolationController.h +++ b/Modules/Segmentation/Controllers/mitkSliceBasedInterpolationController.h @@ -1,200 +1,190 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkSliceBasedInterpolationController_h_Included #define mitkSliceBasedInterpolationController_h_Included #include "mitkLabelSetImage.h" #include #include #include #include #include namespace mitk { class Image; /** \brief Generates interpolations of 2D slices. \sa QmitkSlicesInterpolator \sa QmitkInteractiveSegmentation \ingroup ToolManagerEtAl This class keeps track of the contents of a 3D segmentation image. \attention mitk::SliceBasedInterpolationController assumes that the image contains pixel values of 0 and 1. After you set the segmentation image using SetSegmentationVolume(), the whole image is scanned for pixels other than 0. SliceBasedInterpolationController registers as an observer to the segmentation image, and repeats the scan whenvever the image is modified. You can prevent this (time consuming) scan if you do the changes slice-wise and send difference images to SliceBasedInterpolationController. For this purpose SetChangedSlice() should be used. mitk::OverwriteImageFilter already does this every time it changes a slice of an image. There is a static method InterpolatorForImage(), which can be used to find out if there already is an interpolator instance for a specified image. OverwriteImageFilter uses this to get to know its interpolator. SliceBasedInterpolationController needs to maintain some information about the image slices (in every dimension). This information is stored internally in m_SegmentationCountInSlice, which is basically three std::vectors (one for each dimension). Each item describes one image dimension, each vector item holds the count of pixels in "its" slice. This is perhaps better to understand from the following picture (where red items just mean to symbolize "there is some segmentation" - in reality there is an integer count). - \image html slice_based_segmentation_interpolator.png - $Author$ */ class MITKSEGMENTATION_EXPORT SliceBasedInterpolationController : public itk::Object { public: mitkClassMacroItkParent(SliceBasedInterpolationController, itk::Object); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** \brief Find interpolator for a given image. \return nullptr if there is no interpolator yet. This method is useful if several "clients" modify the same image and want to access the interpolations. Then they can share the same object. */ static SliceBasedInterpolationController *InterpolatorForImage(const Image *); /** \brief Initialize with a whole volume. Will scan the volume for segmentation pixels (values other than 0) and fill some internal data structures. You don't have to call this method every time something changes, but only when several slices at once change. When you change a single slice, call SetChangedSlice() instead. */ void SetWorkingImage(LabelSetImage *image); /** \brief Set a reference image (original patient image) - optional. If this image is set (must exactly match the dimensions of the segmentation), the interpolation algorithm may consider image content to improve the interpolated (estimated) segmentation. */ void SetReferenceImage(Image *image); /** \brief Update after changing a single slice in the working image. \param image is a 2D image with the difference image of the slice determined by sliceDimension and sliceIndex. The difference is (pixel value in the new slice minus pixel value in the old slice). \param sliceDimension Number of the dimension which is constant for all pixels of the meant slice. \param sliceIndex Which slice to take, in the direction specified by sliceDimension. Count starts from 0. \param timeStep Which time step is changed */ void SetChangedSlice(const Image *image, unsigned int sliceDimension, unsigned int sliceIndex, unsigned int timeStep); - /** - \brief Update after changing the whole working image. - - \param image is a 3D image with the difference image of the slice determined by sliceDimension and sliceIndex. - The difference is (pixel value in the new slice minus pixel value in the old slice). - - \param timeStep Which time step is changed - */ - // void SetChangedImage( const Image* image, unsigned int timeStep ); - /** \brief Generates an interpolated image for the given slice. \param sliceDimension Number of the dimension which is constant for all pixels of the meant slice. \param sliceIndex Which slice to take, in the direction specified by sliceDimension. Count starts from 0. + \param currentPlane + \param timeStep Which time step to use */ Image::Pointer Interpolate(unsigned int sliceDimension, unsigned int sliceIndex, const mitk::PlaneGeometry *currentPlane, unsigned int timeStep); /** \brief Initializes the internal container with the number of voxels per label. */ void ResetLabelCount(); protected: /** \brief Protected class of mitk::SliceBasedInterpolationController. Don't use (you shouldn't be able to do so)! */ class MITKSEGMENTATION_EXPORT SetChangedSliceOptions { public: SetChangedSliceOptions(unsigned int sd, unsigned int si, unsigned int d0, unsigned int d1, unsigned int t) : sliceDimension(sd), sliceIndex(si), dim0(d0), dim1(d1), timeStep(t) { } unsigned int sliceDimension; unsigned int sliceIndex; unsigned int dim0; unsigned int dim1; unsigned int timeStep; // void* pixelData; }; typedef std::vector LabelCounterVectorType; typedef std::vector LabelCounterSliceVectorType; typedef std::vector> LabelCounterSliceTimeVectorType; typedef std::map InterpolatorMapType; SliceBasedInterpolationController(); // purposely hidden ~SliceBasedInterpolationController() override; /// internal scan of a single slice template void ScanSliceITKProcessing(const itk::Image *, const SetChangedSliceOptions &options); /// internal scan of the whole image template void ScanImageITKProcessing(itk::Image *, unsigned int timeStep); /** An array that of flags. One for each dimension of the image. A flag is set, when a slice in a certain dimension has at least one pixel that is not 0 (which would mean that it has to be considered by the interpolation algorithm). E.g. flags for axial slices are stored in m_SegmentationCountInSlice[0][index]. Enhanced with time steps it is now m_SegmentationCountInSlice[timeStep][0][index] */ LabelCounterSliceTimeVectorType m_LabelCountInSlice; static InterpolatorMapType s_InterpolatorForImage; LabelSetImage::Pointer m_WorkingImage; Image::Pointer m_ReferenceImage; }; } // namespace #endif diff --git a/Modules/Segmentation/Interactions/mitkSegTool2D.h b/Modules/Segmentation/Interactions/mitkSegTool2D.h index b4d4c5d2e6..474b90fae7 100644 --- a/Modules/Segmentation/Interactions/mitkSegTool2D.h +++ b/Modules/Segmentation/Interactions/mitkSegTool2D.h @@ -1,192 +1,199 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkSegTool2D_h_Included #define mitkSegTool2D_h_Included #include "mitkCommon.h" #include "mitkImage.h" #include "mitkTool.h" #include #include "mitkInteractionPositionEvent.h" #include "mitkInteractionConst.h" #include "mitkPlanePositionManager.h" #include "mitkRestorePlanePositionOperation.h" #include namespace mitk { class BaseRenderer; /** \brief Abstract base class for segmentation tools. \sa Tool \ingroup Interaction \ingroup ToolManagerEtAl Implements 2D segmentation specific helper methods, that might be of use to all kind of 2D segmentation tools. At the moment these are: - Determination of the slice where the user paints upon (DetermineAffectedImageSlice) - Projection of a 3D contour onto a 2D plane/slice SegTool2D tries to structure the interaction a bit. If you pass "PressMoveRelease" as the interaction type of your derived tool, you might implement the methods OnMousePressed, OnMouseMoved, and OnMouseReleased. Yes, your guess about when they are called is correct. \warning Only to be instantiated by mitk::ToolManager. $Author$ */ class MITKSEGMENTATION_EXPORT SegTool2D : public Tool { public: mitkClassMacro(SegTool2D, Tool); /** \brief Calculates for a given Image and PlaneGeometry, which slice of the image (in index corrdinates) is meant by the plane. \return false, if no slice direction seems right (e.g. rotated planes) + \param image + \param plane \param affectedDimension The image dimension, which is constant for all points in the plane, e.g. Axial --> 2 \param affectedSlice The index of the image slice */ static bool DetermineAffectedImageSlice(const Image *image, const PlaneGeometry *plane, int &affectedDimension, int &affectedSlice); /** * @brief Updates the surface interpolation by extracting the contour form the given slice. * @param slice the slice from which the contour should be extracted * @param workingImage the segmentation image * @param plane the plane in which the slice lies * @param detectIntersection if true the slice is eroded before contour extraction. If the slice is empty after the * erosion it is most * likely an intersecting contour an will not be added to the SurfaceInterpolationController */ static void UpdateSurfaceInterpolation(const Image *slice, const Image *workingImage, const PlaneGeometry *plane, bool detectIntersection); void SetShowMarkerNodes(bool); /** * \brief Enables or disables the 3D interpolation after writing back the 2D segmentation result, and defaults to * true. */ void SetEnable3DInterpolation(bool); protected: SegTool2D(); // purposely hidden SegTool2D(const char *, const us::Module *interactorModule = nullptr); // purposely hidden ~SegTool2D() override; struct SliceInformation { mitk::Image::Pointer slice; mitk::PlaneGeometry *plane; unsigned int timestep; SliceInformation() {} SliceInformation(mitk::Image *slice, mitk::PlaneGeometry *plane, unsigned int timestep) { this->slice = slice; this->plane = plane; this->timestep = timestep; } }; /** * \brief Filters events that cannot be handle by 2D segmentation tools * * Current an event is discarded if it was not sent by a 2D renderwindow and if it is * not of type InteractionPositionEvent */ bool FilterEvents(InteractionEvent *interactionEvent, DataNode *dataNode) override; /** * \brief Extract the slice of an image that the user just scribbles on. The given component denotes the vector component of a dwi-image. * + * \param positionEvent + * \param image * \param component The component to be extracted of a given multi-component image. -1 is the default parameter to denote an invalid component. * * \return 'nullptr' if SegTool2D is either unable to determine which slice was affected, or if there was some problem * getting the image data at that position. */ Image::Pointer GetAffectedImageSliceAs2DImage(const InteractionPositionEvent *positionEvent, const Image *image, unsigned int component = 0); /** * \brief Extract the slice of an image cut by given plane. The given component denotes the vector component of a dwi-image. * + * \param planeGeometry + * \param image + * \param timeStep * \param component The component to be extracted of a given multi-component image. -1 is the default parameter to denote an invalid component. * * \return 'nullptr' if SegTool2D is either unable to determine which slice was affected, or if there was some problem * getting the image data at that position. */ Image::Pointer GetAffectedImageSliceAs2DImage(const PlaneGeometry *planeGeometry, const Image *image, unsigned int timeStep, unsigned int component = 0); /** \brief Extract the slice of the currently selected working image that the user just scribbles on. \return nullptr if SegTool2D is either unable to determine which slice was affected, or if there was some problem getting the image data at that position, or just no working image is selected. */ Image::Pointer GetAffectedWorkingSlice(const InteractionPositionEvent *); /** \brief Extract the slice of the currently selected reference image that the user just scribbles on. \return nullptr if SegTool2D is either unable to determine which slice was affected, or if there was some problem getting the image data at that position, or just no reference image is selected. */ Image::Pointer GetAffectedReferenceSlice(const InteractionPositionEvent *); void WriteBackSegmentationResult(const InteractionPositionEvent *, Image *); void WriteBackSegmentationResult(const PlaneGeometry *planeGeometry, Image *, unsigned int timeStep); void WriteBackSegmentationResult(const std::vector &sliceList, bool writeSliceToVolume = true); void WritePreviewOnWorkingImage( Image *targetSlice, Image *sourceSlice, Image *workingImage, int paintingPixelValue, int timestep); void WriteSliceToVolume(const SliceInformation &sliceInfo); /** \brief Adds a new node called Contourmarker to the datastorage which holds a mitk::PlanarFigure. By selecting this node the slicestack will be reoriented according to the PlanarFigure's Geometry */ int AddContourmarker(); void InteractiveSegmentationBugMessage(const std::string &message); BaseRenderer *m_LastEventSender; unsigned int m_LastEventSlice; private: // The prefix of the contourmarkername. Suffix is a consecutive number const std::string m_Contourmarkername; bool m_ShowMarkerNodes; static bool m_SurfaceInterpolationEnabled; }; } // namespace #endif diff --git a/Modules/SurfaceInterpolation/mitkSurfaceInterpolationController.h b/Modules/SurfaceInterpolation/mitkSurfaceInterpolationController.h index 55d0bce56e..c808672918 100644 --- a/Modules/SurfaceInterpolation/mitkSurfaceInterpolationController.h +++ b/Modules/SurfaceInterpolation/mitkSurfaceInterpolationController.h @@ -1,250 +1,250 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkSurfaceInterpolationController_h_Included #define mitkSurfaceInterpolationController_h_Included #include "mitkColorProperty.h" #include "mitkCommon.h" #include "mitkInteractionConst.h" #include "mitkProperties.h" #include "mitkRestorePlanePositionOperation.h" #include "mitkSurface.h" #include #include "mitkComputeContourSetNormalsFilter.h" #include "mitkCreateDistanceImageFromSurfaceFilter.h" #include "mitkReduceContourSetFilter.h" #include "mitkDataNode.h" #include "mitkDataStorage.h" #include "vtkAppendPolyData.h" #include "vtkCellArray.h" #include "vtkPoints.h" #include "vtkPolyData.h" #include "vtkPolygon.h" #include "vtkSmartPointer.h" #include "mitkImageTimeSelector.h" #include "mitkVtkRepresentationProperty.h" #include "vtkImageData.h" #include "vtkMarchingCubes.h" #include "vtkProperty.h" #include "mitkProgressBar.h" namespace mitk { class MITKSURFACEINTERPOLATION_EXPORT SurfaceInterpolationController : public itk::Object { public: mitkClassMacroItkParent(SurfaceInterpolationController, itk::Object); itkFactorylessNewMacro(Self); itkCloneMacro(Self); itkGetMacro(DistanceImageSpacing, double); struct ContourPositionInformation { Surface::Pointer contour; Vector3D contourNormal; Point3D contourPoint; }; typedef std::vector ContourPositionInformationList; typedef std::vector ContourPositionInformationVec2D; typedef std::map ContourListMap; static SurfaceInterpolationController *GetInstance(); void SetCurrentTimePoint(TimePointType tp) { if (m_CurrentTimePoint != tp) { m_CurrentTimePoint = tp; if (m_SelectedSegmentation) { this->ReinitializeInterpolation(); } } }; TimePointType GetCurrentTimePoint() const { return m_CurrentTimePoint; }; /** * @brief Adds a new extracted contour to the list * @param newContour the contour to be added. If a contour at that position * already exists the related contour will be updated */ void AddNewContour(Surface::Pointer newContour); /** * @brief Removes the contour for a given plane for the current selected segmenation * @param contourInfo the contour which should be removed * @return true if a contour was found and removed, false if no contour was found */ bool RemoveContour(ContourPositionInformation contourInfo); /** * @brief Adds new extracted contours to the list. If one or more contours at a given position * already exist they will be updated respectively * @param newContours the list of the contours */ void AddNewContours(std::vector newContours); /** * @brief Returns the contour for a given plane for the current selected segmenation - * @param ontourInfo the contour which should be returned + * @param contourInfo the contour which should be returned * @return the contour as an mitk::Surface. If no contour is available at the give position nullptr is returned */ const mitk::Surface *GetContour(ContourPositionInformation contourInfo); /** * @brief Returns the number of available contours for the current selected segmentation * @return the number of contours */ unsigned int GetNumberOfContours(); /** * Interpolates the 3D surface from the given extracted contours */ void Interpolate(); mitk::Surface::Pointer GetInterpolationResult(); /** * Sets the minimum spacing of the current selected segmentation * This is needed since the contour points we reduced before they are used to interpolate the surface */ void SetMinSpacing(double minSpacing); /** * Sets the minimum spacing of the current selected segmentation * This is needed since the contour points we reduced before they are used to interpolate the surface */ void SetMaxSpacing(double maxSpacing); /** * Sets the volume i.e. the number of pixels that the distance image should have * By evaluation we found out that 50.000 pixel delivers a good result */ void SetDistanceImageVolume(unsigned int distImageVolume); /** * @brief Get the current selected segmentation for which the interpolation is performed * @return the current segmentation image */ mitk::Image::Pointer GetCurrentSegmentation(); Surface *GetContoursAsSurface(); void SetDataStorage(DataStorage::Pointer ds); /** * Sets the current list of contourpoints which is used for the surface interpolation * @param segmentation The current selected segmentation * \deprecatedSince{2014_03} */ DEPRECATED(void SetCurrentSegmentationInterpolationList(mitk::Image::Pointer segmentation)); /** * Sets the current list of contourpoints which is used for the surface interpolation - * @param segmentation The current selected segmentation + * @param currentSegmentationImage The current selected segmentation */ void SetCurrentInterpolationSession(mitk::Image::Pointer currentSegmentationImage); /** * Removes the segmentation and all its contours from the list * @param segmentation The segmentation to be removed * \deprecatedSince{2014_03} */ DEPRECATED(void RemoveSegmentationFromContourList(mitk::Image *segmentation)); /** * @brief Remove interpolation session * @param segmentationImage the session to be removed */ void RemoveInterpolationSession(mitk::Image::Pointer segmentationImage); /** * Replaces the current interpolation session with a new one. All contours form the old * session will be applied to the new session. This only works if the two images have the * geometry * @param oldSession the session which should be replaced * @param newSession the new session which replaces the old one * @return true it the the replacement was successful, false if not (e.g. the image's geometry differs) */ bool ReplaceInterpolationSession(mitk::Image::Pointer oldSession, mitk::Image::Pointer newSession); /** * @brief Removes all sessions */ void RemoveAllInterpolationSessions(); /** * @brief Reinitializes the interpolation using the provided contour data * @param contours a mitk::Surface which contains the contours as polys in the vtkPolyData */ void ReinitializeInterpolation(mitk::Surface::Pointer contours); mitk::Image *GetImage(); /** * Estimates the memory which is needed to build up the equationsystem for the interpolation. * \returns The percentage of the real memory which will be used by the interpolation */ double EstimatePortionOfNeededMemory(); unsigned int GetNumberOfInterpolationSessions(); protected: SurfaceInterpolationController(); ~SurfaceInterpolationController() override; template void GetImageBase(itk::Image *input, itk::ImageBase<3>::Pointer &result); private: void ReinitializeInterpolation(); void OnSegmentationDeleted(const itk::Object *caller, const itk::EventObject &event); void AddToInterpolationPipeline(ContourPositionInformation contourInfo); ReduceContourSetFilter::Pointer m_ReduceFilter; ComputeContourSetNormalsFilter::Pointer m_NormalsFilter; CreateDistanceImageFromSurfaceFilter::Pointer m_InterpolateSurfaceFilter; Surface::Pointer m_Contours; double m_DistanceImageSpacing; vtkSmartPointer m_PolyData; mitk::DataStorage::Pointer m_DataStorage; ContourListMap m_ListOfInterpolationSessions; mitk::Surface::Pointer m_InterpolationResult; unsigned int m_CurrentNumberOfReducedContours; mitk::Image *m_SelectedSegmentation; std::map m_SegmentationObserverTags; mitk::TimePointType m_CurrentTimePoint; }; } #endif diff --git a/Modules/ToFHardware/MesaSR4000/mitkToFCameraMESADevice.h b/Modules/ToFHardware/MesaSR4000/mitkToFCameraMESADevice.h index 4aacb79086..df4623b1b1 100644 --- a/Modules/ToFHardware/MesaSR4000/mitkToFCameraMESADevice.h +++ b/Modules/ToFHardware/MesaSR4000/mitkToFCameraMESADevice.h @@ -1,137 +1,138 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkToFCameraMESADevice_h #define __mitkToFCameraMESADevice_h #include #include "mitkCommon.h" #include "mitkToFCameraDevice.h" #include "mitkToFCameraMESAController.h" #include "itkObject.h" #include "itkObjectFactory.h" #include "itkMultiThreader.h" #include "itkFastMutexLock.h" namespace mitk { /** * @brief Interface for all representations of MESA ToF devices. * ToFCameraMESADevice internally holds an instance of ToFCameraMESAController and starts a thread * that continuously grabs images from the controller. A buffer structure buffers the last acquired images * to provide the image data loss-less. * * @ingroup ToFHardware */ class MITKMESASR4000_EXPORT ToFCameraMESADevice : public ToFCameraDevice { public: mitkClassMacro( ToFCameraMESADevice , ToFCameraDevice ); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /*! \brief opens a connection to the ToF camera */ virtual bool OnConnectCamera(); /*! \brief closes the connection to the camera */ virtual bool DisconnectCamera(); /*! \brief starts the continuous updating of the camera. A separate thread updates the source data, the main thread processes the source data and creates images and coordinates */ virtual void StartCamera(); /*! \brief stops the continuous updating of the camera */ virtual void StopCamera(); /*! \brief updates the camera for image acquisition */ virtual void UpdateCamera(); /*! \brief returns whether the camera is currently active or not */ virtual bool IsCameraActive(); /*! \brief gets the amplitude data from the ToF camera as the strength of the active illumination of every pixel. Caution! The user is responsible for allocating and deleting the images. These values can be used to determine the quality of the distance values. The higher the amplitude value, the higher the accuracy of the according distance value \param imageSequence the actually captured image sequence number \param amplitudeArray contains the returned amplitude data as an array. */ virtual void GetAmplitudes(float* amplitudeArray, int& imageSequence); /*! \brief gets the intensity data from the ToF camera as a greyscale image. Caution! The user is responsible for allocating and deleting the images. \param intensityArray contains the returned intensities data as an array. \param imageSequence the actually captured image sequence number */ virtual void GetIntensities(float* intensityArray, int& imageSequence); /*! \brief gets the distance data from the ToF camera measuring the distance between the camera and the different object points in millimeters. Caution! The user is responsible for allocating and deleting the images. \param distanceArray contains the returned distances data as an array. \param imageSequence the actually captured image sequence number */ virtual void GetDistances(float* distanceArray, int& imageSequence); /*! \brief gets the 3 images (distance, amplitude, intensity) from the ToF camera. Caution! The user is responsible for allocating and deleting the images. \param distanceArray contains the returned distance data as an array. \param amplitudeArray contains the returned amplitude data as an array. \param intensityArray contains the returned intensity data as an array. \param sourceDataArray contains the complete source data from the camera device. \param requiredImageSequence the required image sequence number \param capturedImageSequence the actually captured image sequence number + \param rgbDataArray */ virtual void GetAllImages(float* distanceArray, float* amplitudeArray, float* intensityArray, char* sourceDataArray, int requiredImageSequence, int& capturedImageSequence, unsigned char* rgbDataArray=nullptr); /*! \brief returns the corresponding camera controller */ ToFCameraMESAController::Pointer GetController(); /*! \brief set a BaseProperty */ virtual void SetProperty( const char *propertyKey, BaseProperty* propertyValue ); protected: ToFCameraMESADevice(); ~ToFCameraMESADevice(); /*! \brief Thread method continuously acquiring images from the ToF hardware */ static ITK_THREAD_RETURN_TYPE Acquire(void* pInfoStruct); /*! \brief moves the position pointer m_CurrentPos to the next position in the buffer if that's not the next free position to prevent reading from an empty buffer */ void GetNextPos(); ToFCameraMESAController::Pointer m_Controller; ///< corresponding CameraController float** m_DistanceDataBuffer; ///< buffer holding the last distance images float** m_AmplitudeDataBuffer; ///< buffer holding the last amplitude images float** m_IntensityDataBuffer; ///< buffer holding the last intensity images private: }; } //END mitk namespace #endif diff --git a/Modules/ToFHardware/MesaSR4000/mitkToFCameraMESASR4000Device.h b/Modules/ToFHardware/MesaSR4000/mitkToFCameraMESASR4000Device.h index d3ccbbe152..2a82fccf8d 100644 --- a/Modules/ToFHardware/MesaSR4000/mitkToFCameraMESASR4000Device.h +++ b/Modules/ToFHardware/MesaSR4000/mitkToFCameraMESASR4000Device.h @@ -1,68 +1,68 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkToFCameraMESASR4000Device_h #define __mitkToFCameraMESASR4000Device_h #include #include "mitkCommon.h" #include "mitkToFCameraDevice.h" #include "mitkToFCameraMESADevice.h" #include "mitkToFCameraMESASR4000Controller.h" #include "itkObject.h" #include "itkObjectFactory.h" #include "itkMultiThreader.h" #include "itkFastMutexLock.h" namespace mitk { /** * @brief Device class representing a MESA CamBoard camera * * @ingroup ToFHardware */ class MITKMESASR4000_EXPORT ToFCameraMESASR4000Device : public ToFCameraMESADevice { public: mitkClassMacro( ToFCameraMESASR4000Device , ToFCameraMESADevice ); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /*! \brief set a BaseProperty */ virtual void SetProperty( const char *propertyKey, BaseProperty* propertyValue ); /*! \brief Setting the region of interest, the camera is configured to only output a certain area of the image. \param leftUpperCornerX x value of left upper corner of region - \param leftUpperCornerX y value of left upper corner of region + \param leftUpperCornerY y value of left upper corner of region \param width width of region \param height height of region */ void SetRegionOfInterest( unsigned int leftUpperCornerX, unsigned int leftUpperCornerY, unsigned int width, unsigned int height ); protected: ToFCameraMESASR4000Device(); ~ToFCameraMESASR4000Device(); private: }; } //END mitk namespace #endif diff --git a/Modules/ToFHardware/PMD/mitkToFCameraPMDCamBoardController.h b/Modules/ToFHardware/PMD/mitkToFCameraPMDCamBoardController.h index ae7a77f0c1..99902033e7 100644 --- a/Modules/ToFHardware/PMD/mitkToFCameraPMDCamBoardController.h +++ b/Modules/ToFHardware/PMD/mitkToFCameraPMDCamBoardController.h @@ -1,95 +1,95 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkToFCameraPMDCamBoardController_h #define __mitkToFCameraPMDCamBoardController_h #include "MitkPMDExports.h" #include "mitkCommon.h" #include "mitkToFCameraPMDController.h" #include "itkObject.h" #include "itkObjectFactory.h" namespace mitk { /** * @brief Interface to the Time-of-Flight (ToF) camera PMD CamBoard * * * @ingroup ToFHardware */ class MITKPMD_EXPORT ToFCameraPMDCamBoardController : public ToFCameraPMDController { public: mitkClassMacro( ToFCameraPMDCamBoardController , ToFCameraPMDController ); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /*! \brief opens a connection to the ToF camera and initializes the hardware specific members \return returns whether the connection was successful (true) or not (false) */ virtual bool OpenCameraConnection(); /*! \brief sets an additional distance offset which will be added to all distance values. \param offset offset in m */ bool SetDistanceOffset( float offset ); /*! \brief returns the currently applied distance offset in m \param offset offset in m */ float GetDistanceOffset(); /*! \brief Setting the region of interest, the camera is configured to only output a certain area of the image. \param leftUpperCornerX x value of left upper corner of region - \param leftUpperCornerX y value of left upper corner of region + \param leftUpperCornerY y value of left upper corner of region \param width width of region \param height height of region */ bool SetRegionOfInterest( unsigned int leftUpperCornerX, unsigned int leftUpperCornerY, unsigned int width, unsigned int height ); /*! \brief Setting the region of interest, the camera is configured to only output a certain area of the image. \param roi region of interest. roi[0]: x value of left upper corner, roi[1]: y value of left upper corner, roi[2]: width, roi[3]: height */ bool SetRegionOfInterest( unsigned int roi[4] ); /*! \brief returns the region of interest currently set \return currently set region of interest. */ unsigned int* GetRegionOfInterest(); /*! \brief Sets the field of view of the camera lens. \param fov field of view in degrees. The default value is 40 degrees. */ bool SetFieldOfView( float fov ); protected: ToFCameraPMDCamBoardController(); ~ToFCameraPMDCamBoardController(); /* \brief Transform the output of the camera, i.e. cut invalid pixels, and rotate 90 degrees counterclockwise \param input data array of original size (207x204) \param rotated output data array of reduced size (200x200) */ virtual void TransformCameraOutput(float* in, float* out, bool isDist); }; } //END mitk namespace #endif diff --git a/Modules/ToFHardware/PMD/mitkToFCameraPMDCamBoardDevice.h b/Modules/ToFHardware/PMD/mitkToFCameraPMDCamBoardDevice.h index 1b2f787d5d..b858688d45 100644 --- a/Modules/ToFHardware/PMD/mitkToFCameraPMDCamBoardDevice.h +++ b/Modules/ToFHardware/PMD/mitkToFCameraPMDCamBoardDevice.h @@ -1,69 +1,69 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkToFCameraPMDCamBoardDevice_h #define __mitkToFCameraPMDCamBoardDevice_h #include #include "mitkCommon.h" #include "mitkToFCameraDevice.h" #include "mitkToFCameraPMDDevice.h" #include "mitkToFCameraPMDCamBoardController.h" #include "itkObject.h" #include "itkObjectFactory.h" #include "itkMultiThreader.h" #include "itkFastMutexLock.h" namespace mitk { /** * @brief Device class representing a PMD CamBoard camera * * @ingroup ToFHardware */ class MITKPMD_EXPORT ToFCameraPMDCamBoardDevice : public ToFCameraPMDDevice { public: mitkClassMacro( ToFCameraPMDCamBoardDevice , ToFCameraPMDDevice ); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /*! \brief set a BaseProperty */ virtual void SetProperty( const char *propertyKey, BaseProperty* propertyValue ); /*! \brief Setting the region of interest, the camera is configured to only output a certain area of the image. \param leftUpperCornerX x value of left upper corner of region - \param leftUpperCornerX y value of left upper corner of region + \param leftUpperCornerY y value of left upper corner of region \param width width of region \param height height of region */ void SetRegionOfInterest( unsigned int leftUpperCornerX, unsigned int leftUpperCornerY, unsigned int width, unsigned int height ); //void GetAllImages(float* distanceArray, float* amplitudeArray, float* intensityArray, char* sourceDataArray, int requiredImageSequence, int& capturedImageSequence, unsigned char* rgbDataArray); protected: ToFCameraPMDCamBoardDevice(); ~ToFCameraPMDCamBoardDevice(); private: }; } //END mitk namespace #endif diff --git a/Modules/ToFHardware/PMD/mitkToFCameraPMDCamCubeController.h b/Modules/ToFHardware/PMD/mitkToFCameraPMDCamCubeController.h index 18e73a8fb7..b0c00d5d6a 100644 --- a/Modules/ToFHardware/PMD/mitkToFCameraPMDCamCubeController.h +++ b/Modules/ToFHardware/PMD/mitkToFCameraPMDCamCubeController.h @@ -1,126 +1,126 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkToFCameraPMDCamCubeController_h #define __mitkToFCameraPMDCamCubeController_h #include #include "mitkCommon.h" #include "mitkToFCameraPMDController.h" #include "itkObject.h" #include "itkObjectFactory.h" namespace mitk { /** * @brief Interface to the Time-of-Flight (ToF) camera PMD CamCube * * * @ingroup ToFHardware */ class MITKPMD_EXPORT ToFCameraPMDCamCubeController : public ToFCameraPMDController { public: mitkClassMacro( ToFCameraPMDCamCubeController , ToFCameraPMDController ); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /*! \brief opens a connection to the ToF camera and initializes the hardware specific members \return returns whether the connection was successful (true) or not (false) */ virtual bool OpenCameraConnection(); /*! \brief sets an additional distance offset which will be added to all distance values. \param offset offset in m \return returns whether set operation was successful (true) or not (false) */ bool SetDistanceOffset( float offset ); /*! \brief returns the currently applied distance offset in m \param offset offset in m */ float GetDistanceOffset(); /*! \brief Setting the region of interest, the camera is configured to only output a certain area of the image. \param leftUpperCornerX x value of left upper corner of region - \param leftUpperCornerX y value of left upper corner of region + \param leftUpperCornerY y value of left upper corner of region \param width width of region \param height height of region \return returns whether set operation was successful (true) or not (false) */ bool SetRegionOfInterest( unsigned int leftUpperCornerX, unsigned int leftUpperCornerY, unsigned int width, unsigned int height ); /*! \brief Setting the region of interest, the camera is configured to only output a certain area of the image. \param roi region of interest. roi[0]: x value of left upper corner, roi[1]: y value of left upper corner, roi[2]: width, roi[3]: height \return returns whether set operation was successful (true) or not (false) */ bool SetRegionOfInterest( unsigned int roi[4] ); /*! \brief returns the region of interest currently set \return currently set region of interest. */ unsigned int* GetRegionOfInterest(); /*! \brief sets the exposure mode of the CamCube \param mode exposure mode. 0: normal mode (one exposure), 1: Suppression of motion blur (SMB), minimizes the time needed to capture a distance image from the camera which results in a reduced amount of motion artifact but may lead to increased noise. \return returns whether set operation was successful (true) or not (false) */ bool SetExposureMode( int mode ); /*! \brief Sets the field of view of the camera lens. \param fov field of view in degrees. The default value is 40 degrees. \return returns whether set operation was successful (true) or not (false) */ bool SetFieldOfView( float fov ); /*! \brief Enable/Disable PMD fixed pattern noise (FPN) calibration \param on enabled (true), disabled (false) \return returns whether set operation was successful (true) or not (false) */ bool SetFPNCalibration( bool on ); /*! \brief Enable/Disable PMD fixed pattern phase noise (FPPN) calibration \param on enabled (true), disabled (false) \return returns whether set operation was successful (true) or not (false) */ bool SetFPPNCalibration( bool on ); /*! \brief Enable/Disable PMD linearity calibration \param on enabled (true), disabled (false) \return returns whether set operation was successful (true) or not (false) */ bool SetLinearityCalibration( bool on ); /*! \brief Enable/Disable PMD lens calibration \param on enabled (true), disabled (false) \return returns whether set operation was successful (true) or not (false) */ bool SetLensCalibration( bool on ); protected: virtual void TransformCameraOutput(float* in, float* out, bool isDist); ToFCameraPMDCamCubeController(); ~ToFCameraPMDCamCubeController(); private: }; } //END mitk namespace #endif diff --git a/Modules/ToFHardware/PMD/mitkToFCameraPMDDevice.h b/Modules/ToFHardware/PMD/mitkToFCameraPMDDevice.h index c13238e061..5423a76c54 100644 --- a/Modules/ToFHardware/PMD/mitkToFCameraPMDDevice.h +++ b/Modules/ToFHardware/PMD/mitkToFCameraPMDDevice.h @@ -1,140 +1,141 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkToFCameraPMDDevice_h #define __mitkToFCameraPMDDevice_h #include #include "mitkCommon.h" #include "mitkToFCameraDevice.h" #include "mitkToFCameraPMDController.h" #include "itkObject.h" #include "itkObjectFactory.h" #include "itkMultiThreader.h" #include "itkFastMutexLock.h" namespace mitk { /** * @brief Interface for all representations of PMD ToF devices. * ToFCameraPMDDevice internally holds an instance of ToFCameraPMDController and starts a thread * that continuously grabs images from the controller. A buffer structure buffers the last acquired images * to provide the image data loss-less. * *\throws mitkException In case of no connection, an exception is thrown! * * @ingroup ToFHardware */ class MITKPMD_EXPORT ToFCameraPMDDevice : public ToFCameraDevice { public: mitkClassMacro( ToFCameraPMDDevice , ToFCameraDevice ); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /*! \brief opens a connection to the ToF camera \throws mitkException In case of no connection, an exception is thrown! */ virtual bool OnConnectCamera(); /*! \brief closes the connection to the camera */ virtual bool DisconnectCamera(); /*! \brief starts the continuous updating of the camera. A separate thread updates the source data, the main thread processes the source data and creates images and coordinates \throws mitkException In case of no connection, an exception is thrown! */ virtual void StartCamera(); /*! \brief updated the controller hold by this device \throws mitkException In case of no connection, an exception is thrown! */ virtual void UpdateCamera(); /*! \brief gets the amplitude data from the ToF camera as the strength of the active illumination of every pixel. Caution! The user is responsible for allocating and deleting the images. These values can be used to determine the quality of the distance values. The higher the amplitude value, the higher the accuracy of the according distance value \param imageSequence the actually captured image sequence number \param amplitudeArray contains the returned amplitude data as an array. */ virtual void GetAmplitudes(float* amplitudeArray, int& imageSequence); /*! \brief gets the intensity data from the ToF camera as a greyscale image. Caution! The user is responsible for allocating and deleting the images. \param intensityArray contains the returned intensities data as an array. \param imageSequence the actually captured image sequence number */ virtual void GetIntensities(float* intensityArray, int& imageSequence); /*! \brief gets the distance data from the ToF camera measuring the distance between the camera and the different object points in millimeters. Caution! The user is responsible for allocating and deleting the images. \param distanceArray contains the returned distances data as an array. \param imageSequence the actually captured image sequence number */ virtual void GetDistances(float* distanceArray, int& imageSequence); /*! \brief gets the 3 images (distance, amplitude, intensity) from the ToF camera. Caution! The user is responsible for allocating and deleting the images. \param distanceArray contains the returned distance data as an array. \param amplitudeArray contains the returned amplitude data as an array. \param intensityArray contains the returned intensity data as an array. \param sourceDataArray contains the complete source data from the camera device. \param requiredImageSequence the required image sequence number \param capturedImageSequence the actually captured image sequence number + \param rgbDataArray */ virtual void GetAllImages(float* distanceArray, float* amplitudeArray, float* intensityArray, char* sourceDataArray, int requiredImageSequence, int& capturedImageSequence, unsigned char* rgbDataArray=nullptr); /*! \brief returns the corresponding camera controller */ ToFCameraPMDController::Pointer GetController(); /*! \brief set a BaseProperty */ virtual void SetProperty( const char *propertyKey, BaseProperty* propertyValue ); protected: ToFCameraPMDDevice(); ~ToFCameraPMDDevice(); /*! \brief method for allocating m_SourceDataArray and m_SourceDataBuffer */ virtual void AllocateSourceData(); /*! \brief method for cleaning up memory allocated for m_SourceDataArray and m_SourceDataBuffer */ virtual void CleanUpSourceData(); /*! \brief Thread method continuously acquiring images from the ToF hardware */ static ITK_THREAD_RETURN_TYPE Acquire(void* pInfoStruct); /*! \brief moves the position pointer m_CurrentPos to the next position in the buffer if that's not the next free position to prevent reading from an empty buffer */ void GetNextPos(); ToFCameraPMDController::Pointer m_Controller; ///< corresponding CameraController char** m_SourceDataBuffer; ///< buffer holding the last acquired images char* m_SourceDataArray; ///< array holding the current PMD source data private: }; } //END mitk namespace #endif diff --git a/Modules/ToFHardware/PMD/mitkToFCameraPMDRawDataDevice.h b/Modules/ToFHardware/PMD/mitkToFCameraPMDRawDataDevice.h index 23119703e1..1c303eb74e 100644 --- a/Modules/ToFHardware/PMD/mitkToFCameraPMDRawDataDevice.h +++ b/Modules/ToFHardware/PMD/mitkToFCameraPMDRawDataDevice.h @@ -1,167 +1,168 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkToFCameraPMDRawDataDevice_h #define __mitkToFCameraPMDRawDataDevice_h #include #include "mitkToFCameraDevice.h" #include "mitkToFCameraPMDController.h" #include "mitkThreadedToFRawDataReconstruction.h" namespace mitk { /** * @brief Interface for all representations of PMD ToF devices. * ToFCameraPMDDevice internally holds an instance of ToFCameraPMDController and starts a thread * that continuously grabs images from the controller. A buffer structure buffers the last acquired images * to provide the image data loss-less. * * @ingroup ToFHardware */ class MITKPMD_EXPORT ToFCameraPMDRawDataDevice : public ToFCameraDevice { public: mitkClassMacro( ToFCameraPMDRawDataDevice , ToFCameraDevice ); itkFactorylessNewMacro(Self); itkCloneMacro(Self); itkSetMacro(ChannelSize, int); itkGetMacro(ChannelSize, int); /*! \brief opens a connection to the ToF camera */ virtual bool OnConnectCamera(); /*! \brief closes the connection to the camera */ virtual bool DisconnectCamera(); /*! \brief starts the continuous updating of the camera. A separate thread updates the source data, the main thread processes the source data and creates images and coordinates */ virtual void StartCamera(); /*! \brief stops the continuous updating of the camera */ virtual void StopCamera(); /*! \brief updates the camera for image acquisition */ virtual void UpdateCamera(); /*! \brief returns whether the camera is currently active or not */ virtual bool IsCameraActive(); /*! \brief gets the amplitude data from the ToF camera as the strength of the active illumination of every pixel. Caution! The user is responsible for allocating and deleting the images. These values can be used to determine the quality of the distance values. The higher the amplitude value, the higher the accuracy of the according distance value \param imageSequence the actually captured image sequence number \param amplitudeArray contains the returned amplitude data as an array. */ virtual void GetAmplitudes(float* amplitudeArray, int& imageSequence); /*! \brief gets the intensity data from the ToF camera as a greyscale image. Caution! The user is responsible for allocating and deleting the images. \param intensityArray contains the returned intensities data as an array. \param imageSequence the actually captured image sequence number */ virtual void GetIntensities(float* intensityArray, int& imageSequence); /*! \brief gets the distance data from the ToF camera measuring the distance between the camera and the different object points in millimeters. Caution! The user is responsible for allocating and deleting the images. \param distanceArray contains the returned distances data as an array. \param imageSequence the actually captured image sequence number */ virtual void GetDistances(float* distanceArray, int& imageSequence); /*! \brief gets the 3 images (distance, amplitude, intensity) from the ToF camera. Caution! The user is responsible for allocating and deleting the images. \param distanceArray contains the returned distance data as an array. \param amplitudeArray contains the returned amplitude data as an array. \param intensityArray contains the returned intensity data as an array. \param sourceDataArray contains the complete source data from the camera device. \param requiredImageSequence the required image sequence number \param capturedImageSequence the actually captured image sequence number + \param rgbDataArray */ virtual void GetAllImages(float* distanceArray, float* amplitudeArray, float* intensityArray, char* sourceDataArray, int requiredImageSequence, int& capturedImageSequence, unsigned char* rgbDataArray=nullptr); /*! \brief returns the corresponding camera controller */ ToFCameraPMDController::Pointer GetController(); virtual void GetChannelSourceData(short* /*sourceData*/, vtkShortArray* /*vtkChannelArray*/ ){}; /*! \brief set a BaseProperty */ virtual void SetProperty( const char *propertyKey, BaseProperty* propertyValue ); protected: ToFCameraPMDRawDataDevice(); ~ToFCameraPMDRawDataDevice(); /*! \brief method for allocating m_SourceDataArray and m_SourceDataBuffer */ virtual void AllocateSourceData(); /*! \brief method for cleaning up memory allocated for m_SourceDataArray and m_SourceDataBuffer */ virtual void CleanUpSourceData(); /*! \brief method for allocating memory for pixel arrays m_IntensityArray, m_DistanceArray and m_AmplitudeArray */ virtual void AllocatePixelArrays(); /*! \brief method for cleanup memory allocated for pixel arrays m_IntensityArray, m_DistanceArray and m_AmplitudeArray */ virtual void CleanupPixelArrays(); /*! \brief Thread method continuously acquiring images from the ToF hardware */ static ITK_THREAD_RETURN_TYPE Acquire(void* pInfoStruct); /*! \brief moves the position pointer m_CurrentPos to the next position in the buffer if that's not the next free position to prevent reading from an empty buffer */ void GetNextPos(); /*! \brief gets the image data and flips it according to user needs Caution! The user is responsible for allocating and deleting the data. \param imageData contains array to the input data. \param flippedData contains flipped output array - Caution! The user is responsible for allocating and deleting the data. Size should be equal to imageData! \param xAxis flag is set to flip around x axis (1 - set, 0 - not set). \param yAxis flag is set to flip around y axis (1 - set, 0 - not set). \param dimension contains the extend of the z dimension (preset is 1) */ void XYAxisFlipImage( float* imageData, float* &flippedData, int xAxis, int yAxis, int dimension = 1 ); //member variables ToFCameraPMDController::Pointer m_Controller; ///< corresponding CameraController ThreadedToFRawDataReconstruction::Pointer m_RawDataSource; char** m_SourceDataBuffer; ///< buffer holding the last acquired images char* m_SourceDataArray; ///< array holding the current PMD source data short* m_ShortSourceData; ///< array holding the current PMD raw data unsigned int m_OriginControllerWidth; ///< holds the original controller width unsigned int m_OriginControllerHeight; ///< holds the original controller height private: int m_ChannelSize; ///< member holds the size of a single raw data channel }; } //END mitk namespace #endif diff --git a/Modules/ToFHardware/mitkToFCameraDevice.h b/Modules/ToFHardware/mitkToFCameraDevice.h index 80e74ed18e..be4f4537ad 100644 --- a/Modules/ToFHardware/mitkToFCameraDevice.h +++ b/Modules/ToFHardware/mitkToFCameraDevice.h @@ -1,230 +1,231 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkToFCameraDevice_h #define __mitkToFCameraDevice_h #include #include "mitkCommon.h" #include "mitkStringProperty.h" #include "mitkProperties.h" #include "mitkPropertyList.h" #include "itkObject.h" #include "itkObjectFactory.h" #include "itkMultiThreader.h" #include "itkFastMutexLock.h" // Microservices #include namespace mitk { /** * @brief Virtual interface and base class for all Time-of-Flight devices. * * @ingroup ToFHardware */ class MITKTOFHARDWARE_EXPORT ToFCameraDevice : public itk::Object { public: mitkClassMacroItkParent(ToFCameraDevice, itk::Object); /*! \brief Opens a connection to the ToF camera. Has to be implemented in the specialized inherited classes. \return True for success. */ virtual bool OnConnectCamera() = 0; /** * @brief ConnectCamera Internally calls OnConnectCamera() of the * respective device implementation. * @return True for success. */ virtual bool ConnectCamera(); /*! \brief closes the connection to the camera */ virtual bool DisconnectCamera() = 0; /*! \brief starts the continuous updating of the camera. A separate thread updates the source data, the main thread processes the source data and creates images and coordinates */ virtual void StartCamera() = 0; /*! \brief stops the continuous updating of the camera */ virtual void StopCamera(); /*! \brief returns true if the camera is connected and started */ virtual bool IsCameraActive(); /*! \brief returns true if the camera is connected */ virtual bool IsCameraConnected(); /*! \brief updates the camera for image acquisition */ virtual void UpdateCamera() = 0; /*! \brief gets the amplitude data from the ToF camera as the strength of the active illumination of every pixel These values can be used to determine the quality of the distance values. The higher the amplitude value, the higher the accuracy of the according distance value \param imageSequence the actually captured image sequence number \param amplitudeArray contains the returned amplitude data as an array. */ virtual void GetAmplitudes(float* amplitudeArray, int& imageSequence) = 0; /*! \brief gets the intensity data from the ToF camera as a greyscale image \param intensityArray contains the returned intensities data as an array. \param imageSequence the actually captured image sequence number */ virtual void GetIntensities(float* intensityArray, int& imageSequence) = 0; /*! \brief gets the distance data from the ToF camera measuring the distance between the camera and the different object points in millimeters \param distanceArray contains the returned distances data as an array. \param imageSequence the actually captured image sequence number */ virtual void GetDistances(float* distanceArray, int& imageSequence) = 0; /*! \brief gets the 3 images (distance, amplitude, intensity) from the ToF camera. Caution! The user is responsible for allocating and deleting the images. \param distanceArray contains the returned distance data as an array. \param amplitudeArray contains the returned amplitude data as an array. \param intensityArray contains the returned intensity data as an array. \param sourceDataArray contains the complete source data from the camera device. \param requiredImageSequence the required image sequence number \param capturedImageSequence the actually captured image sequence number + \param rgbDataArray */ virtual void GetAllImages(float* distanceArray, float* amplitudeArray, float* intensityArray, char* sourceDataArray, int requiredImageSequence, int& capturedImageSequence, unsigned char* rgbDataArray=nullptr) = 0; /*! \brief get the currently set capture width \return capture width */ itkGetMacro(CaptureWidth, int); /*! \brief get the currently set capture height \return capture height */ itkGetMacro(CaptureHeight, int); /*! \brief get the currently set source data size \return source data size */ itkGetMacro(SourceDataSize, int); /*! \brief get the currently set buffer size \return buffer size */ itkGetMacro(BufferSize, int); /*! \brief get the currently set max buffer size \return max buffer size */ itkGetMacro(MaxBufferSize, int); /*! \brief set a bool property in the property list */ void SetBoolProperty( const char* propertyKey, bool boolValue ); /*! \brief set an int property in the property list */ void SetIntProperty( const char* propertyKey, int intValue ); /*! \brief set a float property in the property list */ void SetFloatProperty( const char* propertyKey, float floatValue ); /*! \brief set a string property in the property list */ void SetStringProperty( const char* propertyKey, const char* stringValue ); /*! \brief set a BaseProperty property in the property list */ virtual void SetProperty( const char *propertyKey, BaseProperty* propertyValue ); /*! \brief get a BaseProperty from the property list */ virtual BaseProperty* GetProperty( const char *propertyKey ); /*! \brief get a bool from the property list */ bool GetBoolProperty(const char *propertyKey, bool& boolValue); /*! \brief get a string from the property list */ bool GetStringProperty(const char *propertyKey, std::string& string); /*! \brief get an int from the property list */ bool GetIntProperty(const char *propertyKey, int& integer); virtual int GetRGBCaptureWidth(); virtual int GetRGBCaptureHeight(); protected: ToFCameraDevice(); ~ToFCameraDevice() override; /*! \brief method for allocating memory for pixel arrays m_IntensityArray, m_DistanceArray and m_AmplitudeArray */ virtual void AllocatePixelArrays(); /*! \brief method for cleanup memory allocated for pixel arrays m_IntensityArray, m_DistanceArray and m_AmplitudeArray */ virtual void CleanupPixelArrays(); float* m_IntensityArray; ///< float array holding the intensity image float* m_DistanceArray; ///< float array holding the distance image float* m_AmplitudeArray; ///< float array holding the amplitude image int m_BufferSize; ///< buffer size of the image buffer needed for loss-less acquisition of range data int m_MaxBufferSize; ///< maximal buffer size needed for initialization of data arrays. Default value is 100. int m_CurrentPos; ///< current position in the buffer which will be retrieved by the Get methods int m_FreePos; ///< current position in the buffer which will be filled with data acquired from the hardware int m_CaptureWidth; ///< width of the range image (x dimension) int m_CaptureHeight; ///< height of the range image (y dimension) int m_PixelNumber; ///< number of pixels in the range image (m_CaptureWidth*m_CaptureHeight) int m_RGBImageWidth; ///< width of the RGB image (x dimension) int m_RGBImageHeight; ///< height of the RGB image (y dimension) int m_RGBPixelNumber; ///< number of pixels in the range image (m_RGBImageWidth*m_RGBImageHeight) int m_SourceDataSize; ///< size of the PMD source data itk::MultiThreader::Pointer m_MultiThreader; ///< itk::MultiThreader used for thread handling itk::FastMutexLock::Pointer m_ImageMutex; ///< mutex for images provided by the range camera itk::FastMutexLock::Pointer m_CameraActiveMutex; ///< mutex for the cameraActive flag int m_ThreadID; ///< ID of the started thread bool m_CameraActive; ///< flag indicating if the camera is currently active or not. Caution: thread safe access only! bool m_CameraConnected; ///< flag indicating if the camera is successfully connected or not. Caution: thread safe access only! int m_ImageSequence; ///< counter for acquired images PropertyList::Pointer m_PropertyList; ///< a list of the corresponding properties }; } //END mitk namespace /** ToFCameraDevice is declared a MicroService interface. See MicroService documenation for more details. */ MITK_DECLARE_SERVICE_INTERFACE(mitk::ToFCameraDevice, "org.mitk.services.ToFCameraDevice") #endif diff --git a/Modules/ToFHardware/mitkToFCameraMITKPlayerDevice.h b/Modules/ToFHardware/mitkToFCameraMITKPlayerDevice.h index 003442b818..52662df0c4 100644 --- a/Modules/ToFHardware/mitkToFCameraMITKPlayerDevice.h +++ b/Modules/ToFHardware/mitkToFCameraMITKPlayerDevice.h @@ -1,137 +1,138 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkToFCameraMITKPlayerDevice_h #define __mitkToFCameraMITKPlayerDevice_h #include #include "mitkCommon.h" #include "mitkToFCameraDevice.h" #include "mitkToFCameraMITKPlayerController.h" #include "itkObject.h" #include "itkObjectFactory.h" #include "itkMultiThreader.h" #include "itkFastMutexLock.h" namespace mitk { /** * @brief Device class representing a player for MITK-ToF images. * * @ingroup ToFHardware */ class MITKTOFHARDWARE_EXPORT ToFCameraMITKPlayerDevice : public ToFCameraDevice { public: mitkClassMacro( ToFCameraMITKPlayerDevice , ToFCameraDevice ); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /*! \brief opens a connection to the ToF camera */ bool OnConnectCamera() override; /*! \brief closes the connection to the camera */ bool DisconnectCamera() override; /*! \brief starts the continuous updating of the camera. A separate thread updates the source data, the main thread processes the source data and creates images and coordinates */ void StartCamera() override; /*! \brief gets the amplitude data from the ToF camera as the strength of the active illumination of every pixel. Caution! The user is responsible for allocating and deleting the images. These values can be used to determine the quality of the distance values. The higher the amplitude value, the higher the accuracy of the according distance value \param imageSequence the actually captured image sequence number \param amplitudeArray contains the returned amplitude data as an array. */ void GetAmplitudes(float* amplitudeArray, int& imageSequence) override; /*! \brief gets the intensity data from the ToF camera as a greyscale image. Caution! The user is responsible for allocating and deleting the images. \param intensityArray contains the returned intensities data as an array. \param imageSequence the actually captured image sequence number */ void GetIntensities(float* intensityArray, int& imageSequence) override; /*! \brief gets the rgb data from the ToF camera. Caution! The user is responsible for allocating and deleting the images. \param rgbArray contains the returned rgb data as an array. \param imageSequence the actually captured image sequence number */ virtual void GetRgb(unsigned char* rgbArray, int& imageSequence); /*! \brief gets the distance data from the ToF camera measuring the distance between the camera and the different object points in millimeters. Caution! The user is responsible for allocating and deleting the images. \param distanceArray contains the returned distances data as an array. \param imageSequence the actually captured image sequence number */ void GetDistances(float* distanceArray, int& imageSequence) override; /*! \brief gets the 3 images (distance, amplitude, intensity) from the ToF camera. Caution! The user is responsible for allocating and deleting the images. \param distanceArray contains the returned distance data as an array. \param amplitudeArray contains the returned amplitude data as an array. \param intensityArray contains the returned intensity data as an array. \param sourceDataArray contains the complete source data from the camera device. \param requiredImageSequence the required image sequence number \param capturedImageSequence the actually captured image sequence number + \param rgbDataArray */ void GetAllImages(float* distanceArray, float* amplitudeArray, float* intensityArray, char* sourceDataArray, int requiredImageSequence, int& capturedImageSequence, unsigned char* rgbDataArray=nullptr) override; /*! \brief Set file name where the data is recorded \param inputFileName name of input file which should be played */ virtual void SetInputFileName(std::string inputFileName); /*! \brief set a BaseProperty */ void SetProperty( const char *propertyKey, BaseProperty* propertyValue ) override; protected: ToFCameraMITKPlayerDevice(); ~ToFCameraMITKPlayerDevice() override; /*! \brief updates the camera for image acquisition */ void UpdateCamera() override; /*! \brief Thread method continuously acquiring images from the specified input file */ static ITK_THREAD_RETURN_TYPE Acquire(void* pInfoStruct); /*! \brief Clean up memory (pixel buffers) */ void CleanUpDataBuffers(); /*! \brief Allocate pixel buffers */ void AllocateDataBuffers(); ToFCameraMITKPlayerController::Pointer m_Controller; ///< member holding the corresponding controller std::string m_InputFileName; ///< member holding the file name of the current input file private: float** m_DistanceDataBuffer; ///< buffer holding the last distance images float** m_AmplitudeDataBuffer; ///< buffer holding the last amplitude images float** m_IntensityDataBuffer; ///< buffer holding the last intensity images unsigned char** m_RGBDataBuffer; ///< buffer holding the last rgb images }; } //END mitk namespace #endif diff --git a/Modules/ToFHardware/mitkToFImageCsvWriter.h b/Modules/ToFHardware/mitkToFImageCsvWriter.h index 5b9e4e9be8..f429231c97 100644 --- a/Modules/ToFHardware/mitkToFImageCsvWriter.h +++ b/Modules/ToFHardware/mitkToFImageCsvWriter.h @@ -1,87 +1,88 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkToFImageCsvWriter_h #define __mitkToFImageCsvWriter_h #include "mitkToFImageWriter.h" #include namespace mitk { /** * @brief CSV writer class for ToF image data * * This writer class allows streaming of ToF data into a CSV file. * Writer can simultaneously save "distance", "intensity" and "amplitude" image data. * Output files are written as 1D CSV data stream. * * @ingroup ToFHardware */ class MITKTOFHARDWARE_EXPORT ToFImageCsvWriter : public ToFImageWriter { public: /*! \brief standard ctor */ ToFImageCsvWriter(); /*! \brief standard ~ctor */ ~ToFImageCsvWriter() override; mitkClassMacro( ToFImageCsvWriter , ToFImageWriter ); itkFactorylessNewMacro(Self); itkCloneMacro(Self) /*! \brief Checks for file extensions and opens the output files */ void Open() override; /*! \brief Closes the output files */ void Close() override; /*! \brief Pushes the image data to the output files \param distanceFloatData from distance image as float value \param amplitudeFloatData from amplitude image as float value \param intensityFloatData from intensity image as float value + \param rgbData */ void Add(float* distanceFloatData, float* amplitudeFloatData, float* intensityFloatData, unsigned char* rgbData=nullptr) override; protected: Image::Pointer m_MitkImage; ///< mitk image used for pic header creation FILE* m_DistanceOutfile; ///< file for distance image FILE* m_AmplitudeOutfile; ///< file for amplitude image FILE* m_IntensityOutfile; ///< file for intensity image private: /*! \brief opens CSV output file \param output file, name of the output file */ void OpenCsvFile(FILE** outfile, std::string outfileName); /*! \brief closes CSV output file \param output file */ void CloseCsvFile(FILE* outfile); /*! \brief writes the data to the CSV output file \param output file, data array of float values */ void WriteCsvFile(FILE* outfile, float* floatData); }; } //END mitk namespace #endif // __mitkToFImageCsvWriter_h diff --git a/Modules/ToFHardware/mitkToFOpenCVImageGrabber.h b/Modules/ToFHardware/mitkToFOpenCVImageGrabber.h index 390de1eab5..03a64cadd7 100644 --- a/Modules/ToFHardware/mitkToFOpenCVImageGrabber.h +++ b/Modules/ToFHardware/mitkToFOpenCVImageGrabber.h @@ -1,101 +1,102 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkToFOpenCVImageGrabber_h #define __mitkToFOpenCVImageGrabber_h #include #include "mitkCommon.h" #include "mitkOpenCVImageSource.h" #include "mitkToFImageGrabber.h" #include "itkObject.h" #include "itkObjectFactory.h" namespace mitk { /** * @brief TofImageGrabber class providing OpenCV images * * * @ingroup ToFHardware */ class MITKTOFHARDWARE_EXPORT ToFOpenCVImageGrabber : public mitk::OpenCVImageSource { public: ToFOpenCVImageGrabber(); ~ToFOpenCVImageGrabber() override; mitkClassMacro( ToFOpenCVImageGrabber , OpenCVImageSource ); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /*! \brief Get current ToF image. Specify image you want to grab with SetImageType() */ cv::Mat GetImage() override; /*! \brief set type of image you want to grab. 0: Distance image (Default) 1: Amplitude image 2: Intensity image */ void SetImageType(unsigned int imageType); /*! \brief set the depth of the image. Some functions of OpenCV do not support IPL_DEPTH_32F. Warning: changing from default results in a mapping of the pixel value through a lookup table IPL_DEPTH_1U 1 IPL_DEPTH_8U 8 IPL_DEPTH_16U 16 IPL_DEPTH_32F 32 (Default) */ void SetImageDepth(unsigned int imageDepth); /*! \brief set the ImageGrabber used for fetching image data from the camera */ void SetToFImageGrabber(mitk::ToFImageGrabber::Pointer imageGrabber); /*! \brief get the ImageGrabber used for fetching image data from the camera */ mitk::ToFImageGrabber::Pointer GetToFImageGrabber(); void StartCapturing(); void StopCapturing(); protected: /*! \brief map scalars through lookup table - \param image current MITK image + \param mitkImage current MITK image + \param openCVImage */ void MapScalars(mitk::Image::Pointer mitkImage, IplImage* openCVImage); mitk::ToFImageGrabber::Pointer m_ImageGrabber; ///< ImageGrabber used for fetching ToF image data from the camera unsigned int m_ImageType; ///< type of image currently supplied by this image source /*! \brief image depth currently used by this image source. Warning: Changing from default (IPL_DEPTH_32F) results in a mapping of the pixel value through a lookup table */ unsigned int m_ImageDepth; IplImage* m_CurrentOpenCVIntensityImage; ///< OpenCV image holding the current intensity data IplImage* m_CurrentOpenCVAmplitudeImage; ///< OpenCV image holding the current amplitude data IplImage* m_CurrentOpenCVDistanceImage; ///< OpenCV image holding the current distance data private: }; } //END mitk namespace #endif diff --git a/Modules/ToFProcessing/mitkToFDistanceImageToPointSetFilter.h b/Modules/ToFProcessing/mitkToFDistanceImageToPointSetFilter.h index eef515cdd0..d7e31f4a04 100644 --- a/Modules/ToFProcessing/mitkToFDistanceImageToPointSetFilter.h +++ b/Modules/ToFProcessing/mitkToFDistanceImageToPointSetFilter.h @@ -1,135 +1,135 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkToFDistanceImageToPointSetFilter_h #define __mitkToFDistanceImageToPointSetFilter_h #include #include "mitkImage.h" #include "mitkPointSet.h" #include #include "mitkImageSource.h" #include #include namespace mitk { /** * @brief Converts a Time-of-Flight (ToF) distance image to a PointSet using the pinhole camera model for coordinate computation. * The intrinsic parameters of the camera (FocalLength, PrincipalPoint, InterPixelDistance) are set via SetIntrinsicParameters(). The * measured distance for each pixel corresponds to the distance between the object point and the corresponding image point on the * image plane. * If a subset of indizes of the image is defined via SetSubset(), the output PointSet will only contain the cartesian coordinates * of the corresponding 3D points. * * The coordinate conversion follows the model of a common pinhole camera where the origin of the camera * coordinate system (world coordinates) is at the pinhole - * \image html ../Modules/ToFProcessing/Documentation/PinholeCameraModel.png + * \image html Modules/ToFProcessing/Documentation/PinholeCameraModel.png * The definition of the image plane and its coordinate systems (pixel and mm) is depicted in the following image - * \image html ../Modules/ToFProcessing/Documentation/ImagePlane.png + * \image html Modules/ToFProcessing/Documentation/ImagePlane.png * * @ingroup SurfaceFilters * @ingroup ToFProcessing */ class MITKTOFPROCESSING_EXPORT ToFDistanceImageToPointSetFilter : public PointSetSource { public: mitkClassMacro( ToFDistanceImageToPointSetFilter , PointSetSource ); itkFactorylessNewMacro(Self); itkCloneMacro(Self); itkSetMacro(CameraIntrinsics,mitk::CameraIntrinsics::Pointer); itkGetMacro(CameraIntrinsics,mitk::CameraIntrinsics::Pointer); itkSetMacro(InterPixelDistance,mitk::ToFProcessingCommon::ToFPoint2D); itkGetMacro(InterPixelDistance,mitk::ToFProcessingCommon::ToFPoint2D); using itk::ProcessObject::SetInput; /*! \brief Sets the input of this filter \param distanceImage input is the distance image of e.g. a ToF camera */ virtual void SetInput(const Image* distanceImage); /*! \brief Sets the input of this filter at idx \param idx number of the current input \param distanceImage input is the distance image of e.g. a ToF camera */ virtual void SetInput(unsigned int idx, const Image *distanceImage); /*! \brief Returns the input of this filter */ Image* GetInput(); /*! \brief Returns the input with id idx of this filter */ Image* GetInput(unsigned int idx); /*! \brief If this subset is defined, the cartesian coordinates are only computed for the contained indizes. Make sure the indizes are contained in the input image \param subset index subset specified in index coordinates. */ void SetSubset( std::vector > subset); /*! \brief Sets the subset of indizes used for caluclation of output PointSet as a PointSet. Warning: make sure the points in your PointSet are index coordinates. - \param PointSet specified in index coordinates. + \param pointSet specified in index coordinates. */ void SetSubset( mitk::PointSet::Pointer pointSet); /*! \brief Sets the reconstruction mode, if using no interpixeldistances and focal lenghts in pixel units (=true) or interpixeldistances and focal length in mm (=false) */ void SetReconstructionMode(bool withoutInterpixdist = true); /*! \brief Returns the reconstruction mode */ bool GetReconstructionMode(); protected: /*! \brief Standard constructor */ ToFDistanceImageToPointSetFilter(); /*! \brief Standard destructor */ ~ToFDistanceImageToPointSetFilter() override; void GenerateOutputInformation() override; /*! \brief Method generating the output of this filter. Called in the updated process of the pipeline. This method generates the output of the ToFSurfaceSource: The generated surface of the 3d points */ void GenerateData() override; /** * \brief Create an output for each input * * This Method sets the number of outputs to the number of inputs * and creates missing outputs objects. * \warning any additional outputs that exist before the method is called are deleted */ void CreateOutputsForAllInputs(); std::vector > m_Subset; ///< If this subset is specified only the contained indizes are converted to cartesian coordinates mitk::CameraIntrinsics::Pointer m_CameraIntrinsics; ///< Member holding the intrinsic parameters needed for PointSet calculation ToFProcessingCommon::ToFPoint2D m_InterPixelDistance; ///< distance in mm between two adjacent pixels on the ToF camera chip bool m_ReconstructionMode; ///< true = Reconstruction without interpixeldistance and with focal lengths in pixel units. false = Reconstruction with interpixeldistance and with focal length in mm. }; } //END mitk namespace #endif diff --git a/Modules/ToFProcessing/mitkToFDistanceImageToSurfaceFilter.h b/Modules/ToFProcessing/mitkToFDistanceImageToSurfaceFilter.h index f1cb4f8bb1..1a65814578 100644 --- a/Modules/ToFProcessing/mitkToFDistanceImageToSurfaceFilter.h +++ b/Modules/ToFProcessing/mitkToFDistanceImageToSurfaceFilter.h @@ -1,189 +1,190 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkToFDistanceImageToSurfaceFilter_h #define __mitkToFDistanceImageToSurfaceFilter_h #include #include #include #include #include #include "mitkCameraIntrinsics.h" #include #include #include namespace mitk { /** * @brief Converts a Time-of-Flight (ToF) distance image to a 3D surface using the pinhole camera model for coordinate computation. * The intrinsic parameters of the camera (FocalLength, PrincipalPoint, InterPixelDistance) are set via SetCameraIntrinsics(). The * measured distance for each pixel corresponds to the distance between the object point and the corresponding image point on the * image plane. * * The coordinate conversion follows the model of a common pinhole camera where the origin of the camera * coordinate system (world coordinates) is at the pinhole - * \image html ../Modules/ToFProcessing/Documentation/PinholeCameraModel.png + * \image html Modules/ToFProcessing/Documentation/PinholeCameraModel.png * The definition of the image plane and its coordinate systems (pixel and mm) is depicted in the following image - * \image html ../Modules/ToFProcessing/Documentation/ImagePlane.png + * \image html Modules/ToFProcessing/Documentation/ImagePlane.png * * @ingroup SurfaceFilters * @ingroup ToFProcessing */ class MITKTOFPROCESSING_EXPORT ToFDistanceImageToSurfaceFilter : public SurfaceSource { public: mitkClassMacro( ToFDistanceImageToSurfaceFilter , SurfaceSource ); itkFactorylessNewMacro(Self); itkCloneMacro(Self); itkSetMacro(CameraIntrinsics, mitk::CameraIntrinsics::Pointer); itkGetMacro(CameraIntrinsics, mitk::CameraIntrinsics::Pointer); itkSetMacro(InterPixelDistance,ToFProcessingCommon::ToFPoint2D); itkGetMacro(InterPixelDistance,ToFProcessingCommon::ToFPoint2D); itkSetMacro(TextureIndex,int); /** * @brief SetTriangulationThreshold Sets a triangulation threshold in order * to remove unusually huge faces from the surface. If this value is set, * the filter will check whether the distance between two neighboring vertices * exceeds the triangulation threshold. If yes, there vertices will not be * triangulated (connected with lines). The vertices will still be added to * the surface, but only as single point (if they have no other neighbors). * @param triangulationThreshold The triangulationThreshold in mm. (not mm*mm!) * @note vtkMath::Distance2BetweenPoints returns the squared distance * between two points and hence we square m_TriangulationThreshold in * order to save run-time. */ void SetTriangulationThreshold( double triangulationThreshold ); itkGetMacro(TriangulationThreshold, double); itkSetMacro(VertexIdList, vtkSmartPointer); itkGetMacro(VertexIdList, vtkSmartPointer); itkSetMacro(GenerateTriangularMesh,bool); itkGetMacro(GenerateTriangularMesh,bool); /** * @brief The ReconstructionModeType enum: Defines the reconstruction mode, if using no interpixeldistances and focal lenghts in pixel units or interpixeldistances and focal length in mm. The Kinect option defines a special reconstruction mode for the kinect. */ enum ReconstructionModeType{ WithOutInterPixelDistance = 1, WithInterPixelDistance = 2, Kinect = 3}; itkSetEnumMacro(ReconstructionMode,ReconstructionModeType); itkGetEnumMacro(ReconstructionMode,ReconstructionModeType); /*! \brief Set scalar image used as texture of the surface. \param iplScalarImage OpenCV image for texturing */ void SetScalarImage(IplImage* iplScalarImage); /*! \brief Set scalar image used as texture of the surface. \return OpenCV image for texturing */ IplImage* GetScalarImage(); /*! \brief Set width of the scalar image used for texturing the surface \param width width (x-dimension) of the texture image */ void SetTextureImageWidth(int width); /*! \brief Set height of the scalar image used for texturing the surface \param height height (y-dimension) of the texture image */ void SetTextureImageHeight(int height); using itk::ProcessObject::SetInput; /*! \brief Sets the input of this filter \param distanceImage input is the distance image of e.g. a ToF camera */ virtual void SetInput( Image* distanceImage); /*! \brief Sets the input of this filter and the intrinsic parameters \param distanceImage input is the distance image of e.g. a ToF camera + \param cameraIntrinsics */ virtual void SetInput( Image* distanceImage, mitk::CameraIntrinsics::Pointer cameraIntrinsics ); /*! \brief Sets the input of this filter at idx \param idx number of the current input \param distanceImage input is the distance image of e.g. a ToF camera */ virtual void SetInput(unsigned int idx, Image* distanceImage); /*! \brief Sets the input of this filter at idx and the intrinsic parameters \param idx number of the current input \param distanceImage input is the distance image of e.g. a ToF camera \param cameraIntrinsics This is the camera model which holds parameters like focal length, pixel size, etc. which are needed for the reconstruction of the surface. */ virtual void SetInput( unsigned int idx, Image* distanceImage, mitk::CameraIntrinsics::Pointer cameraIntrinsics ); /*! \brief Returns the input of this filter */ Image* GetInput(); /*! \brief Returns the input with id idx of this filter */ Image* GetInput(unsigned int idx); protected: /*! \brief Standard constructor */ ToFDistanceImageToSurfaceFilter(); /*! \brief Standard destructor */ ~ToFDistanceImageToSurfaceFilter() override; void GenerateOutputInformation() override; /*! \brief Method generating the output of this filter. Called in the updated process of the pipeline. This method generates the output of the ToFSurfaceSource: The generated surface of the 3d points */ void GenerateData() override; /** * \brief Create an output for each input * * This Method sets the number of outputs to the number of inputs * and creates missing outputs objects. * \warning any additional outputs that exist before the method is called are deleted */ void CreateOutputsForAllInputs(); IplImage* m_IplScalarImage; ///< Scalar image used for surface texturing mitk::CameraIntrinsics::Pointer m_CameraIntrinsics; ///< Specifies the intrinsic parameters int m_TextureImageWidth; ///< Width (x-dimension) of the texture image int m_TextureImageHeight; ///< Height (y-dimension) of the texture image ToFProcessingCommon::ToFPoint2D m_InterPixelDistance; ///< distance in mm between two adjacent pixels on the ToF camera chip int m_TextureIndex; ///< Index of the input used as texture image when no scalar image was set via SetIplScalarImage(). 0 = Distance, 1 = Amplitude, 2 = Intensity bool m_GenerateTriangularMesh; ReconstructionModeType m_ReconstructionMode; ///< The ReconstructionModeType enum: Defines the reconstruction mode, if using no interpixeldistances and focal lenghts in pixel units or interpixeldistances and focal length in mm. The Kinect option defines a special reconstruction mode for the kinect. vtkSmartPointer m_VertexIdList; ///< Make a vtkIdList to save the ID's of the polyData corresponding to the image pixel ID's. This can be accessed after generate data to obtain the mapping. double m_TriangulationThreshold; }; } //END mitk namespace #endif diff --git a/Modules/ToFProcessing/mitkToFImageDownsamplingFilter.h b/Modules/ToFProcessing/mitkToFImageDownsamplingFilter.h index 48010ea256..80f1b164bf 100644 --- a/Modules/ToFProcessing/mitkToFImageDownsamplingFilter.h +++ b/Modules/ToFProcessing/mitkToFImageDownsamplingFilter.h @@ -1,81 +1,79 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkToFImageDownsamplingFilter_h #define __mitkToFImageDownsamplingFilter_h //MITK includes #include #include "mitkImageToImageFilter.h" #include // ITK includes #include "itkImage.h" namespace mitk { /** * @brief Reduces the resolution of a ToF distance image. Although it is meant to be used for ToF distance images, it should work * for any 2D or 3D images. The dimensions (in pixels) of the desired image are taken as input parameters, and an image with these * specified dimensions is created. * * @ingroup SurfaceFilters * @ingroup ToFProcessing */ class MITKTOFPROCESSING_EXPORT ToFImageDownsamplingFilter : public ImageToImageFilter { public: mitkClassMacro(ToFImageDownsamplingFilter, ImageToImageFilter); itkFactorylessNewMacro(Self); itkCloneMacro(Self); itkSetMacro(ResampledX,double); itkGetMacro(ResampledX,double); itkSetMacro(ResampledY,double); itkGetMacro(ResampledY,double); itkSetMacro(ResampledZ,double); itkGetMacro(ResampledZ,double); protected: /*! \brief Standard constructor */ ToFImageDownsamplingFilter(); /*! \brief Standard destructor */ ~ToFImageDownsamplingFilter() override; /*! \brief Method generating the output of this filter. Called in the updated process of the pipeline. This method calls the AccessFixedDimensionByItk class with the ItkImageResampling function below */ void GenerateData() override; /*! \brief Templated method for ITK image type which performs the resampling with an itk filter. \param itkImage is the input to the filter converted to ITK format - \param TPixel is a pixel type such as float or char or double - \param VImageDimension is the image dimension (2D or 3D) */ template void ItkImageResampling( const itk::Image* itkImage ); double m_ResampledX;///< length of x dimension of output image in pixels double m_ResampledY;///< length of y dimension of output image in pixels double m_ResampledZ;///< length of z dimension of output image in pixels (if 2D, default is set to 1) }; }// end namespace mitk #endif diff --git a/Modules/ToFProcessing/mitkToFProcessingCommon.h b/Modules/ToFProcessing/mitkToFProcessingCommon.h index 8944ce73c3..02cecea635 100644 --- a/Modules/ToFProcessing/mitkToFProcessingCommon.h +++ b/Modules/ToFProcessing/mitkToFProcessingCommon.h @@ -1,341 +1,338 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKTOFPROCESSINGCOMMON_H #define MITKTOFPROCESSINGCOMMON_H #include #include #include "mitkNumericTypes.h" #include namespace mitk { /** * @brief Helper class providing functions which are useful for multiple usage * * Currently the following methods are provided: *
      *
    • Conversion from 2D image coordinates to 3D world coordinates (IndexToCartesianCoordinates()) *
    • Conversion from 3D world coordinates to 2D image coordinates (CartesianToIndexCoordinates()) *
    * The coordinate conversion follows the model of a common pinhole camera where the origin of the camera * coordinate system (world coordinates) is at the pinhole - * \image html ../Modules/ToFProcessing/Documentation/PinholeCameraModel.png + * \image html Modules/ToFProcessing/Documentation/PinholeCameraModel.png * The definition of the image plane and its coordinate systems (pixel and mm) is depicted in the following image - * \image html ../Modules/ToFProcessing/Documentation/ImagePlane.png + * \image html Modules/ToFProcessing/Documentation/ImagePlane.png * @ingroup ToFProcessing */ class MITKTOFPROCESSING_EXPORT ToFProcessingCommon { public: typedef double ToFScalarType; typedef itk::Point ToFPoint2D; typedef itk::Point ToFPoint3D; typedef itk::Vector ToFVector2D; typedef itk::Vector ToFVector3D; /*! \brief Convert index based distances to cartesian coordinates \param i index in x direction of image plane \param j index in y direction of image plane \param distance distance value at given index in mm \param focalLengthX focal length of optical system in pixel units in x-direction (mostly obtained from camera calibration) \param focalLengthY focal length of optical system in pixel units in y-direction (mostly obtained from camera calibration) \param principalPointX x coordinate of principal point on image plane in pixel \param principalPointY y coordinate of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ static ToFPoint3D IndexToCartesianCoordinates(unsigned int i, unsigned int j, ToFScalarType distance, ToFScalarType focalLengthX, ToFScalarType focalLengthY, ToFScalarType principalPointX, ToFScalarType principalPointY); /*! \brief Convert index based distances to cartesian coordinates \param i index in x direction of image plane \param j index in y direction of image plane \param distance distance value at given index in mm \param focalLength focal length of optical system in pixel units (mostly obtained from camera calibration) \param principalPoint coordinates of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ static ToFPoint3D IndexToCartesianCoordinates(unsigned int i, unsigned int j, ToFScalarType distance, ToFPoint2D focalLength, ToFPoint2D principalPoint) { return IndexToCartesianCoordinates(i,j,distance,focalLength[0],focalLength[1],principalPoint[0],principalPoint[1]); } /*! \brief Convert index based distances to cartesian coordinates \param index index coordinates \param distance distance value at given index in mm \param focalLength focal length of optical system in pixel units (mostly obtained from camera calibration) \param principalPoint coordinates of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ static ToFPoint3D IndexToCartesianCoordinates(itk::Index<3> index, ToFScalarType distance, ToFPoint2D focalLength, ToFPoint2D principalPoint) { return IndexToCartesianCoordinates(index[0],index[1],distance,focalLength[0],focalLength[1],principalPoint[0], principalPoint[1]); } /*! \brief Convenience method to convert index based distances to cartesian coordinates using array as input \param i index in x direction of image plane \param j index in y direction of image plane \param distance distance value at given index in mm \param focalLength focal length of optical system in pixel units (mostly obtained from camera calibration) \param principalPoint coordinates of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ static ToFPoint3D IndexToCartesianCoordinates(unsigned int i, unsigned int j, ToFScalarType distance, ToFScalarType focalLength[2], ToFScalarType principalPoint[2]) { return IndexToCartesianCoordinates(i,j,distance,focalLength[0],focalLength[1],principalPoint[0],principalPoint[1]); } /*! \brief Convert index based distances to cartesian coordinates \param i index in x direction of image plane \param j index in y direction of image plane \param distance distance value at given index in mm \param focalLength focal length of optical system in mm (mostly obtained from camera calibration) \param interPixelDistanceX distance in x direction between adjacent pixels in mm \param interPixelDistanceY distance in y direction between adjacent pixels in mm \param principalPointX x coordinate of principal point on image plane in pixel \param principalPointY y coordinate of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ static ToFPoint3D IndexToCartesianCoordinatesWithInterpixdist(unsigned int i, unsigned int j, ToFScalarType distance, ToFScalarType focalLength, ToFScalarType interPixelDistanceX, ToFScalarType interPixelDistanceY, ToFScalarType principalPointX, ToFScalarType principalPointY); /*! \brief Convert index based distances to cartesian coordinates \param i index in x direction of image plane \param j index in y direction of image plane \param distance distance value at given index in mm \param focalLength focal length of optical system in mm (mostly obtained from camera calibration) \param interPixelDistance distance between adjacent pixels in mm \param principalPoint coordinates of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ static ToFPoint3D IndexToCartesianCoordinatesWithInterpixdist(unsigned int i, unsigned int j, ToFScalarType distance, ToFScalarType focalLength, ToFPoint2D interPixelDistance, ToFPoint2D principalPoint) { return IndexToCartesianCoordinatesWithInterpixdist(i,j,distance,focalLength,interPixelDistance[0],interPixelDistance[1],principalPoint[0],principalPoint[1]); } /*! \brief Convert index based distances to cartesian coordinates \param index index coordinates \param distance distance value at given index in mm \param focalLength focal length of optical system (mostly obtained from camera calibration) \param interPixelDistance distance between adjacent pixels in mm for x and y direction \param principalPoint coordinates of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ static ToFPoint3D IndexToCartesianCoordinatesWithInterpixdist(itk::Index<3> index, ToFScalarType distance, ToFScalarType focalLength, ToFPoint2D interPixelDistance, ToFPoint2D principalPoint) { return IndexToCartesianCoordinatesWithInterpixdist(index[0],index[1],distance,focalLength,interPixelDistance[0], interPixelDistance[1],principalPoint[0], principalPoint[1]); } /*! \brief Convenience method to convert index based distances to cartesian coordinates using array as input \param i index in x direction of image plane \param j index in y direction of image plane \param distance distance value at given index in mm \param focalLength focal length of optical system in mm (mostly obtained from camera calibration) \param interPixelDistance distance between adjacent pixels in mm \param principalPoint coordinates of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ static ToFPoint3D IndexToCartesianCoordinatesWithInterpixdist(unsigned int i, unsigned int j, ToFScalarType distance, ToFScalarType focalLength, ToFScalarType interPixelDistance[2], ToFScalarType principalPoint[2]) { return IndexToCartesianCoordinatesWithInterpixdist(i,j,distance,focalLength,interPixelDistance[0],interPixelDistance[1],principalPoint[0],principalPoint[1]); } /*! \brief Convert cartesian coordinates to index based distances \param cartesianPointX x coordinate of point (of a surface or point set) to convert in 3D coordinates \param cartesianPointY y coordinate of point (of a surface or point set) to convert in 3D coordinates \param cartesianPointZ z coordinate of point (of a surface or point set) to convert in 3D coordinates \param focalLengthX focal length of optical system in pixel units in x-direction (mostly obtained from camera calibration) \param focalLengthY focal length of optical system in pixel units in y-direction (mostly obtained from camera calibration) \param principalPointX x coordinate of principal point on image plane in pixel \param principalPointY y coordinate of principal point on image plane in pixel \param calculateDistance if this flag is set, the distance value is stored in the z position of the output otherwise z=0 \return a ToFPoint3D. (int)ToFPoint3D[0]+0.5 and (int)ToFPoint3D[0]+0.5 will return the x and y index coordinates. ToFPoint3D[2] contains the distance value */ static ToFPoint3D CartesianToIndexCoordinates(ToFScalarType cartesianPointX, ToFScalarType cartesianPointY,ToFScalarType cartesianPointZ, ToFScalarType focalLengthX, ToFScalarType focalLengthY, ToFScalarType principalPointX, ToFScalarType principalPointY, bool calculateDistance=true); /*! \brief Convenience method to convert cartesian coordinates to index based distances using arrays \param cartesianPoint point (of a surface or point set) to convert in 3D coordinates \param focalLength focal length of optical system in pixel units (mostly obtained from camera calibration) \param principalPoint coordinates of principal point on image plane in pixel \param calculateDistance if this flag is set, the distance value is stored in the z position of the output otherwise z=0 \return a ToFPoint3D. (int)ToFPoint3D[0]+0.5 and (int)ToFPoint3D[0]+0.5 will return the x and y index coordinates. ToFPoint3D[2] contains the distance value */ static ToFPoint3D CartesianToIndexCoordinates(ToFScalarType cartesianPoint[3], ToFScalarType focalLength[2], ToFScalarType principalPoint[2], bool calculateDistance=true) { return CartesianToIndexCoordinates(cartesianPoint[0],cartesianPoint[1],cartesianPoint[2],focalLength[0], focalLength[1], principalPoint[0],principalPoint[1],calculateDistance); } /*! \brief Convert cartesian coordinates to index based distances \param cartesianPoint point (of a surface or point set) to convert in 3D coordinates \param focalLength focal length of optical system in pixel units (mostly obtained from camera calibration) \param principalPoint coordinates of principal point on image plane in pixel \param calculateDistance if this flag is set, the distance value is stored in the z position of the output otherwise z=0 \return a ToFPoint3D. (int)ToFPoint3D[0]+0.5 and (int)ToFPoint3D[0]+0.5 will return the x and y index coordinates. ToFPoint3D[2] contains the distance value */ static ToFPoint3D CartesianToIndexCoordinates(ToFPoint3D cartesianPoint, ToFPoint2D focalLength, ToFPoint2D principalPoint, bool calculateDistance=true) { return CartesianToIndexCoordinates(cartesianPoint[0],cartesianPoint[1],cartesianPoint[2],focalLength[0], focalLength[1], principalPoint[0],principalPoint[1],calculateDistance); } /*! \brief Convert cartesian coordinates to index based distances \param cartesianPointX x coordinate of point (of a surface or point set) to convert in 3D coordinates \param cartesianPointY y coordinate of point (of a surface or point set) to convert in 3D coordinates \param cartesianPointZ z coordinate of point (of a surface or point set) to convert in 3D coordinates \param focalLength focal length of optical system in mm (mostly obtained from camera calibration) \param interPixelDistanceX distance in x direction between adjacent pixels in mm \param interPixelDistanceY distance in y direction between adjacent pixels in mm \param principalPointX x coordinate of principal point on image plane in pixel \param principalPointY y coordinate of principal point on image plane in pixel \param calculateDistance if this flag is set, the distance value is stored in the z position of the output otherwise z=0 \return a ToFPoint3D. (int)ToFPoint3D[0]+0.5 and (int)ToFPoint3D[0]+0.5 will return the x and y index coordinates. ToFPoint3D[2] contains the distance value */ static ToFPoint3D CartesianToIndexCoordinatesWithInterpixdist(ToFScalarType cartesianPointX, ToFScalarType cartesianPointY,ToFScalarType cartesianPointZ, ToFScalarType focalLength, ToFScalarType interPixelDistanceX, ToFScalarType interPixelDistanceY, ToFScalarType principalPointX, ToFScalarType principalPointY, bool calculateDistance=true); /*! \brief Convenience method to convert cartesian coordinates to index based distances using arrays \param cartesianPoint point (of a surface or point set) to convert in 3D coordinates \param focalLength focal length of optical system in mm (mostly obtained from camera calibration) \param interPixelDistance distance between adjacent pixels in mm for x and y direction \param principalPoint coordinates of principal point on image plane in pixel \param calculateDistance if this flag is set, the distance value is stored in the z position of the output otherwise z=0 \return a ToFPoint3D. (int)ToFPoint3D[0]+0.5 and (int)ToFPoint3D[0]+0.5 will return the x and y index coordinates. ToFPoint3D[2] contains the distance value */ static ToFPoint3D CartesianToIndexCoordinatesWithInterpixdist(ToFScalarType cartesianPoint[3], ToFScalarType focalLength, ToFScalarType interPixelDistance[2], ToFScalarType principalPoint[2], bool calculateDistance=true) { return CartesianToIndexCoordinatesWithInterpixdist(cartesianPoint[0],cartesianPoint[1],cartesianPoint[2],focalLength, interPixelDistance[0],interPixelDistance[1],principalPoint[0],principalPoint[1],calculateDistance); } /*! \brief Convert cartesian coordinates to index based distances \param cartesianPoint point (of a surface or point set) to convert in 3D coordinates \param focalLength focal length of optical system in mm (mostly obtained from camera calibration) \param interPixelDistance distance between adjacent pixels in mm for x and y direction \param principalPoint coordinates of principal point on image plane in pixel \param calculateDistance if this flag is set, the distance value is stored in the z position of the output otherwise z=0 \return a ToFPoint3D. (int)ToFPoint3D[0]+0.5 and (int)ToFPoint3D[0]+0.5 will return the x and y index coordinates. ToFPoint3D[2] contains the distance value */ static ToFPoint3D CartesianToIndexCoordinatesWithInterpixdist(ToFPoint3D cartesianPoint, ToFScalarType focalLength, ToFPoint2D interPixelDistance, ToFPoint2D principalPoint, bool calculateDistance=true) { return CartesianToIndexCoordinatesWithInterpixdist(cartesianPoint[0],cartesianPoint[1],cartesianPoint[2],focalLength, interPixelDistance[0],interPixelDistance[1],principalPoint[0],principalPoint[1],calculateDistance); } /** \ingroup KinectReconstruction - * @{ - * * @brief KinectIndexToCartesianCoordinates Convert a pixel (i,j) with value d to a 3D world point. This conversion is meant for Kinect and slightly different then ToF reconstruction. See also "Hacking the Kinect" - Jeff Kramer, Matt Parker, Daniel Herrera C., Nicolas Burrus, Florian Echtler, Chapter 7, Part 1 "Moving from Depth Map to Point Cloud. * @param i Pixel index i. * @param j Pixel index j. * @param distance Distance value d in mm as obtained from OpenNI. * @param focalLengthX Focallength from calibration. * @param focalLengthY Focallength from calibration. * @param principalPointX Principal point from calibration. * @param principalPointY Principal point from calibration. * @return a ToFPoint3D. The point in world coordinates (mm). */ static ToFProcessingCommon::ToFPoint3D KinectIndexToCartesianCoordinates(unsigned int i, unsigned int j, ToFScalarType distance, ToFScalarType focalLengthX, ToFScalarType focalLengthY, ToFScalarType principalPointX, ToFScalarType principalPointY); static ToFPoint3D KinectIndexToCartesianCoordinates(unsigned int i, unsigned int j, ToFScalarType distance, ToFScalarType focalLength[2], ToFScalarType principalPoint[2]) { return KinectIndexToCartesianCoordinates(i,j,distance,focalLength[0],focalLength[1],principalPoint[0],principalPoint[1]); } static ToFPoint3D KinectIndexToCartesianCoordinates(unsigned int i, unsigned int j, ToFScalarType distance, ToFPoint2D focalLength, ToFPoint2D principalPoint) { return KinectIndexToCartesianCoordinates(i,j,distance,focalLength[0],focalLength[1],principalPoint[0],principalPoint[1]); } static ToFPoint3D KinectIndexToCartesianCoordinates(itk::Index<3> index, ToFScalarType distance, ToFPoint2D focalLength, ToFPoint2D principalPoint) { return KinectIndexToCartesianCoordinates(index[0],index[1],distance,focalLength[0],focalLength[1],principalPoint[0], principalPoint[1]); } - /** @}*/ + /** \ingroup KinectReconstructionInverse - * @{ * @brief CartesianCoordinatesToKinectIndexCoordinates Transform a 3D world point back to distance image pixel coordinates. * @param cartesianPointX x value of the cartesian point. * @param cartesianPointY y value of the cartesian point. * @param cartesianPointZ z value of the cartesian point. * @param focalLengthX x value of the focal length (from calibration). * @param focalLengthY y value of the focal length (from calibration). * @param principalPointX x value of the principal point (from calibration). * @param principalPointY y value of the principal point (from calibration). * @param calculateDistance Do you want to compute also the distance of the distance image? For Kinect, this value is always the same in cartesian and index coordinates. * @return A ToFPoint3D containing the pixel indices (i,j) in [0] and [1] and (optionally) the distance value in [2] (or just 0.0). */ static ToFPoint3D CartesianToKinectIndexCoordinates(ToFScalarType cartesianPointX, ToFScalarType cartesianPointY, ToFScalarType cartesianPointZ, ToFScalarType focalLengthX, ToFScalarType focalLengthY, ToFScalarType principalPointX, ToFScalarType principalPointY, bool calculateDistance=true); static ToFProcessingCommon::ToFPoint3D CartesianToKinectIndexCoordinates(ToFPoint3D cartesianPoint, ToFPoint2D focalLength, ToFPoint2D principalPoint, bool calculateDistance=true) { return CartesianToKinectIndexCoordinates( cartesianPoint[0], cartesianPoint[1], cartesianPoint[2], focalLength[0], focalLength[1], principalPoint[0], principalPoint[1], calculateDistance); } - /** @}*/ + /** * @brief ContinuousKinectIndexToCartesianCoordinates This method is escpially meant for reconstructing a Kinect point * with continuous index coordinates (i.e. not exactly a pixel position, but a point interpolated between two pixels). * The only difference to KinectIndexToCartesianCoordinates() is that ContinuousKinectIndexToCartesianCoordinates does not * cast to unsigned int for the index. * @param continuousIndex The continuous coordinates (e.g. 0.5; 0.5). * @param distance Distance value d in mm as obtained from OpenNI. * @param focalLengthX x value of the focal length (from calibration). * @param focalLengthY y value of the focal length (from calibration) * @param principalPointX x value of the principal point (from calibration). * @param principalPointY y value of the principal point (from calibration). * @return a ToFPoint3D. The point in world coordinates (mm). */ static ToFProcessingCommon::ToFPoint3D ContinuousKinectIndexToCartesianCoordinates(mitk::Point2D continuousIndex, ToFScalarType distance, ToFScalarType focalLengthX, ToFScalarType focalLengthY, ToFScalarType principalPointX, ToFScalarType principalPointY); /** \brief Calculates the horizontal view angle of the camera with the given intrinsics \param intrinsics intrinsic parameters of the camera \param dimX dimension of the image in horizontal direction angle = atan(principalPoint[0]/focalLength[0]) + atan((dimX-principalPoint[0]/focalLength[0])) **/ static ToFScalarType CalculateViewAngle(mitk::CameraIntrinsics::Pointer intrinsics, unsigned int dimX); }; } #endif diff --git a/Modules/TubeGraph/include/mitkTubeGraphProperty.h b/Modules/TubeGraph/include/mitkTubeGraphProperty.h index 856c251ed0..090b346989 100644 --- a/Modules/TubeGraph/include/mitkTubeGraphProperty.h +++ b/Modules/TubeGraph/include/mitkTubeGraphProperty.h @@ -1,146 +1,146 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _mitk_TubeGraphProperty_h #define _mitk_TubeGraphProperty_h #include #include "mitkTubeGraph.h" #include #include #include #include #include namespace mitk { /** * \brief Property for tube graphs */ class MITKTUBEGRAPH_EXPORT TubeGraphProperty : public BaseProperty { public: mitkClassMacro(TubeGraphProperty, BaseProperty); itkNewMacro(TubeGraphProperty); struct LabelGroup { struct Label { std::string labelName; bool isVisible; Color labelColor; }; std::string labelGroupName; std::vector