<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "itkQuaternionRigidTransform.h"
#include "itkMutualInformationImageToImageMetric.h"
#include "itkQuaternionRigidTransformGradientDescentOptimizer.h"

#include "itkTextOutput.h"
#include "itkSimpleMultiResolutionImageRegistrationUI.h"

namespace
{

double F( itk::Vector<double,3> & v );
}

/**
 *  This program test one instantiation of the
 *  itk::MultiResolutionImageRegistrationMethod class
 *
 *  This file tests the combination of:
 *   - MutualInformation
 *   - QuaternionRigidTransform
 *   - QuaternionRigidTransformGradientDescentOptimizer
 *   - LinearInterpolateImageFunction
 *   - RecursiveMultiResolutionPyramidImageFilter
 *
 *  The test image pattern consists of a 3D gaussian in the middle
 *  with some directional pattern on the outside.
 *  One image is rotated and shifted relative to the other.
 *
 * Notes:
 * =====
 * This example performs an rigid
 * registration between a 3D moving image and a 3D fixed image using
 * mutual information and a multi-resolution strategy.
 *
 * See notes for itkImageRegistrationMethodTest_14.cxx for more
 * detailed information on the algorithm.
 *
 * A simple user-interface, allows the user to define the number
 * of iteration and learning rate at each resolution level.
 *
 */

