コード例 #1
0
ファイル: mitkBaseRenderer.cpp プロジェクト: beneon/MITK
void mitk::BaseRenderer::SetWorldGeometry(mitk::Geometry3D* geometry)
{
    itkDebugMacro("setting WorldGeometry to " << geometry);

    if (m_WorldGeometry != geometry)
    {
        if (geometry->GetBoundingBox()->GetDiagonalLength2() == 0)
            return;

        m_WorldGeometry = geometry;
        m_TimeSlicedWorldGeometry = dynamic_cast<TimeSlicedGeometry*>(geometry);
        SlicedGeometry3D* slicedWorldGeometry;
        if (m_TimeSlicedWorldGeometry.IsNotNull())
        {
            itkDebugMacro("setting TimeSlicedWorldGeometry to " << m_TimeSlicedWorldGeometry);
            if (m_TimeStep >= m_TimeSlicedWorldGeometry->GetTimeSteps())
                m_TimeStep = m_TimeSlicedWorldGeometry->GetTimeSteps() - 1;
            slicedWorldGeometry = dynamic_cast<SlicedGeometry3D*>(m_TimeSlicedWorldGeometry->GetGeometry3D(m_TimeStep));
        }
        else
        {
            slicedWorldGeometry = dynamic_cast<SlicedGeometry3D*>(geometry);
        }
        Geometry2D::Pointer geometry2d;
        if (slicedWorldGeometry != NULL)
        {
            if (m_Slice >= slicedWorldGeometry->GetSlices() && (m_Slice != 0))
                m_Slice = slicedWorldGeometry->GetSlices() - 1;
            geometry2d = slicedWorldGeometry->GetGeometry2D(m_Slice);
            if (geometry2d.IsNull())
            {
                PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New();
                plane->InitializeStandardPlane(slicedWorldGeometry);
                geometry2d = plane;
            }
            SetCurrentWorldGeometry(slicedWorldGeometry);
        }
        else
        {
            geometry2d = dynamic_cast<Geometry2D*>(geometry);
            if (geometry2d.IsNull())
            {
                PlaneGeometry::Pointer plane = PlaneGeometry::New();
                plane->InitializeStandardPlane(geometry);
                geometry2d = plane;
            }
            SetCurrentWorldGeometry(geometry);
        }
        SetCurrentWorldGeometry2D(geometry2d); // calls Modified()
    }
    if (m_CurrentWorldGeometry2D.IsNull())
        itkWarningMacro("m_CurrentWorldGeometry2D is NULL");
}
コード例 #2
0
void
SliceNavigationController::SelectSliceByPoint( const Point3D &point )
{
  //@todo add time to PositionEvent and use here!!
  SlicedGeometry3D* slicedWorldGeometry = dynamic_cast< SlicedGeometry3D * >(
    m_CreatedWorldGeometry->GetGeometry3D( this->GetTime()->GetPos() ) );

  if ( slicedWorldGeometry )
  {
    int bestSlice = -1;
    double bestDistance = itk::NumericTraits<double>::max();

    int s, slices;
    slices = slicedWorldGeometry->GetSlices();
    if ( slicedWorldGeometry->GetEvenlySpaced() )
    {
      mitk::Geometry2D *plane = slicedWorldGeometry->GetGeometry2D( 0 );

      const Vector3D &direction = slicedWorldGeometry->GetDirectionVector();
      
      Point3D projectedPoint;
      plane->Project( point, projectedPoint );

      // Check whether the point is somewhere within the slice stack volume;
      // otherwise, the defualt slice (0) will be selected
      if ( direction[0] * (point[0] - projectedPoint[0])
         + direction[1] * (point[1] - projectedPoint[1])
         + direction[2] * (point[2] - projectedPoint[2]) >= 0 )
      {
        bestSlice = (int)(plane->Distance( point )
          / slicedWorldGeometry->GetSpacing()[2] + 0.5);
      }
    }
    else
    {
      Point3D projectedPoint;
      for ( s = 0; s < slices; ++s )
      {
        slicedWorldGeometry->GetGeometry2D( s )->Project( point, projectedPoint );
        Vector3D distance = projectedPoint - point;
        ScalarType currentDistance = distance.GetSquaredNorm();

        if ( currentDistance < bestDistance )
        {
          bestDistance = currentDistance;
          bestSlice = s;
        }
      }
    }
    if ( bestSlice >= 0 )
    {
      this->GetSlice()->SetPos( bestSlice );
    }
    else
    {
      this->GetSlice()->SetPos( 0 );
    }
    this->SendCreatedWorldGeometryUpdate();
  }
}
コード例 #3
0
ファイル: mitkBaseRenderer.cpp プロジェクト: beneon/MITK
void mitk::BaseRenderer::UpdateGeometry(const itk::EventObject & geometryUpdateEvent)
{
    const SliceNavigationController::GeometryUpdateEvent* updateEvent =
        dynamic_cast<const SliceNavigationController::GeometryUpdateEvent*>(&geometryUpdateEvent);

    if (updateEvent == NULL)
        return;

    if (m_CurrentWorldGeometry.IsNotNull())
    {
        SlicedGeometry3D* slicedWorldGeometry = dynamic_cast<SlicedGeometry3D*>(m_CurrentWorldGeometry.GetPointer());
        if (slicedWorldGeometry)
        {
            Geometry2D* geometry2D = slicedWorldGeometry->GetGeometry2D(m_Slice);

            SetCurrentWorldGeometry2D(geometry2D); // calls Modified()
        }
    }
}
コード例 #4
0
ファイル: mitkBaseRenderer.cpp プロジェクト: beneon/MITK
void mitk::BaseRenderer::SetSlice(unsigned int slice)
{
    if (m_Slice != slice)
    {
        m_Slice = slice;
        if (m_TimeSlicedWorldGeometry.IsNotNull())
        {
            SlicedGeometry3D* slicedWorldGeometry = dynamic_cast<SlicedGeometry3D*>(m_TimeSlicedWorldGeometry->GetGeometry3D(m_TimeStep));
            if (slicedWorldGeometry != NULL)
            {
                if (m_Slice >= slicedWorldGeometry->GetSlices())
                    m_Slice = slicedWorldGeometry->GetSlices() - 1;
                SetCurrentWorldGeometry2D(slicedWorldGeometry->GetGeometry2D(m_Slice));
                SetCurrentWorldGeometry(slicedWorldGeometry);
            }
        }
        else
            Modified();
    }
}
コード例 #5
0
ファイル: mitkBaseRenderer.cpp プロジェクト: beneon/MITK
void mitk::BaseRenderer::SetTimeStep(unsigned int timeStep)
{
    if (m_TimeStep != timeStep)
    {
        m_TimeStep = timeStep;
        m_TimeStepUpdateTime.Modified();

        if (m_TimeSlicedWorldGeometry.IsNotNull())
        {
            if (m_TimeStep >= m_TimeSlicedWorldGeometry->GetTimeSteps())
                m_TimeStep = m_TimeSlicedWorldGeometry->GetTimeSteps() - 1;
            SlicedGeometry3D* slicedWorldGeometry = dynamic_cast<SlicedGeometry3D*>(m_TimeSlicedWorldGeometry->GetGeometry3D(m_TimeStep));
            if (slicedWorldGeometry != NULL)
            {
                SetCurrentWorldGeometry2D(slicedWorldGeometry->GetGeometry2D(m_Slice));
                SetCurrentWorldGeometry(slicedWorldGeometry);
            }
        }
        else
            Modified();
    }
}
コード例 #6
0
mitk::SlicedGeometry3D::SlicedGeometry3D(const SlicedGeometry3D& other)
  : Superclass(other),
  m_EvenlySpaced( other.m_EvenlySpaced ),
  m_Slices( other.m_Slices ),
  m_ReferenceGeometry( other.m_ReferenceGeometry ),
  m_SliceNavigationController( other.m_SliceNavigationController )
{
  m_DirectionVector.Fill(0);
  SetSpacing( other.GetSpacing() );
  SetDirectionVector( other.GetDirectionVector() );

  if ( m_EvenlySpaced )
  {
    PlaneGeometry::Pointer geometry = other.m_PlaneGeometries[0]->Clone();
    assert(geometry.IsNotNull());
    SetPlaneGeometry(geometry, 0);
  }
  else
  {
    unsigned int s;
    for ( s = 0; s < other.m_Slices; ++s )
    {
      if ( other.m_PlaneGeometries[s].IsNull() )
      {
        assert(other.m_EvenlySpaced);
        m_PlaneGeometries[s] = nullptr;
      }
      else
      {
        PlaneGeometry* geometry2D = other.m_PlaneGeometries[s]->Clone();
        assert(geometry2D!=nullptr);
        SetPlaneGeometry(geometry2D, s);
      }
    }
  }
}
コード例 #7
0
ファイル: mitkImage.cpp プロジェクト: ClydeChen/MITK
void mitk::Image::Initialize(vtkImageData* vtkimagedata, int channels, int tDim, int sDim, int pDim)
{
  if(vtkimagedata==NULL) return;

  m_Dimension=vtkimagedata->GetDataDimension();
  unsigned int i, *tmpDimensions=new unsigned int[m_Dimension>4?m_Dimension:4];
  for(i=0;i<m_Dimension;++i) tmpDimensions[i]=vtkimagedata->GetDimensions()[i];
  if(m_Dimension<4)
  {
    unsigned int *p;
    for(i=0,p=tmpDimensions+m_Dimension;i<4-m_Dimension;++i, ++p)
      *p=1;
  }

  if(pDim>=0)
  {
    tmpDimensions[1]=pDim;
    if(m_Dimension < 2)
      m_Dimension = 2;
  }
  if(sDim>=0)
  {
    tmpDimensions[2]=sDim;
    if(m_Dimension < 3)
      m_Dimension = 3;
  }
  if(tDim>=0)
  {
    tmpDimensions[3]=tDim;
    if(m_Dimension < 4)
      m_Dimension = 4;
  }


  switch ( vtkimagedata->GetScalarType() )
  {
  case VTK_BIT:
  case VTK_CHAR:
    //pixelType.Initialize(typeid(char), vtkimagedata->GetNumberOfScalarComponents());
    Initialize(mitk::MakeScalarPixelType<char>(), m_Dimension, tmpDimensions, channels);
    break;
  case VTK_UNSIGNED_CHAR:
    //pixelType.Initialize(typeid(unsigned char), vtkimagedata->GetNumberOfScalarComponents());
    Initialize(mitk::MakeScalarPixelType<unsigned char>(), m_Dimension, tmpDimensions, channels);
    break;
  case VTK_SHORT:
    //pixelType.Initialize(typeid(short), vtkimagedata->GetNumberOfScalarComponents());
    Initialize(mitk::MakeScalarPixelType<short>(), m_Dimension, tmpDimensions, channels);
    break;
  case VTK_UNSIGNED_SHORT:
    //pixelType.Initialize(typeid(unsigned short), vtkimagedata->GetNumberOfScalarComponents());
    Initialize(mitk::MakeScalarPixelType<unsigned short>(), m_Dimension, tmpDimensions, channels);
    break;
  case VTK_INT:
    //pixelType.Initialize(typeid(int), vtkimagedata->GetNumberOfScalarComponents());
    Initialize(mitk::MakeScalarPixelType<int>(), m_Dimension, tmpDimensions, channels);
    break;
  case VTK_UNSIGNED_INT:
    //pixelType.Initialize(typeid(unsigned int), vtkimagedata->GetNumberOfScalarComponents());
    Initialize(mitk::MakeScalarPixelType<unsigned int>(), m_Dimension, tmpDimensions, channels);
    break;
  case VTK_LONG:
    //pixelType.Initialize(typeid(long), vtkimagedata->GetNumberOfScalarComponents());
    Initialize(mitk::MakeScalarPixelType<long>(), m_Dimension, tmpDimensions, channels);
    break;
  case VTK_UNSIGNED_LONG:
    //pixelType.Initialize(typeid(unsigned long), vtkimagedata->GetNumberOfScalarComponents());
    Initialize(mitk::MakeScalarPixelType<unsigned long>(), m_Dimension, tmpDimensions, channels);
    break;
  case VTK_FLOAT:
    //pixelType.Initialize(typeid(float), vtkimagedata->GetNumberOfScalarComponents());
    Initialize(mitk::MakeScalarPixelType<float>(), m_Dimension, tmpDimensions, channels);
    break;
  case VTK_DOUBLE:
    //pixelType.Initialize(typeid(double), vtkimagedata->GetNumberOfScalarComponents());
    Initialize(mitk::MakeScalarPixelType<double>(), m_Dimension, tmpDimensions, channels);
    break;
  default:
    break;
  }
  /*
  Initialize(pixelType,
    m_Dimension,
    tmpDimensions,
    channels);
*/

  const double *spacinglist = vtkimagedata->GetSpacing();
  Vector3D spacing;
  FillVector3D(spacing, spacinglist[0], 1.0, 1.0);
  if(m_Dimension>=2)
    spacing[1]=spacinglist[1];
  if(m_Dimension>=3)
    spacing[2]=spacinglist[2];

  // access origin of vtkImage
  Point3D origin;
  double vtkorigin[3];
  vtkimagedata->GetOrigin(vtkorigin);
  FillVector3D(origin, vtkorigin[0], 0.0, 0.0);
  if(m_Dimension>=2)
    origin[1]=vtkorigin[1];
  if(m_Dimension>=3)
    origin[2]=vtkorigin[2];

  SlicedGeometry3D* slicedGeometry = GetSlicedGeometry(0);

  // re-initialize PlaneGeometry with origin and direction
  PlaneGeometry* planeGeometry = static_cast<PlaneGeometry*>(slicedGeometry->GetGeometry2D(0));
  planeGeometry->SetOrigin(origin);

  // re-initialize SlicedGeometry3D
  slicedGeometry->SetOrigin(origin);
  slicedGeometry->SetSpacing(spacing);

  ProportionalTimeGeometry::Pointer timeGeometry = ProportionalTimeGeometry::New();
  timeGeometry->Initialize(slicedGeometry, m_Dimensions[3]);
  SetTimeGeometry(timeGeometry);

  delete [] tmpDimensions;
}
コード例 #8
0
  std::vector<BaseData::Pointer> ItkImageIO::Read()
  {
    std::vector<BaseData::Pointer> result;
    mitk::LocaleSwitch localeSwitch("C");

    Image::Pointer image = Image::New();

    const unsigned int MINDIM = 2;
    const unsigned int MAXDIM = 4;

    const std::string path = this->GetLocalFileName();

    MITK_INFO << "loading " << path << " via itk::ImageIOFactory... " << std::endl;

    // Check to see if we can read the file given the name or prefix
    if (path.empty())
    {
      mitkThrow() << "Empty filename in mitk::ItkImageIO ";
    }

    // Got to allocate space for the image. Determine the characteristics of
    // the image.
    m_ImageIO->SetFileName(path);
    m_ImageIO->ReadImageInformation();

    unsigned int ndim = m_ImageIO->GetNumberOfDimensions();
    if (ndim < MINDIM || ndim > MAXDIM)
    {
      MITK_WARN << "Sorry, only dimensions 2, 3 and 4 are supported. The given file has " << ndim
                << " dimensions! Reading as 4D.";
      ndim = MAXDIM;
    }

    itk::ImageIORegion ioRegion(ndim);
    itk::ImageIORegion::SizeType ioSize = ioRegion.GetSize();
    itk::ImageIORegion::IndexType ioStart = ioRegion.GetIndex();

    unsigned int dimensions[MAXDIM];
    dimensions[0] = 0;
    dimensions[1] = 0;
    dimensions[2] = 0;
    dimensions[3] = 0;

    ScalarType spacing[MAXDIM];
    spacing[0] = 1.0f;
    spacing[1] = 1.0f;
    spacing[2] = 1.0f;
    spacing[3] = 1.0f;

    Point3D origin;
    origin.Fill(0);

    unsigned int i;
    for (i = 0; i < ndim; ++i)
    {
      ioStart[i] = 0;
      ioSize[i] = m_ImageIO->GetDimensions(i);
      if (i < MAXDIM)
      {
        dimensions[i] = m_ImageIO->GetDimensions(i);
        spacing[i] = m_ImageIO->GetSpacing(i);
        if (spacing[i] <= 0)
          spacing[i] = 1.0f;
      }
      if (i < 3)
      {
        origin[i] = m_ImageIO->GetOrigin(i);
      }
    }

    ioRegion.SetSize(ioSize);
    ioRegion.SetIndex(ioStart);

    MITK_INFO << "ioRegion: " << ioRegion << std::endl;
    m_ImageIO->SetIORegion(ioRegion);
    void *buffer = new unsigned char[m_ImageIO->GetImageSizeInBytes()];
    m_ImageIO->Read(buffer);

    image->Initialize(MakePixelType(m_ImageIO), ndim, dimensions);
    image->SetImportChannel(buffer, 0, Image::ManageMemory);

    const itk::MetaDataDictionary &dictionary = m_ImageIO->GetMetaDataDictionary();

    // access direction of itk::Image and include spacing
    mitk::Matrix3D matrix;
    matrix.SetIdentity();
    unsigned int j, itkDimMax3 = (ndim >= 3 ? 3 : ndim);
    for (i = 0; i < itkDimMax3; ++i)
      for (j = 0; j < itkDimMax3; ++j)
        matrix[i][j] = m_ImageIO->GetDirection(j)[i];

    // re-initialize PlaneGeometry with origin and direction
    PlaneGeometry *planeGeometry = image->GetSlicedGeometry(0)->GetPlaneGeometry(0);
    planeGeometry->SetOrigin(origin);
    planeGeometry->GetIndexToWorldTransform()->SetMatrix(matrix);

    // re-initialize SlicedGeometry3D
    SlicedGeometry3D *slicedGeometry = image->GetSlicedGeometry(0);
    slicedGeometry->InitializeEvenlySpaced(planeGeometry, image->GetDimension(2));
    slicedGeometry->SetSpacing(spacing);

    MITK_INFO << slicedGeometry->GetCornerPoint(false, false, false);
    MITK_INFO << slicedGeometry->GetCornerPoint(true, true, true);

    // re-initialize TimeGeometry
    TimeGeometry::Pointer timeGeometry;

    if (dictionary.HasKey(PROPERTY_NAME_TIMEGEOMETRY_TYPE) || dictionary.HasKey(PROPERTY_KEY_TIMEGEOMETRY_TYPE))
    { // also check for the name because of backwards compatibility. Past code version stored with the name and not with
      // the key
      itk::MetaDataObject<std::string>::ConstPointer timeGeometryTypeData = nullptr;
      if (dictionary.HasKey(PROPERTY_NAME_TIMEGEOMETRY_TYPE))
      {
        timeGeometryTypeData =
          dynamic_cast<const itk::MetaDataObject<std::string> *>(dictionary.Get(PROPERTY_NAME_TIMEGEOMETRY_TYPE));
      }
      else
      {
        timeGeometryTypeData =
          dynamic_cast<const itk::MetaDataObject<std::string> *>(dictionary.Get(PROPERTY_KEY_TIMEGEOMETRY_TYPE));
      }

      if (timeGeometryTypeData->GetMetaDataObjectValue() == ArbitraryTimeGeometry::GetStaticNameOfClass())
      {
        MITK_INFO << "used time geometry: " << ArbitraryTimeGeometry::GetStaticNameOfClass() << std::endl;
        typedef std::vector<TimePointType> TimePointVector;
        TimePointVector timePoints;

        if (dictionary.HasKey(PROPERTY_NAME_TIMEGEOMETRY_TIMEPOINTS))
        {
          timePoints = ConvertMetaDataObjectToTimePointList(dictionary.Get(PROPERTY_NAME_TIMEGEOMETRY_TIMEPOINTS));
        }
        else if (dictionary.HasKey(PROPERTY_KEY_TIMEGEOMETRY_TIMEPOINTS))
        {
          timePoints = ConvertMetaDataObjectToTimePointList(dictionary.Get(PROPERTY_KEY_TIMEGEOMETRY_TIMEPOINTS));
        }

        if (timePoints.size() - 1 != image->GetDimension(3))
        {
          MITK_ERROR << "Stored timepoints (" << timePoints.size() - 1 << ") and size of image time dimension ("
                     << image->GetDimension(3) << ") do not match. Switch to ProportionalTimeGeometry fallback"
                     << std::endl;
        }
        else
        {
          ArbitraryTimeGeometry::Pointer arbitraryTimeGeometry = ArbitraryTimeGeometry::New();
          TimePointVector::const_iterator pos = timePoints.begin();
          TimePointVector::const_iterator prePos = pos++;

          for (; pos != timePoints.end(); ++prePos, ++pos)
          {
            arbitraryTimeGeometry->AppendTimeStepClone(slicedGeometry, *pos, *prePos);
          }

          timeGeometry = arbitraryTimeGeometry;
        }
      }
    }

    if (timeGeometry.IsNull())
    { // Fallback. If no other valid time geometry has been created, create a ProportionalTimeGeometry
      MITK_INFO << "used time geometry: " << ProportionalTimeGeometry::GetStaticNameOfClass() << std::endl;
      ProportionalTimeGeometry::Pointer propTimeGeometry = ProportionalTimeGeometry::New();
      propTimeGeometry->Initialize(slicedGeometry, image->GetDimension(3));
      timeGeometry = propTimeGeometry;
    }

    image->SetTimeGeometry(timeGeometry);

    buffer = NULL;
    MITK_INFO << "number of image components: " << image->GetPixelType().GetNumberOfComponents() << std::endl;

    for (itk::MetaDataDictionary::ConstIterator iter = dictionary.Begin(), iterEnd = dictionary.End(); iter != iterEnd;
         ++iter)
    {
      if (iter->second->GetMetaDataObjectTypeInfo() == typeid(std::string))
      {
        const std::string &key = iter->first;
        std::string assumedPropertyName = key;
        std::replace(assumedPropertyName.begin(), assumedPropertyName.end(), '_', '.');

        std::string mimeTypeName = GetMimeType()->GetName();

        // Check if there is already a info for the key and our mime type.
        IPropertyPersistence::InfoResultType infoList = mitk::CoreServices::GetPropertyPersistence()->GetInfoByKey(key);

        auto predicate = [mimeTypeName](const PropertyPersistenceInfo::ConstPointer &x) {
          return x.IsNotNull() && x->GetMimeTypeName() == mimeTypeName;
        };
        auto finding = std::find_if(infoList.begin(), infoList.end(), predicate);

        if (finding == infoList.end())
        {
          auto predicateWild = [](const PropertyPersistenceInfo::ConstPointer &x) {
            return x.IsNotNull() && x->GetMimeTypeName() == PropertyPersistenceInfo::ANY_MIMETYPE_NAME();
          };
          finding = std::find_if(infoList.begin(), infoList.end(), predicateWild);
        }

        PropertyPersistenceInfo::ConstPointer info;

        if (finding != infoList.end())
        {
          assumedPropertyName = (*finding)->GetName();
          info = *finding;
        }
        else
        { // we have not found anything suitable so we generate our own info
          PropertyPersistenceInfo::Pointer newInfo = PropertyPersistenceInfo::New();
          newInfo->SetNameAndKey(assumedPropertyName, key);
          newInfo->SetMimeTypeName(PropertyPersistenceInfo::ANY_MIMETYPE_NAME());
          info = newInfo;
        }

        std::string value =
          dynamic_cast<itk::MetaDataObject<std::string> *>(iter->second.GetPointer())->GetMetaDataObjectValue();

        mitk::BaseProperty::Pointer loadedProp = info->GetDeserializationFunction()(value);

        image->SetProperty(assumedPropertyName.c_str(), loadedProp);

        // Read properties should be persisted unless they are default properties
        // which are written anyway
        bool isDefaultKey(false);

        for (const auto &defaultKey : m_DefaultMetaDataKeys)
        {
          if (defaultKey.length() <= assumedPropertyName.length())
          {
            // does the start match the default key
            if (assumedPropertyName.substr(0, defaultKey.length()).find(defaultKey) != std::string::npos)
            {
              isDefaultKey = true;
              break;
            }
          }
        }

        if (!isDefaultKey)
        {
          mitk::CoreServices::GetPropertyPersistence()->AddInfo(info);
        }
      }
    }

    MITK_INFO << "...finished!" << std::endl;

    result.push_back(image.GetPointer());
    return result;
  }