int itkMultiResolutionImageRegistrationMethodTest_2(int, char* [] )
{

  itk::OutputWindow::SetInstance(itk::TextOutput::New().GetPointer());

  bool pass = true;

  const unsigned int dimension = 3;
  unsigned int j;

  typedef float  PixelType;

  // Fixed Image Type
  typedef itk::Image<PixelType,dimension>               FixedImageType;

  // Moving Image Type
  typedef itk::Image<PixelType,dimension>               MovingImageType;

  // Transform Type
  typedef itk::QuaternionRigidTransform< double >       TransformType;

  // Optimizer Type
  typedef itk::QuaternionRigidTransformGradientDescentOptimizer
                                                         OptimizerType;

  // Metric Type
  typedef itk::MutualInformationImageToImageMetric<
                                    FixedImageType,
                                    MovingImageType >    MetricType;

  // Interpolation technique
  typedef itk:: LinearInterpolateImageFunction<
                                    MovingImageType,
                                    double          >    InterpolatorType;

  // Fixed Image Pyramid Type
  typedef itk::RecursiveMultiResolutionPyramidImageFilter<
                                    FixedImageType,
                                    FixedImageType  >    FixedImagePyramidType;

  // Moving Image Pyramid Type
  typedef itk::RecursiveMultiResolutionPyramidImageFilter<
                                    MovingImageType,
                                    MovingImageType  >   MovingImagePyramidType;

  // Registration Method
  typedef itk::MultiResolutionImageRegistrationMethod<
                                    FixedImageType,
                                    MovingImageType >    RegistrationType;

  MetricType::Pointer         metric        = MetricType::New();
  TransformType::Pointer      transform     = TransformType::New();
  OptimizerType::Pointer      optimizer     = OptimizerType::New();
  FixedImageType::Pointer     fixedImage    = FixedImageType::New();
  MovingImageType::Pointer    movingImage   = MovingImageType::New();
  InterpolatorType::Pointer   interpolator  = InterpolatorType::New();
  FixedImagePyramidType::Pointer fixedImagePyramid =
    FixedImagePyramidType::New();
  MovingImagePyramidType::Pointer movingImagePyramid =
    MovingImagePyramidType::New();
  RegistrationType::Pointer   registration  = RegistrationType::New();

  /*********************************************************
   * Set up the two input images.
   * One image rotated (xy plane) and shifted with respect to the other.
   **********************************************************/
  double displacement[dimension] = {7,3,2};
  double angle = 10.0 / 180.0 * itk::Math::pi;

  FixedImageType::SizeType size = {{100,100,40}};
  FixedImageType::IndexType index = {{0,0,0}};
  FixedImageType::RegionType region;
  region.SetSize( size );
  region.SetIndex( index );

  fixedImage->SetLargestPossibleRegion( region );
  fixedImage->SetBufferedRegion( region );
  fixedImage->SetRequestedRegion( region );
  fixedImage->Allocate();

  movingImage->SetLargestPossibleRegion( region );
  movingImage->SetBufferedRegion( region );
  movingImage->SetRequestedRegion( region );
  movingImage->Allocate();

  typedef itk::ImageRegionIterator<MovingImageType> MovingImageIterator;
  typedef itk::ImageRegionIterator<FixedImageType>  FixedImageIterator;

  itk::Point<double,dimension> center;
  for ( j = 0; j < dimension; j++ )
    {
    center[j] = 0.5 *  (double)region.GetSize()[j];
    }

  itk::Point<double,dimension> p;
  itk::Vector<double,dimension> d, d2;

  MovingImageIterator mIter( movingImage, region );
  FixedImageIterator  fIter( fixedImage, region );

  while( !mIter.IsAtEnd() )
    {
    for ( j = 0; j < dimension; j++ )
      {
      p[j] = mIter.GetIndex()[j];
      }

    d = p - center;

    fIter.Set( (PixelType) F(d) );

    d2[0] =  d[0] * std::cos(angle) + d[1] * std::sin(angle) + displacement[0];
    d2[1] = -d[0] * std::sin(angle) + d[1] * std::cos(angle) + displacement[1];
    d2[2] = d[2] + displacement[2];

    mIter.Set( (PixelType) F(d2) );

    ++fIter;
    ++mIter;

    }

  // set the image origin to be center of the image
  double transCenter[dimension];
  for ( j = 0; j < dimension; j++ )
    {
    transCenter[j] = -0.5 * double(size[j]);
    }

  movingImage->SetOrigin( transCenter );
  fixedImage->SetOrigin( transCenter );

  /******************************************************************
   * Set up the optimizer.
   ******************************************************************/

  // set the translation scale
  typedef OptimizerType::ScalesType ScalesType;
  ScalesType parametersScales( transform->GetNumberOfParameters() );

  parametersScales.Fill( 1.0 );

  for ( j = 4; j < 7; j++ )
    {
    parametersScales[j] = 0.0001;
    }

  optimizer->SetScales( parametersScales );

  // need to maximize for mutual information
  optimizer->MaximizeOn();

  /******************************************************************
   * Set up the optimizer observer
   ******************************************************************/
/*
  typedef itk::CommandIterationUpdate< OptimizerType > CommandIterationType;
  CommandIterationType::Pointer iterationCommand =
    CommandIterationType::New();

  iterationCommand->SetOptimizer( optimizer );
*/

  /******************************************************************
   * Set up the metric.
   ******************************************************************/
  metric->SetMovingImageStandardDeviation( 5.0 );
  metric->SetFixedImageStandardDeviation( 5.0 );
  metric->SetNumberOfSpatialSamples( 50 );

  /******************************************************************
   * Set up the registrator.
   ******************************************************************/

  // connect up the components
  registration->SetMetric( metric );
  registration->SetOptimizer( optimizer );
  registration->SetTransform( transform );
  registration->SetFixedImage( fixedImage );
  registration->SetMovingImage( movingImage );
  registration->SetInterpolator( interpolator );
  registration->SetFixedImagePyramid( fixedImagePyramid );
  registration->SetMovingImagePyramid( movingImagePyramid );
  registration->SetFixedImageRegion( fixedImage->GetBufferedRegion() );

  // set initial parameters to identity
  RegistrationType::ParametersType initialParameters(
    transform->GetNumberOfParameters() );

  initialParameters.Fill( 0.0 );
  initialParameters[3] = 1.0;

  /******************************************************************
   * Attach registration to a simple UI and run registration
   ******************************************************************/
  SimpleMultiResolutionImageRegistrationUI2<RegistrationType>
    simpleUI( registration );

  unsigned short numberOfLevels = 3;

  itk::Array<unsigned int> niter( numberOfLevels );
  itk::Array<double>       rates( numberOfLevels );

  niter[0] = 300;
  niter[1] = 300;
  niter[2] = 350;

  rates[0] = 1e-3;
  rates[1] = 5e-4;
  rates[2] = 1e-4;

  simpleUI.SetNumberOfIterations( niter );
  simpleUI.SetLearningRates( rates );

  try
    {
    registration->SetNumberOfLevels( numberOfLevels );
    registration->SetInitialTransformParameters( initialParameters );
    registration->Update();
    }
  catch( itk::ExceptionObject & e )
    {
    std::cout << "Registration failed" << std::endl;
    std::cout << "Reason " << e.GetDescription() << std::endl;
    return EXIT_FAILURE;
    }

  /***********************************************************
   * Check the results
   ************************************************************/
  RegistrationType::ParametersType solution =
    registration->GetLastTransformParameters();

  std::cout << "Solution is: " << solution << std::endl;

  RegistrationType::ParametersType trueParameters(
    transform->GetNumberOfParameters() );
  trueParameters.Fill( 0.0 );
  trueParameters[2] =   std::sin( angle / 2.0 );
  trueParameters[3] =   std::cos( angle / 2.0 );
  trueParameters[4] = -1.0 * ( displacement[0] * std::cos(angle) -
                               displacement[1] * std::sin(angle) );
  trueParameters[5] = -1.0 * ( displacement[0] * std::sin(angle) +
                               displacement[1] * std::cos(angle) );
  trueParameters[6] = -1.0 * displacement[2];

  std::cout << "True solution is: " << trueParameters << std::endl;

  for( j = 0; j < 4; j++ )
    {
    if( itk::Math::abs( solution[j] - trueParameters[j] ) > 0.025 )
      {
      pass = false;
      }
    }
  for( j = 4; j < 7; j++ )
    {
    if( itk::Math::abs( solution[j] - trueParameters[j] ) > 1.0 )
      {
      pass = false;
      }
    }

  if( !pass )
    {
    std::cout << "Test failed." << std::endl;
    return EXIT_FAILURE;
    }

  /*************************************************
   * Check for parzen window exception
   **************************************************/
  double oldValue = metric->GetMovingImageStandardDeviation();
  metric->SetMovingImageStandardDeviation( 0.005 );

  try
    {
    pass = false;
    registration->Update();
    }
  catch(itk::ExceptionObject& err)
    {
    std::cout << "Caught expected ExceptionObject" << std::endl;
    std::cout << err << std::endl;
    pass = true;
    }

  if( !pass )
    {
    std::cout << "Should have caught an exception" << std::endl;
    std::cout << "Test failed." << std::endl;
    return EXIT_FAILURE;
    }

  metric->SetMovingImageStandardDeviation( oldValue );

  /*************************************************
   * Check for mapped out of image error
   **************************************************/
  solution[5] = 1000;
  registration->SetInitialTransformParameters( solution );

  try
    {
    pass = false;
    registration->Update();
    }
  catch(itk::ExceptionObject& err)
    {
    std::cout << "Caught expected ExceptionObject" << std::endl;
    std::cout << err << std::endl;
    pass = true;
    }

  if( !pass )
    {
    std::cout << "Should have caught an exception" << std::endl;
    std::cout << "Test failed." << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Test passed." << std::endl;
  return EXIT_SUCCESS;

}

namespace
{

/**
 * This function defines the test image pattern.
 * The pattern is a 3D gaussian in the middle
 * and some directional pattern on the outside.
 */
double F( itk::Vector<double,3> & v )
{
  double x = v[0];
  double y = v[1];
  double z = v[2];
  const double s = 50;
  double value = 200.0 * std::exp( - ( x*x + y*y + z*z )/(s*s) );
  x -= 8; y += 3; z += 0;
  double r = std::sqrt( x*x + y*y + z*z );
  if( r > 35 )
    {
    value = 2 * ( itk::Math::abs( x ) +
      0.8 * itk::Math::abs( y ) +
      0.5 * itk::Math::abs( z ) );
    }
  if( r < 4 )
    {
    value = 400;
    }

  return value;

}
}
<commit_msg>BUG: Initialized the sampling seed for v3 registration test<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "itkQuaternionRigidTransform.h"
#include "itkMutualInformationImageToImageMetric.h"
#include "itkQuaternionRigidTransformGradientDescentOptimizer.h"

#include "itkTextOutput.h"
#include "itkSimpleMultiResolutionImageRegistrationUI.h"

namespace
{

double F( itk::Vector<double,3> & v );
}

/**
 *  This program test one instantiation of the
 *  itk::MultiResolutionImageRegistrationMethod class
 *
 *  This file tests the combination of:
 *   - MutualInformation
 *   - QuaternionRigidTransform
 *   - QuaternionRigidTransformGradientDescentOptimizer
 *   - LinearInterpolateImageFunction
 *   - RecursiveMultiResolutionPyramidImageFilter
 *
 *  The test image pattern consists of a 3D gaussian in the middle
 *  with some directional pattern on the outside.
 *  One image is rotated and shifted relative to the other.
 *
 * Notes:
 * =====
 * This example performs an rigid
 * registration between a 3D moving image and a 3D fixed image using
 * mutual information and a multi-resolution strategy.
 *
 * See notes for itkImageRegistrationMethodTest_14.cxx for more
 * detailed information on the algorithm.
 *
 * A simple user-interface, allows the user to define the number
 * of iteration and learning rate at each resolution level.
 *
 */

int itkMultiResolutionImageRegistrationMethodTest_2(int, char* [] )
{

  itk::OutputWindow::SetInstance(itk::TextOutput::New().GetPointer());

  bool pass = true;

  const unsigned int dimension = 3;
  unsigned int j;

  typedef float  PixelType;

  // Fixed Image Type
  typedef itk::Image<PixelType,dimension>               FixedImageType;

  // Moving Image Type
  typedef itk::Image<PixelType,dimension>               MovingImageType;

  // Transform Type
  typedef itk::QuaternionRigidTransform< double >       TransformType;

  // Optimizer Type
  typedef itk::QuaternionRigidTransformGradientDescentOptimizer
                                                         OptimizerType;

  // Metric Type
  typedef itk::MutualInformationImageToImageMetric<
                                    FixedImageType,
                                    MovingImageType >    MetricType;

  // Interpolation technique
  typedef itk:: LinearInterpolateImageFunction<
                                    MovingImageType,
                                    double          >    InterpolatorType;

  // Fixed Image Pyramid Type
  typedef itk::RecursiveMultiResolutionPyramidImageFilter<
                                    FixedImageType,
                                    FixedImageType  >    FixedImagePyramidType;

  // Moving Image Pyramid Type
  typedef itk::RecursiveMultiResolutionPyramidImageFilter<
                                    MovingImageType,
                                    MovingImageType  >   MovingImagePyramidType;

  // Registration Method
  typedef itk::MultiResolutionImageRegistrationMethod<
                                    FixedImageType,
                                    MovingImageType >    RegistrationType;

  MetricType::Pointer         metric        = MetricType::New();
  TransformType::Pointer      transform     = TransformType::New();
  OptimizerType::Pointer      optimizer     = OptimizerType::New();
  FixedImageType::Pointer     fixedImage    = FixedImageType::New();
  MovingImageType::Pointer    movingImage   = MovingImageType::New();
  InterpolatorType::Pointer   interpolator  = InterpolatorType::New();
  FixedImagePyramidType::Pointer fixedImagePyramid =
    FixedImagePyramidType::New();
  MovingImagePyramidType::Pointer movingImagePyramid =
    MovingImagePyramidType::New();
  RegistrationType::Pointer   registration  = RegistrationType::New();

  /*********************************************************
   * Set up the two input images.
   * One image rotated (xy plane) and shifted with respect to the other.
   **********************************************************/
  double displacement[dimension] = {7,3,2};
  double angle = 10.0 / 180.0 * itk::Math::pi;

  FixedImageType::SizeType size = {{100,100,40}};
  FixedImageType::IndexType index = {{0,0,0}};
  FixedImageType::RegionType region;
  region.SetSize( size );
  region.SetIndex( index );

  fixedImage->SetLargestPossibleRegion( region );
  fixedImage->SetBufferedRegion( region );
  fixedImage->SetRequestedRegion( region );
  fixedImage->Allocate();

  movingImage->SetLargestPossibleRegion( region );
  movingImage->SetBufferedRegion( region );
  movingImage->SetRequestedRegion( region );
  movingImage->Allocate();

  typedef itk::ImageRegionIterator<MovingImageType> MovingImageIterator;
  typedef itk::ImageRegionIterator<FixedImageType>  FixedImageIterator;

  itk::Point<double,dimension> center;
  for ( j = 0; j < dimension; j++ )
    {
    center[j] = 0.5 *  (double)region.GetSize()[j];
    }

  itk::Point<double,dimension> p;
  itk::Vector<double,dimension> d, d2;

  MovingImageIterator mIter( movingImage, region );
  FixedImageIterator  fIter( fixedImage, region );

  while( !mIter.IsAtEnd() )
    {
    for ( j = 0; j < dimension; j++ )
      {
      p[j] = mIter.GetIndex()[j];
      }

    d = p - center;

    fIter.Set( (PixelType) F(d) );

    d2[0] =  d[0] * std::cos(angle) + d[1] * std::sin(angle) + displacement[0];
    d2[1] = -d[0] * std::sin(angle) + d[1] * std::cos(angle) + displacement[1];
    d2[2] = d[2] + displacement[2];

    mIter.Set( (PixelType) F(d2) );

    ++fIter;
    ++mIter;

    }

  // set the image origin to be center of the image
  double transCenter[dimension];
  for ( j = 0; j < dimension; j++ )
    {
    transCenter[j] = -0.5 * double(size[j]);
    }

  movingImage->SetOrigin( transCenter );
  fixedImage->SetOrigin( transCenter );

  /******************************************************************
   * Set up the optimizer.
   ******************************************************************/

  // set the translation scale
  typedef OptimizerType::ScalesType ScalesType;
  ScalesType parametersScales( transform->GetNumberOfParameters() );

  parametersScales.Fill( 1.0 );

  for ( j = 4; j < 7; j++ )
    {
    parametersScales[j] = 0.0001;
    }

  optimizer->SetScales( parametersScales );

  // need to maximize for mutual information
  optimizer->MaximizeOn();

  /******************************************************************
   * Set up the optimizer observer
   ******************************************************************/
/*
  typedef itk::CommandIterationUpdate< OptimizerType > CommandIterationType;
  CommandIterationType::Pointer iterationCommand =
    CommandIterationType::New();

  iterationCommand->SetOptimizer( optimizer );
*/

  /******************************************************************
   * Set up the metric.
   ******************************************************************/
  metric->SetMovingImageStandardDeviation( 5.0 );
  metric->SetFixedImageStandardDeviation( 5.0 );
  metric->SetNumberOfSpatialSamples( 50 );
  metric->ReinitializeSeed( 121212 );

  /******************************************************************
   * Set up the registrator.
   ******************************************************************/

  // connect up the components
  registration->SetMetric( metric );
  registration->SetOptimizer( optimizer );
  registration->SetTransform( transform );
  registration->SetFixedImage( fixedImage );
  registration->SetMovingImage( movingImage );
  registration->SetInterpolator( interpolator );
  registration->SetFixedImagePyramid( fixedImagePyramid );
  registration->SetMovingImagePyramid( movingImagePyramid );
  registration->SetFixedImageRegion( fixedImage->GetBufferedRegion() );

  // set initial parameters to identity
  RegistrationType::ParametersType initialParameters(
    transform->GetNumberOfParameters() );

  initialParameters.Fill( 0.0 );
  initialParameters[3] = 1.0;

  /******************************************************************
   * Attach registration to a simple UI and run registration
   ******************************************************************/
  SimpleMultiResolutionImageRegistrationUI2<RegistrationType>
    simpleUI( registration );

  unsigned short numberOfLevels = 3;

  itk::Array<unsigned int> niter( numberOfLevels );
  itk::Array<double>       rates( numberOfLevels );

  niter[0] = 300;
  niter[1] = 300;
  niter[2] = 350;

  rates[0] = 1e-3;
  rates[1] = 5e-4;
  rates[2] = 1e-4;

  simpleUI.SetNumberOfIterations( niter );
  simpleUI.SetLearningRates( rates );

  try
    {
    registration->SetNumberOfLevels( numberOfLevels );
    registration->SetInitialTransformParameters( initialParameters );
    registration->Update();
    }
  catch( itk::ExceptionObject & e )
    {
    std::cout << "Registration failed" << std::endl;
    std::cout << "Reason " << e.GetDescription() << std::endl;
    return EXIT_FAILURE;
    }

  /***********************************************************
   * Check the results
   ************************************************************/
  RegistrationType::ParametersType solution =
    registration->GetLastTransformParameters();

  std::cout << "Solution is: " << solution << std::endl;

  RegistrationType::ParametersType trueParameters(
    transform->GetNumberOfParameters() );
  trueParameters.Fill( 0.0 );
  trueParameters[2] =   std::sin( angle / 2.0 );
  trueParameters[3] =   std::cos( angle / 2.0 );
  trueParameters[4] = -1.0 * ( displacement[0] * std::cos(angle) -
                               displacement[1] * std::sin(angle) );
  trueParameters[5] = -1.0 * ( displacement[0] * std::sin(angle) +
                               displacement[1] * std::cos(angle) );
  trueParameters[6] = -1.0 * displacement[2];

  std::cout << "True solution is: " << trueParameters << std::endl;

  for( j = 0; j < 4; j++ )
    {
    if( itk::Math::abs( solution[j] - trueParameters[j] ) > 0.025 )
      {
      pass = false;
      }
    }
  for( j = 4; j < 7; j++ )
    {
    if( itk::Math::abs( solution[j] - trueParameters[j] ) > 1.0 )
      {
      pass = false;
      }
    }

  if( !pass )
    {
    std::cout << "Test failed." << std::endl;
    return EXIT_FAILURE;
    }

  /*************************************************
   * Check for parzen window exception
   **************************************************/
  double oldValue = metric->GetMovingImageStandardDeviation();
  metric->SetMovingImageStandardDeviation( 0.005 );

  try
    {
    pass = false;
    registration->Update();
    }
  catch(itk::ExceptionObject& err)
    {
    std::cout << "Caught expected ExceptionObject" << std::endl;
    std::cout << err << std::endl;
    pass = true;
    }

  if( !pass )
    {
    std::cout << "Should have caught an exception" << std::endl;
    std::cout << "Test failed." << std::endl;
    return EXIT_FAILURE;
    }

  metric->SetMovingImageStandardDeviation( oldValue );

  /*************************************************
   * Check for mapped out of image error
   **************************************************/
  solution[5] = 1000;
  registration->SetInitialTransformParameters( solution );

  try
    {
    pass = false;
    registration->Update();
    }
  catch(itk::ExceptionObject& err)
    {
    std::cout << "Caught expected ExceptionObject" << std::endl;
    std::cout << err << std::endl;
    pass = true;
    }

  if( !pass )
    {
    std::cout << "Should have caught an exception" << std::endl;
    std::cout << "Test failed." << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Test passed." << std::endl;
  return EXIT_SUCCESS;

}

namespace
{

/**
 * This function defines the test image pattern.
 * The pattern is a 3D gaussian in the middle
 * and some directional pattern on the outside.
 */
double F( itk::Vector<double,3> & v )
{
  double x = v[0];
  double y = v[1];
  double z = v[2];
  const double s = 50;
  double value = 200.0 * std::exp( - ( x*x + y*y + z*z )/(s*s) );
  x -= 8; y += 3; z += 0;
  double r = std::sqrt( x*x + y*y + z*z );
  if( r > 35 )
    {
    value = 2 * ( itk::Math::abs( x ) +
      0.8 * itk::Math::abs( y ) +
      0.5 * itk::Math::abs( z ) );
    }
  if( r < 4 )
    {
    value = 400;
    }

  return value;

}
}
<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "QmitkRadiomicsTransformationView.h"

// QT includes (GUI)
#include <qlabel.h>
#include <qspinbox.h>
#include <qpushbutton.h>
#include <qcheckbox.h>
#include <qgroupbox.h>
#include <qradiobutton.h>
#include <qmessagebox.h>

// Berry includes (selection service)
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>

// MITK includes (GUI)
#include <QmitkDataStorageComboBox.h>
#include "QmitkDataNodeSelectionProvider.h"
#include "mitkDataNodeObject.h"

// MITK includes (general
#include <mitkNodePredicateDataType.h>
#include <mitkNodePredicateAnd.h>
#include <mitkProperties.h>
#include <mitkTransformationOperation.h>
#include <mitkLabelSetImage.h>

// Specific GUI Includes
#include "QmitkGIFConfigurationPanel.h"

QmitkRadiomicsTransformation::QmitkRadiomicsTransformation()
: QmitkAbstractView(),
  m_Controls(nullptr)
{
}

QmitkRadiomicsTransformation::~QmitkRadiomicsTransformation()
{
  //berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService();
  //if(s)
  //  s->RemoveSelectionListener(m_SelectionListener);
}

void QmitkRadiomicsTransformation::CreateQtPartControl(QWidget *parent)
{
  if (m_Controls == nullptr)
  {
    m_Controls = new Ui::QmitkRadiomicsTransformationViewControls;
    m_Controls->setupUi(parent);

    QLabel * label1 = new QLabel("Image: ");
    QLabel * label2 = new QLabel("Mask: ");
    QmitkDataStorageComboBox * cb_inputimage = new QmitkDataStorageComboBox(this->GetDataStorage(), mitk::TNodePredicateDataType<mitk::Image>::New());
    m_Controls->m_InputImageGroup->layout()->addWidget(label1);
    m_Controls->m_InputImageGroup->layout()->addWidget(cb_inputimage);

    this->CreateConnections();
  }
}

void QmitkRadiomicsTransformation::CreateConnections()
{
  if ( m_Controls )
  {
    connect( (QObject*)(m_Controls->buttonExecuteMultiresolution), SIGNAL(clicked() ), this, SLOT(executeButtonMultiResolutionPressed() ) );
    connect((QObject*)(m_Controls->m_WaveletExecuteButton), SIGNAL(clicked()), this, SLOT(executeButtonWaveletPressed()));
    connect((QObject*)(m_Controls->m_ExecuteLOG), SIGNAL(clicked()), this, SLOT(executeButtonLoGPressed()));
    connect((QObject*)(m_Controls->buttonResampleImage), SIGNAL(clicked()), this, SLOT(executeButtonResamplingPressed()));

  }
}

void QmitkRadiomicsTransformation::executeButtonMultiResolutionPressed()
{
  QmitkDataStorageComboBox * cb_image = dynamic_cast<QmitkDataStorageComboBox *>(m_Controls->m_InputImageGroup->layout()->itemAt(1)->widget());
  mitk::BaseData* baseDataRawImage = NULL;

  mitk::Image::Pointer raw_image;
  std::string nodeName;
  if ((cb_image->GetSelectedNode().IsNotNull() ) )
  {
    baseDataRawImage = (cb_image->GetSelectedNode()->GetData());
    nodeName = cb_image->GetSelectedNode()->GetName();
  }
  if ((baseDataRawImage != NULL))
  {
    raw_image = dynamic_cast<mitk::Image *>(baseDataRawImage);
  }
  else {
    QMessageBox msgBox;
    msgBox.setText("Please specify the images that shlould be used.");
    msgBox.exec();
    return;
  }
  if (raw_image.IsNull())
  {
    QMessageBox msgBox;
    msgBox.setText("Error during processing the specified images.");
    msgBox.exec();
    return;
  }

  unsigned int numberOfLevels = m_Controls->m_NumberOfLevels->value();
  bool resultAsDouble = m_Controls->m_resultAsDouble->isChecked();

  auto results = mitk::TransformationOperation::MultiResolution(raw_image, numberOfLevels, resultAsDouble);
  unsigned int level = 1;
  for (auto image : results)
  {
    mitk::DataNode::Pointer result = mitk::DataNode::New();
    result->SetProperty("name", mitk::StringProperty::New(nodeName+"::MultiRes::Level-"+us::Any(numberOfLevels-level).ToString()));
    result->SetData(image);
    GetDataStorage()->Add(result, cb_image->GetSelectedNode());
    ++level;
  }
}

void QmitkRadiomicsTransformation::executeButtonWaveletPressed()
{
  QmitkDataStorageComboBox * cb_image = dynamic_cast<QmitkDataStorageComboBox *>(m_Controls->m_InputImageGroup->layout()->itemAt(1)->widget());
  mitk::BaseData* baseDataRawImage = NULL;

  mitk::Image::Pointer raw_image;
  std::string nodeName;
  if ((cb_image->GetSelectedNode().IsNotNull()))
  {
    baseDataRawImage = (cb_image->GetSelectedNode()->GetData());
    nodeName = cb_image->GetSelectedNode()->GetName();
  }
  if ((baseDataRawImage != NULL))
  {
    raw_image = dynamic_cast<mitk::Image *>(baseDataRawImage);
  }
  else {
    QMessageBox msgBox;
    msgBox.setText("Please specify the images that shlould be used.");
    msgBox.exec();
    return;
  }
  if (raw_image.IsNull())
  {
    QMessageBox msgBox;
    msgBox.setText("Error during processing the specified images.");
    msgBox.exec();
    return;
  }

  unsigned int numberOfLevels = m_Controls->m_WaveletNumberOfLevels->value();
  unsigned int numberOfBands = m_Controls->m_WaveletNumberOfBands->value();
  mitk::BorderCondition condition = mitk::BorderCondition::Constant;
  mitk::WaveletType waveletType = mitk::WaveletType::Held;

  std::string waveletStr = m_Controls->m_WaveletWavelet->currentText().toStdString();
  if (waveletStr == "Shannon")
  {
    waveletType = mitk::WaveletType::Shannon;
  }
  if (waveletStr == "Simoncelli")
  {
    waveletType = mitk::WaveletType::Simoncelli;
  }
  if (waveletStr == "Vow")
  {
    waveletType = mitk::WaveletType::Vow;
  }
  if (waveletStr == "Held")
  {
    waveletType = mitk::WaveletType::Held;
  }

  std::string conditionStr = m_Controls->m_WaveletBorderCondition->currentText().toStdString();
  if (conditionStr == "Constant")
  {
    condition = mitk::BorderCondition::Constant;
  }
  if (conditionStr == "Periodic")
  {
    condition = mitk::BorderCondition::Periodic;
  }
  if (conditionStr == "Zero Flux Neumann")
  {
    condition = mitk::BorderCondition::ZeroFluxNeumann;
  }

  auto results = mitk::TransformationOperation::WaveletForward(raw_image, numberOfLevels, numberOfBands, condition, waveletType);
  unsigned int level = 0;
  for (auto image : results)
  {
    mitk::DataNode::Pointer result = mitk::DataNode::New();
    result->SetProperty("name", mitk::StringProperty::New(nodeName + "::Wavelet::"+waveletStr+"-"+conditionStr+"::Level-" + us::Any(level).ToString()));
    result->SetData(image);
    GetDataStorage()->Add(result, cb_image->GetSelectedNode());
    ++level;
  }

}

void QmitkRadiomicsTransformation::executeButtonLoGPressed()
{
  QmitkDataStorageComboBox * cb_image = dynamic_cast<QmitkDataStorageComboBox *>(m_Controls->m_InputImageGroup->layout()->itemAt(1)->widget());
  mitk::BaseData* baseDataRawImage = NULL;

  mitk::Image::Pointer raw_image;
  std::string nodeName;
  if ((cb_image->GetSelectedNode().IsNotNull()))
  {
    baseDataRawImage = (cb_image->GetSelectedNode()->GetData());
    nodeName = cb_image->GetSelectedNode()->GetName();
  }
  if ((baseDataRawImage != NULL))
  {
    raw_image = dynamic_cast<mitk::Image *>(baseDataRawImage);
  }
  else {
    QMessageBox msgBox;
    msgBox.setText("Please specify the images that shlould be used.");
    msgBox.exec();
    return;
  }
  if (raw_image.IsNull())
  {
    QMessageBox msgBox;
    msgBox.setText("Error during processing the specified images.");
    msgBox.exec();
    return;
  }

  double sigma = m_Controls->m_LoGSigma->value();
  bool resultAsDouble = m_Controls->m_LogResultAsDouble->isChecked();

  auto results = mitk::TransformationOperation::LaplacianOfGaussian(raw_image, sigma, resultAsDouble);
  mitk::DataNode::Pointer result = mitk::DataNode::New();
  result->SetProperty("name", mitk::StringProperty::New(nodeName + "::LoG::Sigma-" + us::Any(sigma).ToString()));
  result->SetData(results);
  GetDataStorage()->Add(result, cb_image->GetSelectedNode());
}

void QmitkRadiomicsTransformation::executeButtonResamplingPressed()
{
  QmitkDataStorageComboBox * cb_image = dynamic_cast<QmitkDataStorageComboBox *>(m_Controls->m_InputImageGroup->layout()->itemAt(1)->widget());
  mitk::BaseData* baseDataRawImage = NULL;

  mitk::Image::Pointer raw_image;
  std::string nodeName;
  if ((cb_image->GetSelectedNode().IsNotNull()))
  {
    baseDataRawImage = (cb_image->GetSelectedNode()->GetData());
    nodeName = cb_image->GetSelectedNode()->GetName();
  }
  if ((baseDataRawImage != NULL))
  {
    raw_image = dynamic_cast<mitk::Image *>(baseDataRawImage);
  }
  else {
    QMessageBox msgBox;
    msgBox.setText("Please specify the images that shlould be used.");
    msgBox.exec();
    return;
  }
  if (raw_image.IsNull())
  {
    QMessageBox msgBox;
    msgBox.setText("Error during processing the specified images.");
    msgBox.exec();
    return;
  }

  mitk::ImageMappingInterpolator::Type interpolatorType;
  switch (m_Controls->comboInterpolationMode->currentIndex())
  {
  case 0:
    interpolatorType = mitk::ImageMappingInterpolator::Linear;
    break;

  case 1:
    interpolatorType = mitk::ImageMappingInterpolator::BSpline_3;
    break;

  case 2:
    interpolatorType = mitk::ImageMappingInterpolator::NearestNeighbor;
    break;

  case 3:
    interpolatorType = mitk::ImageMappingInterpolator::WSinc_Hamming;
    break;

  case 4:
    interpolatorType = mitk::ImageMappingInterpolator::WSinc_Welch;
    break;

  default:
    interpolatorType = mitk::ImageMappingInterpolator::Linear;
  }

  mitk::GridInterpolationPositionType gridPosition;
  switch (m_Controls->comboAxisAlignment->currentIndex())
  {
  case 0:
    gridPosition = mitk::GridInterpolationPositionType::OriginAligned;
    break;

  case 1:
    gridPosition = mitk::GridInterpolationPositionType::CenterAligned;
    break;

  case 2:
    gridPosition = mitk::GridInterpolationPositionType::SameSize;
    break;

  default:
    gridPosition = mitk::GridInterpolationPositionType::OriginAligned;
  }

  bool resultAsDouble = m_Controls->checkResamplingOutputAsDouble->isChecked();
  bool roundResult = m_Controls->checkResamplingRoundOutput->isChecked();

  mitk::Vector3D spacing;
  spacing.Fill(-1);
  if (m_Controls->checkResampleX->isChecked()) {
    spacing[0] = m_Controls->doubleSpinDimensionX->value();
  }
  if (m_Controls->checkResampleY->isChecked()) {
    spacing[1] = m_Controls->doubleSpinDimensionY->value();
  }
  if (m_Controls->checkResampleZ->isChecked()) {
    spacing[2] = m_Controls->doubleSpinDimensionZ->value();
  }

  mitk::Image::Pointer results;
  if (m_Controls->checkResampleAsMask->isChecked()) {
    results = mitk::TransformationOperation::ResampleMask(raw_image, spacing, interpolatorType, gridPosition);
    mitk::LabelSetImage::Pointer oldLabelImage = dynamic_cast<mitk::LabelSetImage *> (raw_image.GetPointer());
    if (oldLabelImage.IsNotNull())
    {
      mitk::LabelSetImage::Pointer labelResult = mitk::LabelSetImage::New();
      labelResult->InitializeByLabeledImage(results);
      labelResult->AddLabelSetToLayer(labelResult->GetActiveLayer(), oldLabelImage->GetLabelSet());
      results = dynamic_cast<mitk::Image*>(labelResult.GetPointer());
    }
  }
  else {
    results = mitk::TransformationOperation::ResampleImage(raw_image, spacing, interpolatorType, gridPosition, resultAsDouble, roundResult);
  }
  mitk::DataNode::Pointer result = mitk::DataNode::New();
  result->SetProperty("name", mitk::StringProperty::New(nodeName + "::Resampled" ));
  result->SetData(results);
  GetDataStorage()->Add(result, cb_image->GetSelectedNode());
}

void QmitkRadiomicsTransformation::SetFocus()
{
}

//datamanager selection changed
void QmitkRadiomicsTransformation::OnSelectionChanged(berry::IWorkbenchPart::Pointer, const QList<mitk::DataNode::Pointer>& nodes)
{
  //any nodes there?
  if (!nodes.empty())
  {

  }
}
<commit_msg>Remove unused variable<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "QmitkRadiomicsTransformationView.h"

// QT includes (GUI)
#include <qlabel.h>
#include <qspinbox.h>
#include <qpushbutton.h>
#include <qcheckbox.h>
#include <qgroupbox.h>
#include <qradiobutton.h>
#include <qmessagebox.h>

// Berry includes (selection service)
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>

// MITK includes (GUI)
#include <QmitkDataStorageComboBox.h>
#include "QmitkDataNodeSelectionProvider.h"
#include "mitkDataNodeObject.h"

// MITK includes (general
#include <mitkNodePredicateDataType.h>
#include <mitkNodePredicateAnd.h>
#include <mitkProperties.h>
#include <mitkTransformationOperation.h>
#include <mitkLabelSetImage.h>

// Specific GUI Includes
#include "QmitkGIFConfigurationPanel.h"

QmitkRadiomicsTransformation::QmitkRadiomicsTransformation()
: QmitkAbstractView(),
  m_Controls(nullptr)
{
}

QmitkRadiomicsTransformation::~QmitkRadiomicsTransformation()
{
  //berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService();
  //if(s)
  //  s->RemoveSelectionListener(m_SelectionListener);
}

void QmitkRadiomicsTransformation::CreateQtPartControl(QWidget *parent)
{
  if (m_Controls == nullptr)
  {
    m_Controls = new Ui::QmitkRadiomicsTransformationViewControls;
    m_Controls->setupUi(parent);

    QLabel * label1 = new QLabel("Image: ");
    QmitkDataStorageComboBox * cb_inputimage = new QmitkDataStorageComboBox(this->GetDataStorage(), mitk::TNodePredicateDataType<mitk::Image>::New());
    m_Controls->m_InputImageGroup->layout()->addWidget(label1);
    m_Controls->m_InputImageGroup->layout()->addWidget(cb_inputimage);

    this->CreateConnections();
  }
}

void QmitkRadiomicsTransformation::CreateConnections()
{
  if ( m_Controls )
  {
    connect( (QObject*)(m_Controls->buttonExecuteMultiresolution), SIGNAL(clicked() ), this, SLOT(executeButtonMultiResolutionPressed() ) );
    connect((QObject*)(m_Controls->m_WaveletExecuteButton), SIGNAL(clicked()), this, SLOT(executeButtonWaveletPressed()));
    connect((QObject*)(m_Controls->m_ExecuteLOG), SIGNAL(clicked()), this, SLOT(executeButtonLoGPressed()));
    connect((QObject*)(m_Controls->buttonResampleImage), SIGNAL(clicked()), this, SLOT(executeButtonResamplingPressed()));

  }
}

void QmitkRadiomicsTransformation::executeButtonMultiResolutionPressed()
{
  QmitkDataStorageComboBox * cb_image = dynamic_cast<QmitkDataStorageComboBox *>(m_Controls->m_InputImageGroup->layout()->itemAt(1)->widget());
  mitk::BaseData* baseDataRawImage = NULL;

  mitk::Image::Pointer raw_image;
  std::string nodeName;
  if ((cb_image->GetSelectedNode().IsNotNull() ) )
  {
    baseDataRawImage = (cb_image->GetSelectedNode()->GetData());
    nodeName = cb_image->GetSelectedNode()->GetName();
  }
  if ((baseDataRawImage != NULL))
  {
    raw_image = dynamic_cast<mitk::Image *>(baseDataRawImage);
  }
  else {
    QMessageBox msgBox;
    msgBox.setText("Please specify the images that shlould be used.");
    msgBox.exec();
    return;
  }
  if (raw_image.IsNull())
  {
    QMessageBox msgBox;
    msgBox.setText("Error during processing the specified images.");
    msgBox.exec();
    return;
  }

  unsigned int numberOfLevels = m_Controls->m_NumberOfLevels->value();
  bool resultAsDouble = m_Controls->m_resultAsDouble->isChecked();

  auto results = mitk::TransformationOperation::MultiResolution(raw_image, numberOfLevels, resultAsDouble);
  unsigned int level = 1;
  for (auto image : results)
  {
    mitk::DataNode::Pointer result = mitk::DataNode::New();
    result->SetProperty("name", mitk::StringProperty::New(nodeName+"::MultiRes::Level-"+us::Any(numberOfLevels-level).ToString()));
    result->SetData(image);
    GetDataStorage()->Add(result, cb_image->GetSelectedNode());
    ++level;
  }
}

void QmitkRadiomicsTransformation::executeButtonWaveletPressed()
{
  QmitkDataStorageComboBox * cb_image = dynamic_cast<QmitkDataStorageComboBox *>(m_Controls->m_InputImageGroup->layout()->itemAt(1)->widget());
  mitk::BaseData* baseDataRawImage = NULL;

  mitk::Image::Pointer raw_image;
  std::string nodeName;
  if ((cb_image->GetSelectedNode().IsNotNull()))
  {
    baseDataRawImage = (cb_image->GetSelectedNode()->GetData());
    nodeName = cb_image->GetSelectedNode()->GetName();
  }
  if ((baseDataRawImage != NULL))
  {
    raw_image = dynamic_cast<mitk::Image *>(baseDataRawImage);
  }
  else {
    QMessageBox msgBox;
    msgBox.setText("Please specify the images that shlould be used.");
    msgBox.exec();
    return;
  }
  if (raw_image.IsNull())
  {
    QMessageBox msgBox;
    msgBox.setText("Error during processing the specified images.");
    msgBox.exec();
    return;
  }

  unsigned int numberOfLevels = m_Controls->m_WaveletNumberOfLevels->value();
  unsigned int numberOfBands = m_Controls->m_WaveletNumberOfBands->value();
  mitk::BorderCondition condition = mitk::BorderCondition::Constant;
  mitk::WaveletType waveletType = mitk::WaveletType::Held;

  std::string waveletStr = m_Controls->m_WaveletWavelet->currentText().toStdString();
  if (waveletStr == "Shannon")
  {
    waveletType = mitk::WaveletType::Shannon;
  }
  if (waveletStr == "Simoncelli")
  {
    waveletType = mitk::WaveletType::Simoncelli;
  }
  if (waveletStr == "Vow")
  {
    waveletType = mitk::WaveletType::Vow;
  }
  if (waveletStr == "Held")
  {
    waveletType = mitk::WaveletType::Held;
  }

  std::string conditionStr = m_Controls->m_WaveletBorderCondition->currentText().toStdString();
  if (conditionStr == "Constant")
  {
    condition = mitk::BorderCondition::Constant;
  }
  if (conditionStr == "Periodic")
  {
    condition = mitk::BorderCondition::Periodic;
  }
  if (conditionStr == "Zero Flux Neumann")
  {
    condition = mitk::BorderCondition::ZeroFluxNeumann;
  }

  auto results = mitk::TransformationOperation::WaveletForward(raw_image, numberOfLevels, numberOfBands, condition, waveletType);
  unsigned int level = 0;
  for (auto image : results)
  {
    mitk::DataNode::Pointer result = mitk::DataNode::New();
    result->SetProperty("name", mitk::StringProperty::New(nodeName + "::Wavelet::"+waveletStr+"-"+conditionStr+"::Level-" + us::Any(level).ToString()));
    result->SetData(image);
    GetDataStorage()->Add(result, cb_image->GetSelectedNode());
    ++level;
  }

}

void QmitkRadiomicsTransformation::executeButtonLoGPressed()
{
  QmitkDataStorageComboBox * cb_image = dynamic_cast<QmitkDataStorageComboBox *>(m_Controls->m_InputImageGroup->layout()->itemAt(1)->widget());
  mitk::BaseData* baseDataRawImage = NULL;

  mitk::Image::Pointer raw_image;
  std::string nodeName;
  if ((cb_image->GetSelectedNode().IsNotNull()))
  {
    baseDataRawImage = (cb_image->GetSelectedNode()->GetData());
    nodeName = cb_image->GetSelectedNode()->GetName();
  }
  if ((baseDataRawImage != NULL))
  {
    raw_image = dynamic_cast<mitk::Image *>(baseDataRawImage);
  }
  else {
    QMessageBox msgBox;
    msgBox.setText("Please specify the images that shlould be used.");
    msgBox.exec();
    return;
  }
  if (raw_image.IsNull())
  {
    QMessageBox msgBox;
    msgBox.setText("Error during processing the specified images.");
    msgBox.exec();
    return;
  }

  double sigma = m_Controls->m_LoGSigma->value();
  bool resultAsDouble = m_Controls->m_LogResultAsDouble->isChecked();

  auto results = mitk::TransformationOperation::LaplacianOfGaussian(raw_image, sigma, resultAsDouble);
  mitk::DataNode::Pointer result = mitk::DataNode::New();
  result->SetProperty("name", mitk::StringProperty::New(nodeName + "::LoG::Sigma-" + us::Any(sigma).ToString()));
  result->SetData(results);
  GetDataStorage()->Add(result, cb_image->GetSelectedNode());
}

void QmitkRadiomicsTransformation::executeButtonResamplingPressed()
{
  QmitkDataStorageComboBox * cb_image = dynamic_cast<QmitkDataStorageComboBox *>(m_Controls->m_InputImageGroup->layout()->itemAt(1)->widget());
  mitk::BaseData* baseDataRawImage = NULL;

  mitk::Image::Pointer raw_image;
  std::string nodeName;
  if ((cb_image->GetSelectedNode().IsNotNull()))
  {
    baseDataRawImage = (cb_image->GetSelectedNode()->GetData());
    nodeName = cb_image->GetSelectedNode()->GetName();
  }
  if ((baseDataRawImage != NULL))
  {
    raw_image = dynamic_cast<mitk::Image *>(baseDataRawImage);
  }
  else {
    QMessageBox msgBox;
    msgBox.setText("Please specify the images that shlould be used.");
    msgBox.exec();
    return;
  }
  if (raw_image.IsNull())
  {
    QMessageBox msgBox;
    msgBox.setText("Error during processing the specified images.");
    msgBox.exec();
    return;
  }

  mitk::ImageMappingInterpolator::Type interpolatorType;
  switch (m_Controls->comboInterpolationMode->currentIndex())
  {
  case 0:
    interpolatorType = mitk::ImageMappingInterpolator::Linear;
    break;

  case 1:
    interpolatorType = mitk::ImageMappingInterpolator::BSpline_3;
    break;

  case 2:
    interpolatorType = mitk::ImageMappingInterpolator::NearestNeighbor;
    break;

  case 3:
    interpolatorType = mitk::ImageMappingInterpolator::WSinc_Hamming;
    break;

  case 4:
    interpolatorType = mitk::ImageMappingInterpolator::WSinc_Welch;
    break;

  default:
    interpolatorType = mitk::ImageMappingInterpolator::Linear;
  }

  mitk::GridInterpolationPositionType gridPosition;
  switch (m_Controls->comboAxisAlignment->currentIndex())
  {
  case 0:
    gridPosition = mitk::GridInterpolationPositionType::OriginAligned;
    break;

  case 1:
    gridPosition = mitk::GridInterpolationPositionType::CenterAligned;
    break;

  case 2:
    gridPosition = mitk::GridInterpolationPositionType::SameSize;
    break;

  default:
    gridPosition = mitk::GridInterpolationPositionType::OriginAligned;
  }

  bool resultAsDouble = m_Controls->checkResamplingOutputAsDouble->isChecked();
  bool roundResult = m_Controls->checkResamplingRoundOutput->isChecked();

  mitk::Vector3D spacing;
  spacing.Fill(-1);
  if (m_Controls->checkResampleX->isChecked()) {
    spacing[0] = m_Controls->doubleSpinDimensionX->value();
  }
  if (m_Controls->checkResampleY->isChecked()) {
    spacing[1] = m_Controls->doubleSpinDimensionY->value();
  }
  if (m_Controls->checkResampleZ->isChecked()) {
    spacing[2] = m_Controls->doubleSpinDimensionZ->value();
  }

  mitk::Image::Pointer results;
  if (m_Controls->checkResampleAsMask->isChecked()) {
    results = mitk::TransformationOperation::ResampleMask(raw_image, spacing, interpolatorType, gridPosition);
    mitk::LabelSetImage::Pointer oldLabelImage = dynamic_cast<mitk::LabelSetImage *> (raw_image.GetPointer());
    if (oldLabelImage.IsNotNull())
    {
      mitk::LabelSetImage::Pointer labelResult = mitk::LabelSetImage::New();
      labelResult->InitializeByLabeledImage(results);
      labelResult->AddLabelSetToLayer(labelResult->GetActiveLayer(), oldLabelImage->GetLabelSet());
      results = dynamic_cast<mitk::Image*>(labelResult.GetPointer());
    }
  }
  else {
    results = mitk::TransformationOperation::ResampleImage(raw_image, spacing, interpolatorType, gridPosition, resultAsDouble, roundResult);
  }
  mitk::DataNode::Pointer result = mitk::DataNode::New();
  result->SetProperty("name", mitk::StringProperty::New(nodeName + "::Resampled" ));
  result->SetData(results);
  GetDataStorage()->Add(result, cb_image->GetSelectedNode());
}

void QmitkRadiomicsTransformation::SetFocus()
{
}

//datamanager selection changed
void QmitkRadiomicsTransformation::OnSelectionChanged(berry::IWorkbenchPart::Pointer, const QList<mitk::DataNode::Pointer>& nodes)
{
  //any nodes there?
  if (!nodes.empty())
  {

  }
}
<|endoftext|>


<commit_before>/*  This file is part of the KDE project
    Copyright (C) 2007 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 as published by the Free Software Foundation.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/

#include "mediasource.h"
#include "mediasource_p.h"
#include "iodevicestream.h"
#include <QFile>

namespace Phonon
{

MediaSource::MediaSource()
    : d(new MediaSourcePrivate(Invalid))
{
}

MediaSource::MediaSource(const QString &filename)
    : d(new MediaSourcePrivate(LocalFile))
{
    if (filename.size() > 0 && filename.startsWith(QLatin1Char(':'))) {
        // it's a Qt resource -> use QFile
        d->type = Stream;
        d->resourceFile = new QFile(filename);
        d->stream = new IODeviceStream(d->resourceFile, d->resourceFile);
    } else {
        d->url = QUrl::fromLocalFile(filename);
    }
}

MediaSource::MediaSource(const QUrl &url)
    : d(new MediaSourcePrivate(Url))
{
    d->url = url;
}

MediaSource::MediaSource(Phonon::DiscType dt, const QString &deviceName)
    : d(new MediaSourcePrivate(Disc))
{
    d->discType = dt;
    d->deviceName = deviceName;
}

MediaSource::MediaSource(AbstractMediaStream *stream)
    : d(new MediaSourcePrivate(Stream))
{
    d->stream = stream;
}

MediaSource::MediaSource(QIODevice *ioDevice)
    : d(new MediaSourcePrivate(Stream))
{
    d->stream = new IODeviceStream(ioDevice, ioDevice);
}

MediaSource::~MediaSource()
{
    delete d->resourceFile;
    d->resourceFile = 0;
}

MediaSource::MediaSource(const MediaSource &rhs)
    : d(rhs.d)
{
}

MediaSource &MediaSource::operator=(const MediaSource &rhs)
{
    d = rhs.d;
    return *this;
}

bool MediaSource::operator==(const MediaSource &rhs) const
{
    return d == rhs.d;
}

MediaSource::Type MediaSource::type() const
{
    if (d->type == Stream && d->stream == 0) {
        return Invalid;
    }
    return d->type;
}

QString MediaSource::filename() const
{
    return d->url.toLocalFile();
}

QUrl MediaSource::url() const
{
    return d->url;
}

Phonon::DiscType MediaSource::discType() const
{
    return d->discType;
}

QString MediaSource::deviceName() const
{
    return d->deviceName;
}

AbstractMediaStream *MediaSource::stream() const
{
    return d->stream;
}

//X AudioCaptureDevice MediaSource::audioCaptureDevice() const
//X {
//X     return d->audioCaptureDevice;
//X }
//X
//X VideoCaptureDevice MediaSource::videoCaptureDevice() const
//X {
//X     return d->videoCaptureDevice;
//X }

} // namespace Phonon

// vim: sw=4 sts=4 et tw=100
<commit_msg>passing NoDisc makes it an invalid MediaSource<commit_after>/*  This file is part of the KDE project
    Copyright (C) 2007 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 as published by the Free Software Foundation.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/

#include "mediasource.h"
#include "mediasource_p.h"
#include "iodevicestream.h"
#include <QFile>

namespace Phonon
{

MediaSource::MediaSource()
    : d(new MediaSourcePrivate(Invalid))
{
}

MediaSource::MediaSource(const QString &filename)
    : d(new MediaSourcePrivate(LocalFile))
{
    if (filename.size() > 0 && filename.startsWith(QLatin1Char(':'))) {
        // it's a Qt resource -> use QFile
        d->type = Stream;
        d->resourceFile = new QFile(filename);
        d->stream = new IODeviceStream(d->resourceFile, d->resourceFile);
    } else {
        d->url = QUrl::fromLocalFile(filename);
    }
}

MediaSource::MediaSource(const QUrl &url)
    : d(new MediaSourcePrivate(Url))
{
    d->url = url;
}

MediaSource::MediaSource(Phonon::DiscType dt, const QString &deviceName)
    : d(new MediaSourcePrivate(Disc))
{
    if (dt == NoDisc) {
        d->type = Invalid;
        return;
    }
    d->discType = dt;
    d->deviceName = deviceName;
}

MediaSource::MediaSource(AbstractMediaStream *stream)
    : d(new MediaSourcePrivate(Stream))
{
    d->stream = stream;
}

MediaSource::MediaSource(QIODevice *ioDevice)
    : d(new MediaSourcePrivate(Stream))
{
    d->stream = new IODeviceStream(ioDevice, ioDevice);
}

MediaSource::~MediaSource()
{
    delete d->resourceFile;
    d->resourceFile = 0;
}

MediaSource::MediaSource(const MediaSource &rhs)
    : d(rhs.d)
{
}

MediaSource &MediaSource::operator=(const MediaSource &rhs)
{
    d = rhs.d;
    return *this;
}

bool MediaSource::operator==(const MediaSource &rhs) const
{
    return d == rhs.d;
}

MediaSource::Type MediaSource::type() const
{
    if (d->type == Stream && d->stream == 0) {
        return Invalid;
    }
    return d->type;
}

QString MediaSource::filename() const
{
    return d->url.toLocalFile();
}

QUrl MediaSource::url() const
{
    return d->url;
}

Phonon::DiscType MediaSource::discType() const
{
    return d->discType;
}

QString MediaSource::deviceName() const
{
    return d->deviceName;
}

AbstractMediaStream *MediaSource::stream() const
{
    return d->stream;
}

//X AudioCaptureDevice MediaSource::audioCaptureDevice() const
//X {
//X     return d->audioCaptureDevice;
//X }
//X
//X VideoCaptureDevice MediaSource::videoCaptureDevice() const
//X {
//X     return d->videoCaptureDevice;
//X }

} // namespace Phonon

// vim: sw=4 sts=4 et tw=100
<|endoftext|>


<commit_before>#define png_infopp_NULL (png_infopp)NULL
#define int_p_NULL (int*)NULL
#include <boost/gil/extension/io/png_io.hpp>

#include "cctag/utils/FileDebug.hpp"
#include "cctag/utils/VisualDebug.hpp"
#include "cctag/utils/Exceptions.hpp"
#include "cctag/Detection.hpp"
#include "CmdLine.hpp"

#ifdef WITH_CUDA
#include "cuda/device_prop.hpp"
#include "cuda/debug_macros.hpp"
#endif // WITH_CUDA

#include <boost/filesystem/convenience.hpp>
#include <boost/filesystem.hpp>
#include <boost/progress.hpp>
#include <boost/exception/all.hpp>
#include <boost/ptr_container/ptr_list.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>

#include <opencv/cv.h>
#include <opencv2/videoio.hpp>
#include <opencv2/core/core.hpp>
#include "opencv2/opencv.hpp"

#include <sstream>
#include <iostream>
#include <string>
#include <fstream>
#include <exception>

#define PRINT_TO_CERR

using namespace cctag;
using boost::timer;

using namespace boost::gil;
namespace bfs = boost::filesystem;

// static const std::string kUsageString = "Usage: detection image_file.png\n";

void detection(std::size_t frameId, const cv::Mat & src, const cctag::Parameters & params, const cctag::CCTagMarkersBank & bank, std::ostream & output, std::string debugFileName = "")
{
    if (debugFileName == "") {
      debugFileName = "00000";
    }

    // Process markers detection
    boost::timer t;
    boost::ptr_list<CCTag> markers;

    CCTagVisualDebug::instance().initBackgroundImage(src);
    CCTagVisualDebug::instance().setImageFileName(debugFileName);
    CCTagFileDebug::instance().setPath(CCTagVisualDebug::instance().getPath());

    static cctag::logtime::Mgmt* durations = 0;
#if 0
    if( not durations ) {
        durations = new cctag::logtime::Mgmt( 25 );
    } else {
        durations->resetStartTime();
    }
#endif
    cctagDetection( markers, frameId , src, params, bank, true, durations );

    if( durations ) {
        durations->print( std::cerr );
    }

    CCTagFileDebug::instance().outPutAllSessions();
    CCTagFileDebug::instance().clearSessions();
    CCTagVisualDebug::instance().outPutAllSessions();
    CCTagVisualDebug::instance().clearSessions();

    CCTAG_COUT( markers.size() << " markers.");
    CCTAG_COUT("Total time: " << t.elapsed());
    CCTAG_COUT_NOENDL("Id : ");

    int i = 0;
    output << "#frame " << frameId << '\n';
    output << markers.size() << '\n';
    BOOST_FOREACH(const cctag::CCTag & marker, markers) {
      output << marker.x() << " " << marker.y() << " " << marker.id() << " " << marker.getStatus() << '\n';
      if (i == 0) {
          CCTAG_COUT_NOENDL(marker.id() + 1);
      } else {
          CCTAG_COUT_NOENDL(", " << marker.id() + 1);
      }
      ++i;
    }
    CCTAG_COUT("");
}

/*************************************************************/
/*                    Main entry                             */
/*************************************************************/
int main(int argc, char** argv)
{
  CmdLine cmdline;

  if( cmdline.parse( argc, argv ) == false ) {
    cmdline.usage( argv[0] );
    return EXIT_FAILURE;
  }

  cmdline.print( argv[0] );

  // Check input path
  if( cmdline._filename.compare("") != 0){
    if (!boost::filesystem::exists( cmdline._filename )) {
      std::cerr << std::endl
        << "The input file \""<< cmdline._filename << "\" is missing" << std::endl;
      return EXIT_FAILURE;
    }
  }else{
    std::cerr << std::endl
        << "An input file is required" << std::endl;
    cmdline.usage( argv[0] );
    return EXIT_FAILURE;
  }

#ifdef WITH_CUDA
  popart::pop_cuda_only_sync_calls( cmdline._switchSync );
#endif

  // Check the (optional) parameters path
  std::size_t nCrowns = std::atoi(cmdline._nCrowns.c_str());
  cctag::Parameters params(nCrowns);

  if( cmdline._paramsFilename != "" ) {
    if (!boost::filesystem::exists( cmdline._paramsFilename )) {
      std::cerr << std::endl
        << "The input file \""<< cmdline._paramsFilename << "\" is missing" << std::endl;
      return EXIT_FAILURE;
    }

    // Read the parameter file provided by the user
    std::ifstream ifs( cmdline._paramsFilename.c_str() );
    boost::archive::xml_iarchive ia(ifs);
    ia >> boost::serialization::make_nvp("CCTagsParams", params);
    CCTAG_COUT(params._nCrowns);
    CCTAG_COUT(nCrowns);
    assert( nCrowns == params._nCrowns );
  } else {
    // Use the default parameters and save them in defaultParameters.xml
    cmdline._paramsFilename = "defaultParameters.xml";
    std::ofstream ofs( cmdline._paramsFilename.c_str() );
    boost::archive::xml_oarchive oa(ofs);
    oa << boost::serialization::make_nvp("CCTagsParams", params);
    CCTAG_COUT("Parameter file not provided. Default parameters are used.");
  }

  CCTagMarkersBank bank(params._nCrowns);
  if ( !cmdline._cctagBankFilename.empty())
  {
    bank = CCTagMarkersBank(cmdline._cctagBankFilename);
  }

#ifdef WITH_CUDA
  if( cmdline._useCuda ) {
    params.setUseCuda( true );
  } else {
    params.setUseCuda( false );
  }

  if( cmdline._debugDir != "" ) {
    params.setDebugDir( cmdline._debugDir );
  }

  popart::device_prop_t deviceInfo( false );
#if 0
  deviceInfo.print( );
#endif
#endif // WITH_CUDA

  bfs::path myPath( cmdline._filename );
  std::string ext(myPath.extension().string());

  const bfs::path subFilenamePath(myPath.filename());
  const bfs::path parentPath( myPath.parent_path() == "" ? "." : myPath.parent_path());
  std::string outputFileName;
  if (!bfs::is_directory(myPath))
  {
    CCTagVisualDebug::instance().initializeFolders( parentPath , cmdline._outputFolderName , params._nCrowns );
    outputFileName = parentPath.string() + "/" + cmdline._outputFolderName + "/cctag" + std::to_string(nCrowns) + "CC.out";
  }else
  {
    CCTagVisualDebug::instance().initializeFolders( myPath , cmdline._outputFolderName , params._nCrowns );
    outputFileName = myPath.string() + "/" + cmdline._outputFolderName + "/cctag" + std::to_string(nCrowns) + "CC.out";
  }
  std::ofstream outputFile;
  outputFile.open( outputFileName );

  if ( (ext == ".png") || (ext == ".jpg") || (ext == ".PNG") || (ext == ".JPG")) {
    POP_INFO("looking at image " << myPath.string());

    // Gray scale convertion
    cv::Mat src = cv::imread(cmdline._filename);
    cv::Mat graySrc;
    cv::cvtColor( src, graySrc, CV_BGR2GRAY );

    // Upscale original image
    /*{
            rgb8_image_t simage;
            simage.recreate( 2 * image.width(), 2 * image.height() );
            rgb8_view_t osvw( view( simage ) );
            terry::resize_view( svw, osvw, terry::sampler::bicubic_sampler() );
    }*/

    // Call the CCTag detection
#ifdef PRINT_TO_CERR
    detection(0, graySrc, params, bank, std::cerr, myPath.stem().string());
#else
    detection(0, graySrc, params, bank, outputFile, myPath.stem().string());
#endif
} else if (ext == ".avi" )
  {
    CCTAG_COUT("*** Video mode ***");
    POP_INFO( "looking at video " << myPath.string() );

    // open video and check
    cv::VideoCapture video( cmdline._filename.c_str() );
    if(!video.isOpened())
    {
      CCTAG_COUT("Unable to open the video : " << cmdline._filename); return -1;
    }

    // play loop
    int lastFrame = video.get(CV_CAP_PROP_FRAME_COUNT);

    std::list<cv::Mat*> frames;

    std::cerr << "Starting to read video frames" << std::endl;
    while( video.get(CV_CAP_PROP_POS_FRAMES) < lastFrame )
    {
      cv::Mat frame;
      video >> frame;
      cv::Mat* imgGray = new cv::Mat;
      cv::cvtColor( frame, *imgGray, CV_BGR2GRAY );

      frames.push_back( imgGray );
    }
    std::cerr << "Done. Now processing." << std::endl;

    boost::timer t;
    std::size_t         frameId = 0;
#if 0
    boost::mutex        frame_mutex;
    boost::thread_group frame_processor;
    for( int proc=0; proc<1 ; proc++ ) {
      frame_processor.create_thread(
        [&frames, &frameId, &frame_mutex, &t, params, bank, &outputFile](){
            bool   empty;
            do {
                cv::Mat* imgGray;
                frame_mutex.lock();
                empty = frames.empty();
                if( not empty ) {
                    imgGray = frames.front();
                    frames.pop_front();
                    ++frameId;
                }
                frame_mutex.unlock();

                std::stringstream outFileName;
                outFileName << std::setfill('0') << std::setw(5) << frameId;

                detection(frameId, *imgGray, params, bank, outputFile, outFileName.str());
                if( frameId % 100 == 0 ) {
                    std::cerr << frameId << " (" << std::setprecision(3) << t.elapsed()*1000.0/frameId << ") ";
                }
                delete imgGray;
            } while( not empty );
        } );
    }
    frame_processor.join_all();
#else
    for( cv::Mat* imgGray : frames ) {
        // Set the output folder
        std::stringstream outFileName;
        outFileName << std::setfill('0') << std::setw(5) << frameId;

        // Invert the image for the projection scenario
        //cv::Mat imgGrayInverted;
        //bitwise_not ( imgGray, imgGrayInverted );

        // Call the CCTag detection
#ifdef PRINT_TO_CERR
        detection(frameId, *imgGray, params, bank, std::cerr, outFileName.str());
#else
        detection(frameId, *imgGray, params, bank, outputFile, outFileName.str());
#endif
        ++frameId;
        if( frameId % 100 == 0 ) {
            std::cerr << frameId << " (" << std::setprecision(3) << t.elapsed()*1000.0/frameId << ") ";
        }
    }
#endif
    std::cerr << std::endl;
  } else if (bfs::is_directory(myPath)) {
    CCTAG_COUT("*** Image sequence mode ***");

    std::vector<bfs::path> vFileInFolder;

    std::copy(bfs::directory_iterator(myPath), bfs::directory_iterator(), std::back_inserter(vFileInFolder)); // is directory_entry, which is
    std::sort(vFileInFolder.begin(), vFileInFolder.end());

    std::size_t frameId = 0;

    for(const auto & fileInFolder : vFileInFolder) {
      const std::string subExt(bfs::extension(fileInFolder));

      if ( (subExt == ".png") || (subExt == ".jpg") || (subExt == ".PNG") || (subExt == ".JPG") ) {

        CCTAG_COUT( "Processing image " << fileInFolder.string() );

		cv::Mat src;
    	src = cv::imread(fileInFolder.string());

        cv::Mat imgGray;
        cv::cvtColor( src, imgGray, CV_BGR2GRAY );

        // Call the CCTag detection
#ifdef PRINT_TO_CERR
        detection(frameId, imgGray, params, bank, std::cerr, fileInFolder.stem().string());
#else
        detection(frameId, imgGray, params, bank, outputFile, fileInFolder.stem().string());
#endif
++frameId;
      }
    }
  }else
  {
      throw std::logic_error("Unrecognized input.");
  }
  outputFile.close();
  return 0;
}

<commit_msg>[application] Print elapsed time in any case.<commit_after>#define png_infopp_NULL (png_infopp)NULL
#define int_p_NULL (int*)NULL
#include <boost/gil/extension/io/png_io.hpp>

#include "cctag/utils/FileDebug.hpp"
#include "cctag/utils/VisualDebug.hpp"
#include "cctag/utils/Exceptions.hpp"
#include "cctag/Detection.hpp"
#include "CmdLine.hpp"

#ifdef WITH_CUDA
#include "cuda/device_prop.hpp"
#include "cuda/debug_macros.hpp"
#endif // WITH_CUDA

#include <boost/filesystem/convenience.hpp>
#include <boost/filesystem.hpp>
#include <boost/progress.hpp>
#include <boost/exception/all.hpp>
#include <boost/ptr_container/ptr_list.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>

#include <opencv/cv.h>
#include <opencv2/videoio.hpp>
#include <opencv2/core/core.hpp>
#include "opencv2/opencv.hpp"

#include <sstream>
#include <iostream>
#include <string>
#include <fstream>
#include <exception>

#define PRINT_TO_CERR

using namespace cctag;
using boost::timer;

using namespace boost::gil;
namespace bfs = boost::filesystem;

// static const std::string kUsageString = "Usage: detection image_file.png\n";

void detection(std::size_t frameId, const cv::Mat & src, const cctag::Parameters & params, const cctag::CCTagMarkersBank & bank, std::ostream & output, std::string debugFileName = "")
{
    if (debugFileName == "") {
      debugFileName = "00000";
    }

    // Process markers detection
    boost::timer t;
    boost::ptr_list<CCTag> markers;

    CCTagVisualDebug::instance().initBackgroundImage(src);
    CCTagVisualDebug::instance().setImageFileName(debugFileName);
    CCTagFileDebug::instance().setPath(CCTagVisualDebug::instance().getPath());

    static cctag::logtime::Mgmt* durations = 0;
#if 0
    if( not durations ) {
        durations = new cctag::logtime::Mgmt( 25 );
    } else {
        durations->resetStartTime();
    }
#endif
    cctagDetection( markers, frameId , src, params, bank, true, durations );

    if( durations ) {
        durations->print( std::cerr );
    }

    CCTagFileDebug::instance().outPutAllSessions();
    CCTagFileDebug::instance().clearSessions();
    CCTagVisualDebug::instance().outPutAllSessions();
    CCTagVisualDebug::instance().clearSessions();

    CCTAG_COUT( markers.size() << " markers.");
    std::cout << "Total time: " << t.elapsed() << std::endl;
    CCTAG_COUT_NOENDL("Id : ");

    int i = 0;
    output << "#frame " << frameId << '\n';
    output << markers.size() << '\n';
    BOOST_FOREACH(const cctag::CCTag & marker, markers) {
      output << marker.x() << " " << marker.y() << " " << marker.id() << " " << marker.getStatus() << '\n';
      if (i == 0) {
          CCTAG_COUT_NOENDL(marker.id() + 1);
      } else {
          CCTAG_COUT_NOENDL(", " << marker.id() + 1);
      }
      ++i;
    }
    CCTAG_COUT("");
}

/*************************************************************/
/*                    Main entry                             */
/*************************************************************/
int main(int argc, char** argv)
{
  CmdLine cmdline;

  if( cmdline.parse( argc, argv ) == false ) {
    cmdline.usage( argv[0] );
    return EXIT_FAILURE;
  }

  cmdline.print( argv[0] );

  // Check input path
  if( cmdline._filename.compare("") != 0){
    if (!boost::filesystem::exists( cmdline._filename )) {
      std::cerr << std::endl
        << "The input file \""<< cmdline._filename << "\" is missing" << std::endl;
      return EXIT_FAILURE;
    }
  }else{
    std::cerr << std::endl
        << "An input file is required" << std::endl;
    cmdline.usage( argv[0] );
    return EXIT_FAILURE;
  }

#ifdef WITH_CUDA
  popart::pop_cuda_only_sync_calls( cmdline._switchSync );
#endif

  // Check the (optional) parameters path
  std::size_t nCrowns = std::atoi(cmdline._nCrowns.c_str());
  cctag::Parameters params(nCrowns);

  if( cmdline._paramsFilename != "" ) {
    if (!boost::filesystem::exists( cmdline._paramsFilename )) {
      std::cerr << std::endl
        << "The input file \""<< cmdline._paramsFilename << "\" is missing" << std::endl;
      return EXIT_FAILURE;
    }

    // Read the parameter file provided by the user
    std::ifstream ifs( cmdline._paramsFilename.c_str() );
    boost::archive::xml_iarchive ia(ifs);
    ia >> boost::serialization::make_nvp("CCTagsParams", params);
    CCTAG_COUT(params._nCrowns);
    CCTAG_COUT(nCrowns);
    assert( nCrowns == params._nCrowns );
  } else {
    // Use the default parameters and save them in defaultParameters.xml
    cmdline._paramsFilename = "defaultParameters.xml";
    std::ofstream ofs( cmdline._paramsFilename.c_str() );
    boost::archive::xml_oarchive oa(ofs);
    oa << boost::serialization::make_nvp("CCTagsParams", params);
    CCTAG_COUT("Parameter file not provided. Default parameters are used.");
  }

  CCTagMarkersBank bank(params._nCrowns);
  if ( !cmdline._cctagBankFilename.empty())
  {
    bank = CCTagMarkersBank(cmdline._cctagBankFilename);
  }

#ifdef WITH_CUDA
  if( cmdline._useCuda ) {
    params.setUseCuda( true );
  } else {
    params.setUseCuda( false );
  }

  if( cmdline._debugDir != "" ) {
    params.setDebugDir( cmdline._debugDir );
  }

  popart::device_prop_t deviceInfo( false );
#if 0
  deviceInfo.print( );
#endif
#endif // WITH_CUDA

  bfs::path myPath( cmdline._filename );
  std::string ext(myPath.extension().string());

  const bfs::path subFilenamePath(myPath.filename());
  const bfs::path parentPath( myPath.parent_path() == "" ? "." : myPath.parent_path());
  std::string outputFileName;
  if (!bfs::is_directory(myPath))
  {
    CCTagVisualDebug::instance().initializeFolders( parentPath , cmdline._outputFolderName , params._nCrowns );
    outputFileName = parentPath.string() + "/" + cmdline._outputFolderName + "/cctag" + std::to_string(nCrowns) + "CC.out";
  }else
  {
    CCTagVisualDebug::instance().initializeFolders( myPath , cmdline._outputFolderName , params._nCrowns );
    outputFileName = myPath.string() + "/" + cmdline._outputFolderName + "/cctag" + std::to_string(nCrowns) + "CC.out";
  }
  std::ofstream outputFile;
  outputFile.open( outputFileName );

  if ( (ext == ".png") || (ext == ".jpg") || (ext == ".PNG") || (ext == ".JPG")) {
    POP_INFO("looking at image " << myPath.string());

    // Gray scale convertion
    cv::Mat src = cv::imread(cmdline._filename);
    cv::Mat graySrc;
    cv::cvtColor( src, graySrc, CV_BGR2GRAY );

    // Upscale original image
    /*{
            rgb8_image_t simage;
            simage.recreate( 2 * image.width(), 2 * image.height() );
            rgb8_view_t osvw( view( simage ) );
            terry::resize_view( svw, osvw, terry::sampler::bicubic_sampler() );
    }*/

    // Call the CCTag detection
#ifdef PRINT_TO_CERR
    detection(0, graySrc, params, bank, std::cerr, myPath.stem().string());
#else
    detection(0, graySrc, params, bank, outputFile, myPath.stem().string());
#endif
} else if (ext == ".avi" )
  {
    CCTAG_COUT("*** Video mode ***");
    POP_INFO( "looking at video " << myPath.string() );

    // open video and check
    cv::VideoCapture video( cmdline._filename.c_str() );
    if(!video.isOpened())
    {
      CCTAG_COUT("Unable to open the video : " << cmdline._filename); return -1;
    }

    // play loop
    int lastFrame = video.get(CV_CAP_PROP_FRAME_COUNT);

    std::list<cv::Mat*> frames;

    std::cerr << "Starting to read video frames" << std::endl;
    while( video.get(CV_CAP_PROP_POS_FRAMES) < lastFrame )
    {
      cv::Mat frame;
      video >> frame;
      cv::Mat* imgGray = new cv::Mat;
      cv::cvtColor( frame, *imgGray, CV_BGR2GRAY );

      frames.push_back( imgGray );
    }
    std::cerr << "Done. Now processing." << std::endl;

    boost::timer t;
    std::size_t         frameId = 0;
#if 0
    boost::mutex        frame_mutex;
    boost::thread_group frame_processor;
    for( int proc=0; proc<1 ; proc++ ) {
      frame_processor.create_thread(
        [&frames, &frameId, &frame_mutex, &t, params, bank, &outputFile](){
            bool   empty;
            do {
                cv::Mat* imgGray;
                frame_mutex.lock();
                empty = frames.empty();
                if( not empty ) {
                    imgGray = frames.front();
                    frames.pop_front();
                    ++frameId;
                }
                frame_mutex.unlock();

                std::stringstream outFileName;
                outFileName << std::setfill('0') << std::setw(5) << frameId;

                detection(frameId, *imgGray, params, bank, outputFile, outFileName.str());
                if( frameId % 100 == 0 ) {
                    std::cerr << frameId << " (" << std::setprecision(3) << t.elapsed()*1000.0/frameId << ") ";
                }
                delete imgGray;
            } while( not empty );
        } );
    }
    frame_processor.join_all();
#else
    for( cv::Mat* imgGray : frames ) {
        // Set the output folder
        std::stringstream outFileName;
        outFileName << std::setfill('0') << std::setw(5) << frameId;

        // Invert the image for the projection scenario
        //cv::Mat imgGrayInverted;
        //bitwise_not ( imgGray, imgGrayInverted );

        // Call the CCTag detection
#ifdef PRINT_TO_CERR
        detection(frameId, *imgGray, params, bank, std::cerr, outFileName.str());
#else
        detection(frameId, *imgGray, params, bank, outputFile, outFileName.str());
#endif
        ++frameId;
        if( frameId % 100 == 0 ) {
            std::cerr << frameId << " (" << std::setprecision(3) << t.elapsed()*1000.0/frameId << ") ";
        }
    }
#endif
    std::cerr << std::endl;
  } else if (bfs::is_directory(myPath)) {
    CCTAG_COUT("*** Image sequence mode ***");

    std::vector<bfs::path> vFileInFolder;

    std::copy(bfs::directory_iterator(myPath), bfs::directory_iterator(), std::back_inserter(vFileInFolder)); // is directory_entry, which is
    std::sort(vFileInFolder.begin(), vFileInFolder.end());

    std::size_t frameId = 0;

    for(const auto & fileInFolder : vFileInFolder) {
      const std::string subExt(bfs::extension(fileInFolder));

      if ( (subExt == ".png") || (subExt == ".jpg") || (subExt == ".PNG") || (subExt == ".JPG") ) {

        CCTAG_COUT( "Processing image " << fileInFolder.string() );

		cv::Mat src;
    	src = cv::imread(fileInFolder.string());

        cv::Mat imgGray;
        cv::cvtColor( src, imgGray, CV_BGR2GRAY );

        // Call the CCTag detection
#ifdef PRINT_TO_CERR
        detection(frameId, imgGray, params, bank, std::cerr, fileInFolder.stem().string());
#else
        detection(frameId, imgGray, params, bank, outputFile, fileInFolder.stem().string());
#endif
++frameId;
      }
    }
  }else
  {
      throw std::logic_error("Unrecognized input.");
  }
  outputFile.close();
  return 0;
}

<|endoftext|>