コード例 #9
0
ファイル: mitkLabelSetImageIO.cpp プロジェクト: dkuegler/MITK
std::vector<BaseData::Pointer> LabelSetImageIO::Read()
{
  const std::string& locale = "C";
  const std::string& currLocale = setlocale( LC_ALL, NULL );

  if ( locale.compare(currLocale)!=0 )
  {
    try
    {
      setlocale(LC_ALL, locale.c_str());
    }
    catch(...)
    {
      mitkThrow() << "Could not set locale.";
    }
  }

  // begin regular image loading, adapted from mitkItkImageIO
  itk::NrrdImageIO::Pointer nrrdImageIO = itk::NrrdImageIO::New();
  Image::Pointer image = Image::New();

  const unsigned int MINDIM = 2;
  const unsigned int MAXDIM = 4;

  const std::string path = this->GetLocalFileName();

  MITK_INFO << "loading " << path << " via itk::ImageIOFactory... " << std::endl;

  // Check to see if we can read the file given the name or prefix
  if (path.empty())
  {
    mitkThrow() << "Empty filename in mitk::ItkImageIO ";
  }

  // Got to allocate space for the image. Determine the characteristics of
  // the image.
  nrrdImageIO->SetFileName(path);
  nrrdImageIO->ReadImageInformation();

  unsigned int ndim = nrrdImageIO->GetNumberOfDimensions();
  if (ndim < MINDIM || ndim > MAXDIM)
  {
    MITK_WARN << "Sorry, only dimensions 2, 3 and 4 are supported. The given file has " << ndim << " dimensions! Reading as 4D.";
    ndim = MAXDIM;
  }

  itk::ImageIORegion ioRegion(ndim);
  itk::ImageIORegion::SizeType ioSize = ioRegion.GetSize();
  itk::ImageIORegion::IndexType ioStart = ioRegion.GetIndex();

  unsigned int dimensions[MAXDIM];
  dimensions[0] = 0;
  dimensions[1] = 0;
  dimensions[2] = 0;
  dimensions[3] = 0;

  ScalarType spacing[MAXDIM];
  spacing[0] = 1.0f;
  spacing[1] = 1.0f;
  spacing[2] = 1.0f;
  spacing[3] = 1.0f;

  Point3D origin;
  origin.Fill(0);

  unsigned int i;
  for (i = 0; i < ndim; ++i)
  {
    ioStart[i] = 0;
    ioSize[i] = nrrdImageIO->GetDimensions(i);
    if (i<MAXDIM)
    {
      dimensions[i] = nrrdImageIO->GetDimensions(i);
      spacing[i] = nrrdImageIO->GetSpacing(i);
      if (spacing[i] <= 0)
        spacing[i] = 1.0f;
    }
    if (i<3)
    {
      origin[i] = nrrdImageIO->GetOrigin(i);
    }
  }

  ioRegion.SetSize(ioSize);
  ioRegion.SetIndex(ioStart);

  MITK_INFO << "ioRegion: " << ioRegion << std::endl;
  nrrdImageIO->SetIORegion(ioRegion);
  void* buffer = new unsigned char[nrrdImageIO->GetImageSizeInBytes()];
  nrrdImageIO->Read(buffer);

  image->Initialize(MakePixelType(nrrdImageIO), ndim, dimensions);
  image->SetImportChannel(buffer, 0, Image::ManageMemory);

  // access direction of itk::Image and include spacing
  mitk::Matrix3D matrix;
  matrix.SetIdentity();
  unsigned int j, itkDimMax3 = (ndim >= 3 ? 3 : ndim);
  for (i = 0; i < itkDimMax3; ++i)
    for (j = 0; j < itkDimMax3; ++j)
      matrix[i][j] = nrrdImageIO->GetDirection(j)[i];

  // re-initialize PlaneGeometry with origin and direction
  PlaneGeometry* planeGeometry = image->GetSlicedGeometry(0)->GetPlaneGeometry(0);
  planeGeometry->SetOrigin(origin);
  planeGeometry->GetIndexToWorldTransform()->SetMatrix(matrix);

  // re-initialize SlicedGeometry3D
  SlicedGeometry3D* slicedGeometry = image->GetSlicedGeometry(0);
  slicedGeometry->InitializeEvenlySpaced(planeGeometry, image->GetDimension(2));
  slicedGeometry->SetSpacing(spacing);

  MITK_INFO << slicedGeometry->GetCornerPoint(false, false, false);
  MITK_INFO << slicedGeometry->GetCornerPoint(true, true, true);

  // re-initialize TimeGeometry
  ProportionalTimeGeometry::Pointer timeGeometry = ProportionalTimeGeometry::New();
  timeGeometry->Initialize(slicedGeometry, image->GetDimension(3));
  image->SetTimeGeometry(timeGeometry);

  buffer = NULL;
  MITK_INFO << "number of image components: " << image->GetPixelType().GetNumberOfComponents() << std::endl;

  const itk::MetaDataDictionary& dictionary = nrrdImageIO->GetMetaDataDictionary();
  for (itk::MetaDataDictionary::ConstIterator iter = dictionary.Begin(), iterEnd = dictionary.End();
    iter != iterEnd; ++iter)
  {
    std::string key = std::string("meta.") + iter->first;
    if (iter->second->GetMetaDataObjectTypeInfo() == typeid(std::string))
    {
      std::string value = dynamic_cast<itk::MetaDataObject<std::string>*>(iter->second.GetPointer())->GetMetaDataObjectValue();
      image->SetProperty(key.c_str(), mitk::StringProperty::New(value));
    }
  }

  // end regular image loading

  LabelSetImage::Pointer output = LabelSetImageConverter::ConvertImageToLabelSetImage(image);

  // get labels and add them as properties to the image
  char keybuffer[256];

  unsigned int numberOfLayers = GetIntByKey(dictionary, "layers");
  std::string _xmlStr;
  mitk::Label::Pointer label;

  for (unsigned int layerIdx = 0; layerIdx < numberOfLayers; layerIdx++)
  {
    sprintf(keybuffer, "layer_%03d", layerIdx);
    int numberOfLabels = GetIntByKey(dictionary, keybuffer);

    mitk::LabelSet::Pointer labelSet = mitk::LabelSet::New();

    for (int labelIdx = 0; labelIdx < numberOfLabels; labelIdx++)
    {
      TiXmlDocument doc;
      sprintf(keybuffer, "label_%03d_%05d", layerIdx, labelIdx);
      _xmlStr = GetStringByKey(dictionary, keybuffer);
      doc.Parse(_xmlStr.c_str());

      TiXmlElement * labelElem = doc.FirstChildElement("Label");
      if (labelElem == 0)
        mitkThrow() << "Error parsing NRRD header for mitk::LabelSetImage IO";

      label = LoadLabelFromTiXmlDocument(labelElem);

      if (label->GetValue() == 0) // set exterior label is needed to hold exterior information
        output->SetExteriorLabel(label);
      labelSet->AddLabel(label);
      labelSet->SetLayer(layerIdx);
    }
    output->AddLabelSetToLayer(layerIdx, labelSet);
  }

  MITK_INFO << "...finished!" << std::endl;

  try
  {
    setlocale(LC_ALL, currLocale.c_str());
  }
  catch(...)
  {
    mitkThrow() << "Could not reset locale!";
  }

  std::vector<BaseData::Pointer> result;
  result.push_back(output.GetPointer());
  return result;
}
コード例 #10
0
ファイル: mitkImage.cpp プロジェクト: 0r/MITK
void mitk::Image::Initialize(vtkImageData* vtkimagedata, int channels, int tDim, int sDim, int pDim)
{
  if(vtkimagedata==nullptr) return;

  m_Dimension=vtkimagedata->GetDataDimension();
  unsigned int i, *tmpDimensions=new unsigned int[m_Dimension>4?m_Dimension:4];
  for(i=0;i<m_Dimension;++i) tmpDimensions[i]=vtkimagedata->GetDimensions()[i];
  if(m_Dimension<4)
  {
    unsigned int *p;
    for(i=0,p=tmpDimensions+m_Dimension;i<4-m_Dimension;++i, ++p)
      *p=1;
  }

  if(pDim>=0)
  {
    tmpDimensions[1]=pDim;
    if(m_Dimension < 2)
      m_Dimension = 2;
  }
  if(sDim>=0)
  {
    tmpDimensions[2]=sDim;
    if(m_Dimension < 3)
      m_Dimension = 3;
  }
  if(tDim>=0)
  {
    tmpDimensions[3]=tDim;
    if(m_Dimension < 4)
      m_Dimension = 4;
  }

  mitk::PixelType pixelType(MakePixelType(vtkimagedata));
  Initialize(pixelType, m_Dimension, tmpDimensions, channels);

  const double *spacinglist = vtkimagedata->GetSpacing();
  Vector3D spacing;
  FillVector3D(spacing, spacinglist[0], 1.0, 1.0);
  if(m_Dimension>=2)
    spacing[1]=spacinglist[1];
  if(m_Dimension>=3)
    spacing[2]=spacinglist[2];

  // access origin of vtkImage
  Point3D origin;
  double vtkorigin[3];
  vtkimagedata->GetOrigin(vtkorigin);
  FillVector3D(origin, vtkorigin[0], 0.0, 0.0);
  if(m_Dimension>=2)
    origin[1]=vtkorigin[1];
  if(m_Dimension>=3)
    origin[2]=vtkorigin[2];

  SlicedGeometry3D* slicedGeometry = GetSlicedGeometry(0);

  // re-initialize PlaneGeometry with origin and direction
  PlaneGeometry* planeGeometry = static_cast<PlaneGeometry*>(slicedGeometry->GetPlaneGeometry(0));
  planeGeometry->SetOrigin(origin);

  // re-initialize SlicedGeometry3D
  slicedGeometry->SetOrigin(origin);
  slicedGeometry->SetSpacing(spacing);

  ProportionalTimeGeometry::Pointer timeGeometry = ProportionalTimeGeometry::New();
  timeGeometry->Initialize(slicedGeometry, m_Dimensions[3]);
  SetTimeGeometry(timeGeometry);

  delete [] tmpDimensions;
}
コード例 #11
0
ファイル: mitkItkImageIO.cpp プロジェクト: ImageKit/MITK
std::vector<BaseData::Pointer> ItkImageIO::Read()
{
  std::vector<BaseData::Pointer> result;

  const std::string& locale = "C";
  const std::string& currLocale = setlocale( LC_ALL, NULL );

  if ( locale.compare(currLocale)!=0 )
  {
    try
    {
      setlocale(LC_ALL, locale.c_str());
    }
    catch(...)
    {
      MITK_INFO << "Could not set locale " << locale;
    }
  }

  Image::Pointer image = Image::New();

  const unsigned int MINDIM = 2;
  const unsigned int MAXDIM = 4;

  const std::string path = this->GetLocalFileName();

  MITK_INFO << "loading " << path << " via itk::ImageIOFactory... " << std::endl;

  // Check to see if we can read the file given the name or prefix
  if (path.empty())
  {
    mitkThrow() << "Empty filename in mitk::ItkImageIO ";
  }

  // Got to allocate space for the image. Determine the characteristics of
  // the image.
  m_ImageIO->SetFileName( path );
  m_ImageIO->ReadImageInformation();

  unsigned int ndim = m_ImageIO->GetNumberOfDimensions();
  if ( ndim < MINDIM || ndim > MAXDIM )
  {
    MITK_WARN << "Sorry, only dimensions 2, 3 and 4 are supported. The given file has " << ndim << " dimensions! Reading as 4D.";
    ndim = MAXDIM;
  }

  itk::ImageIORegion ioRegion( ndim );
  itk::ImageIORegion::SizeType ioSize = ioRegion.GetSize();
  itk::ImageIORegion::IndexType ioStart = ioRegion.GetIndex();

  unsigned int dimensions[ MAXDIM ];
  dimensions[ 0 ] = 0;
  dimensions[ 1 ] = 0;
  dimensions[ 2 ] = 0;
  dimensions[ 3 ] = 0;

  ScalarType spacing[ MAXDIM ];
  spacing[ 0 ] = 1.0f;
  spacing[ 1 ] = 1.0f;
  spacing[ 2 ] = 1.0f;
  spacing[ 3 ] = 1.0f;

  Point3D origin;
  origin.Fill(0);

  unsigned int i;
  for ( i = 0; i < ndim ; ++i )
  {
    ioStart[ i ] = 0;
    ioSize[ i ] = m_ImageIO->GetDimensions( i );
    if(i<MAXDIM)
    {
      dimensions[ i ] = m_ImageIO->GetDimensions( i );
      spacing[ i ] = m_ImageIO->GetSpacing( i );
      if(spacing[ i ] <= 0)
        spacing[ i ] = 1.0f;
    }
    if(i<3)
    {
      origin[ i ] = m_ImageIO->GetOrigin( i );
    }
  }

  ioRegion.SetSize( ioSize );
  ioRegion.SetIndex( ioStart );

  MITK_INFO << "ioRegion: " << ioRegion << std::endl;
  m_ImageIO->SetIORegion( ioRegion );
  void* buffer = new unsigned char[m_ImageIO->GetImageSizeInBytes()];
  m_ImageIO->Read( buffer );

  image->Initialize( MakePixelType(m_ImageIO), ndim, dimensions );
  image->SetImportChannel( buffer, 0, Image::ManageMemory );

  // access direction of itk::Image and include spacing
  mitk::Matrix3D matrix;
  matrix.SetIdentity();
  unsigned int j, itkDimMax3 = (ndim >= 3? 3 : ndim);
  for ( i=0; i < itkDimMax3; ++i)
    for( j=0; j < itkDimMax3; ++j )
      matrix[i][j] = m_ImageIO->GetDirection(j)[i];

  // re-initialize PlaneGeometry with origin and direction
  PlaneGeometry* planeGeometry = image->GetSlicedGeometry(0)->GetPlaneGeometry(0);
  planeGeometry->SetOrigin(origin);
  planeGeometry->GetIndexToWorldTransform()->SetMatrix(matrix);

  // re-initialize SlicedGeometry3D
  SlicedGeometry3D* slicedGeometry = image->GetSlicedGeometry(0);
  slicedGeometry->InitializeEvenlySpaced(planeGeometry, image->GetDimension(2));
  slicedGeometry->SetSpacing(spacing);

  MITK_INFO << slicedGeometry->GetCornerPoint(false,false,false);
  MITK_INFO << slicedGeometry->GetCornerPoint(true,true,true);

  // re-initialize TimeGeometry
  ProportionalTimeGeometry::Pointer timeGeometry = ProportionalTimeGeometry::New();
  timeGeometry->Initialize(slicedGeometry, image->GetDimension(3));
  image->SetTimeGeometry(timeGeometry);

  buffer = NULL;
  MITK_INFO << "number of image components: "<< image->GetPixelType().GetNumberOfComponents() << std::endl;

  const itk::MetaDataDictionary& dictionary = m_ImageIO->GetMetaDataDictionary();
  for (itk::MetaDataDictionary::ConstIterator iter = dictionary.Begin(), iterEnd = dictionary.End();
       iter != iterEnd; ++iter)
  {
    std::string key = std::string("meta.") + iter->first;
    if (iter->second->GetMetaDataObjectTypeInfo() == typeid(std::string))
    {
      std::string value = dynamic_cast<itk::MetaDataObject<std::string>*>(iter->second.GetPointer())->GetMetaDataObjectValue();
      image->SetProperty(key.c_str(), mitk::StringProperty::New(value));
    }
  }

  MITK_INFO << "...finished!" << std::endl;

  try
  {
    setlocale(LC_ALL, currLocale.c_str());
  }
  catch(...)
  {
    MITK_INFO << "Could not reset locale " << currLocale;
  }

  result.push_back(image.GetPointer());
  return result;
}