Пример #1
0
// ------------------------------------------------------------------------
void ValveNormaliser::AlignValve(const ValveType::Pointer &input, ValveType::Pointer &output)
{
	if(!output) output = ValveType::New();

	ImageType::Pointer image = input->GetImage();
	PointType p1 = input->GetP1();
	PointType p2 = input->GetP2();


	// tranlsation to the origin
	m_Transform = TransformType::New();
	m_Transform->SetCenter(p1);

	TransformType::OutputVectorType axis;
	for(unsigned int i = 0; i < 3; i++)
	{
		axis[i] = -image->GetDirection()(i,2);
	}

	itk::Vector<double, 3> vec1, vec2;
	for(unsigned int i = 0; i < 3; i++)
	{
		vec1[i] = p2[i]-p1[i];
		vec2[i] = image->GetDirection()(i,0);
	}

	vec1.Normalize();
	vec2.Normalize();

	double angle = acos(vec2*vec1);
	itk::Vector<double,3> axis2 = itk::CrossProduct(vec1,vec2);
	axis2.Normalize();

	m_Transform->Rotate3D(axis, angle);

	typedef itk::ResampleImageFilter<ImageType, ImageType> ResamplerType;
	ResamplerType::Pointer resampler = ResamplerType::New();
	resampler->SetInput(image);
	resampler->SetTransform(m_Transform);
	resampler->SetOutputParametersFromImage(image);
	resampler->Update();


	// create the output 
	if(!output) output = ValveLine<3>::New();
	output->SetImage(resampler->GetOutput());
	output->SetP1(m_Transform->TransformPoint(input->GetP1()));
	output->SetP2(m_Transform->GetInverseTransform()->TransformPoint(input->GetP2()));
	output->UpdateIndexs();
}
Пример #2
0
// ------------------------------------------------------------------------
void transformPointToPatient(const ImageType::Pointer &reference,
		const SeriesTransform &series, const std::vector<int> &roiOffset,
		const ImageType::PointType &input, ImageType::PointType &output)
{
	// rotation is easy
	MatrixType rotTemp = reference->GetDirection().GetVnlMatrix();
	MatrixType rotation;
	rotation.set_size(3,3);
	for(unsigned int i = 0; i < 3; i++)
	{
		rotation(i,0) = rotTemp(i,1);
		rotation(i,1) = rotTemp(i,0);
		rotation(i,2) = rotTemp(i,2);
	}

	VectorType refOrig = reference->GetOrigin().GetVnlVector();
	VectorType offset  = vnl_inverse(rotation) * refOrig;

	vnl_vector<double> vnl_output;

	// translate the point
	vnl_output = vnl_inverse(rotation) * input.GetVnlVector();
	vnl_output = vnl_output - offset;
	vnl_output /= reference->GetSpacing()[0];
	for(unsigned int i = 0; i < 3; i++)
	{
		vnl_output[i] -= roiOffset[i];
		vnl_output[i] -= series.translation[i];
	}

	output[0] = vnl_output[0];
	output[1] = vnl_output[1];
	output[2] = vnl_output[2];
}
Пример #3
0
bool imageSort(const ImageType::Pointer &im1, const ImageType::Pointer &im2)
{
	ImageType::PointType or1 = im1->GetOrigin();
	ImageType::PointType or2 = im2->GetOrigin();

	ImageType::DirectionType direction = im1->GetDirection();
	itk::Vector<double, 3> dir, v1, v2, normed;
   	for(unsigned int i = 0; i < 3; i++)
   	{
   		dir[i] = direction(i,2);
		v1[i] = or1[i];
		v2[i] = or2[i];
   	}

	std::cout << dir << std::endl;
	double mul1 = v1[0] / dir[0];
	double mul2 = v2[0] / dir[0];

	
	



	return (mul1<mul2);

}
Пример #4
0
// ------------------------------------------------------------------------
void buildOutput(const SeriesTransform::List &series, ImageType::Pointer &outputImage,
		ImageType::Pointer &outputLabel, const unsigned int & timestep)
{
	// get the output parameters
	unsigned int slices = series.size();
	unsigned int timeSteps = series.front().images.size();
	ImageType::Pointer ref = series.front().images.front();




	
	ImageType::SpacingType spacing = ref->GetSpacing();
	spacing[2] = series.front().sliceThickness;
	ImageType::DirectionType direction = ref->GetDirection();
	ImageType::PointType origin = ref->GetOrigin();
	ImageType::RegionType region = ref->GetLargestPossibleRegion();
	region.SetSize(2,slices);


	// create the outputs
	outputImage->SetSpacing(spacing);
	outputImage->SetDirection(direction);
	outputImage->SetOrigin(origin);
	outputImage->SetRegions(region);
	outputImage->Allocate();
	

	outputLabel->SetSpacing(spacing);
	outputLabel->SetDirection(direction);
	outputLabel->SetOrigin(origin);
	outputLabel->SetRegions(region);
	outputLabel->Allocate();

	itk::ImageRegionIterator<ImageType> outLIt(outputLabel, outputLabel->GetLargestPossibleRegion());
	itk::ImageRegionIterator<ImageType> outImIt(outputImage, outputImage->GetLargestPossibleRegion());



	// loop through the slices
	for(unsigned int i = 0; i < slices; i++)
	{
		ImageType::Pointer im = series[i].images[timestep];
		ImageType::Pointer label = series[i].labelImages[timestep];

		itk::ImageRegionConstIterator<ImageType> imIt(im, im->GetLargestPossibleRegion());
		itk::ImageRegionConstIterator<ImageType> lIt(label, label->GetLargestPossibleRegion());

		while(!imIt.IsAtEnd())
		{
			outLIt.Set(lIt.Get());
			outImIt.Set(imIt.Get());

			++imIt; ++lIt;
			++outLIt; ++outImIt;
		}
	}
}
Пример #5
0
// ------------------------------------------------------------------------
void createOutput(const ImageType::Pointer &input, ImageType::Pointer &output)
{
	output->SetDirection(input->GetDirection());
	output->SetSpacing(input->GetSpacing());
	output->SetRegions(input->GetLargestPossibleRegion());
	output->SetOrigin(input->GetOrigin());
	output->Allocate();
	output->FillBuffer(0);
}
Пример #6
0
// ------------------------------------------------------------------------
void buildShortAxisVolume(const SeriesTransform::Map &transforms, 
		const unsigned int seriesNumber, ImageType::Pointer &saVolume)
{
	// get the short axis transforms
	SeriesTransform::Map::const_iterator mapIt = transforms.begin();
	std::vector<SeriesTransform> saSlices;
	while(mapIt != transforms.end())
	{
		if(mapIt->second.series == seriesNumber)
		{
			unsigned int sliceNum = mapIt->second.slice;

			if(saSlices.size() < (sliceNum+1))
				saSlices.resize(sliceNum+1);

			saSlices[sliceNum] = mapIt->second;
		}
		
		++mapIt;
	}


	// get the dimensions of the output image
	ImageType::Pointer reference = saSlices[0].images[0];
	unsigned int x,y,z;
	x = reference->GetLargestPossibleRegion().GetSize()[0];
	y = reference->GetLargestPossibleRegion().GetSize()[1];
	z = saSlices.size();

	ImageType::RegionType region;
	ImageType::SizeType size;
	ImageType::IndexType index;
	size[0] = x;
	size[1] = y;
	size[2] = z;

	index.Fill(0);

	region.SetSize(size);
	region.SetIndex(index);
	
	// get the other parts
	ImageType::SpacingType spacing = reference->GetSpacing();
	spacing[2] = saSlices[0].sliceThickness;
	ImageType::DirectionType direction = reference->GetDirection();
	ImageType::PointType origin = reference->GetOrigin();


	saVolume->SetOrigin(origin);
	saVolume->SetDirection(direction);
	saVolume->SetSpacing(spacing);
	saVolume->SetRegions(region);
	saVolume->Allocate();
	saVolume->FillBuffer(0);
	
}
Пример #7
0
// ------------------------------------------------------------------------
void DicomParser::writeSeries(const DicomSeries &series, const QString &outputFolder)
{
	// create the series name
	QString name = QString::fromStdString(series.description);
	name.replace(" ","_");
	name += "_" + QString::number(series.images.front().seriesNumber);
	name += ".nrrd";
	
	QDir path(outputFolder);
	QString fullPath = path.absoluteFilePath(name);
	

	std::vector<DicomImage> images = series.images;
	std::sort(images.begin(), images.end());

	// write and build the output images 
	typedef itk::Image<unsigned short, 3> ImageType;
	typedef itk::Image<unsigned short, 4> OutputImageType;
	typedef itk::ImageFileReader<ImageType> ReaderType;
	typedef itk::JoinSeriesImageFilter<ImageType, OutputImageType> JoinerType;

	JoinerType::Pointer joiner = JoinerType::New();
	ImageType::Pointer orig;
	for(unsigned int i = 0; i < images.size(); i++)
	{
		ReaderType::Pointer reader = ReaderType::New();
		reader->SetFileName(images[i].filename);
		std::cout << images[i].filename << std::endl;
		reader->SetImageIO(itk::GDCMImageIO::New());
		reader->Update();

		ImageType::Pointer im = reader->GetOutput();
		if(i == 0) orig = im;


		im->SetOrigin(orig->GetOrigin());
		im->SetDirection(orig->GetDirection());
		im->SetSpacing(orig->GetSpacing());

		joiner->SetInput(i, reader->GetOutput());
	}


	std::cout << joiner->GetOutput()->GetDirection() << std::endl;


	typedef itk::ImageFileWriter<OutputImageType> WriterType;
	WriterType::Pointer writer = WriterType::New();
	writer->SetInput(joiner->GetOutput());
	writer->SetFileName(fullPath.toStdString());
	writer->SetImageIO(itk::NrrdImageIO::New());
	writer->Update();

}
Пример #8
0
// ------------------------------------------------------------------------
void computeTransform(const ImageType::Pointer &image, vnl_matrix<double> &transform)
{
	vnl_matrix<double> dirMat = image->GetDirection().GetVnlMatrix();
	transform.set_size(4,4);

	for(unsigned int i = 0; i < 3; i++)
	{
		for(unsigned int j = 0; j < 3; j++)
		{
			transform(i,j) = dirMat(i,j);
		}
	}


}
// ------------------------------------------------------------------------
void InitialTransformExtractor::Compute()
{
    GetFilenames(m_Filenames);
    BuildMapping(m_Mapping);
    std::string referenceFilename = GetReferenceImageFilename();


    // load the reference file
    typedef itk::ImageFileReader<ImageType> ReaderType;
    ReaderType::Pointer reader = ReaderType::New();
    reader->SetFileName(referenceFilename);
    reader->SetImageIO(itk::GDCMImageIO::New());
    reader->Update();
    ImageType::Pointer refImage = reader->GetOutput();


    // flip the x and y axis
    typedef itk::PermuteAxesImageFilter<ImageType> FlipperType;
    FlipperType::Pointer flipper = FlipperType::New();
    itk::FixedArray<unsigned int, 3> order;
    order[0] = 1;
    order[1] = 0;
    order[2] = 2;

    flipper->SetOrder(order);
    flipper->SetInput(refImage);
    flipper->Update();

    //refImage = flipper->GetOutput();

    // transformation is the negative origin of the reference
    ImageType::PointType origin = refImage->GetOrigin();
    m_Translation[0] = -origin[0];
    m_Translation[1] = -origin[1];
    m_Translation[2] = -origin[2];

    m_Rotation = refImage->GetDirection().GetInverse();
    m_Reference = refImage;
}
Пример #10
0
  void NrrdQBallImageReader
    ::GenerateData()
  {
    if ( m_FileName == "")
    {
      throw itk::ImageFileReaderException(__FILE__, __LINE__, "Sorry, the filename of the vessel tree to be read is empty!");
    }
    else
    {
      try
      {
        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;
          }
        }

        typedef itk::VectorImage<float,3> ImageType;
        itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();
        typedef itk::ImageFileReader<ImageType> FileReaderType;
        FileReaderType::Pointer reader = FileReaderType::New();
        reader->SetImageIO(io);
        reader->SetFileName(this->m_FileName);
        reader->Update();
        ImageType::Pointer img = reader->GetOutput();

        typedef itk::Image<itk::Vector<float,QBALL_ODFSIZE>,3> VecImgType;
        VecImgType::Pointer vecImg = VecImgType::New();
        vecImg->SetSpacing( img->GetSpacing() );   // Set the image spacing
        vecImg->SetOrigin( img->GetOrigin() );     // Set the image origin
        vecImg->SetDirection( img->GetDirection() );  // Set the image direction
        vecImg->SetLargestPossibleRegion( img->GetLargestPossibleRegion());
        vecImg->SetBufferedRegion( img->GetLargestPossibleRegion() );
        vecImg->Allocate();

        itk::ImageRegionIterator<VecImgType> ot (vecImg, vecImg->GetLargestPossibleRegion() );
        ot = ot.Begin();

        itk::ImageRegionIterator<ImageType> it (img, img->GetLargestPossibleRegion() );

        typedef ImageType::PixelType  VarPixType;
        typedef VecImgType::PixelType FixPixType;

        for (it = it.Begin(); !it.IsAtEnd(); ++it)
        {
          VarPixType vec = it.Get();
          FixPixType fixVec(vec.GetDataPointer());
          ot.Set(fixVec);
          ++ot;
        }

        this->GetOutput()->InitializeByItk(vecImg.GetPointer());
        this->GetOutput()->SetVolume(vecImg->GetBufferPointer());

        try
        {
          setlocale(LC_ALL, currLocale.c_str());
        }
        catch(...)
        {
          MITK_INFO << "Could not reset locale " << currLocale;
        }
      }
      catch(std::exception& e)
      {
        throw itk::ImageFileReaderException(__FILE__, __LINE__, e.what());
      }
      catch(...)
      {
        throw itk::ImageFileReaderException(__FILE__, __LINE__, "Sorry, an error occurred while reading the requested vessel tree file!");
      }
    }
  }
Пример #11
0
// ------------------------------------------------------------------------
void NormaliseImage(const ImageType::Pointer &input, 
		const ImageType::Pointer &reference,	
		ImageType::Pointer &output,
		SeriesTransform &trans)
{
	// flip the x and y axis 
	typedef itk::PermuteAxesImageFilter<ImageType> FlipperType;
	FlipperType::Pointer flipper = FlipperType::New();
	itk::FixedArray<unsigned int, 3> order;
	order[0] = 1;
	order[1] = 0;
	order[2] = 2;

	flipper->SetOrder(order);
	flipper->SetInput(input);
	flipper->Update();

	output = flipper->GetOutput();

	// get the reference offset
	vnl_vector<double> refOrigin(3);
	refOrigin[0] = reference->GetOrigin()[0];// + trans.translation[0];
	refOrigin[1] = reference->GetOrigin()[1];// + trans.translation[1];
	refOrigin[2] = reference->GetOrigin()[2];// + trans.translation[2];

	vnl_matrix<double> refRot = reference->GetDirection().GetVnlMatrix();
	vnl_matrix<double> refRotInv = vnl_inverse(refRot);
	vnl_vector<double> refOffset = refRotInv * refOrigin;

	// get the image origin
	vnl_vector<double> origin(3);
	origin[0] = output->GetOrigin()[0];
	origin[1] = output->GetOrigin()[1];
	origin[2] = output->GetOrigin()[2];
	
	// apply the rotation to the origin
	origin = refRotInv * origin;

	// apply the offset to the origin
	origin = origin - refOffset;

	// apply the scaling 
	origin /= reference->GetSpacing()[0];

	// put the values into the output image
	ImageType::PointType itkOrigin;
	itkOrigin[0] = origin[0];
	itkOrigin[1] = origin[1];
	itkOrigin[2] = origin[2];

	ImageType::SpacingType spacing;
	spacing.Fill(output->GetSpacing()[0] / reference->GetSpacing()[0]);

	// get the new direction
	ImageType::DirectionType dirOut = output->GetDirection();
	dirOut = reference->GetDirection().GetInverse() * dirOut.GetVnlMatrix();
	
	output->SetSpacing(spacing);
	output->SetDirection(dirOut);
	output->SetOrigin(itkOrigin);
}
Пример #12
0
  std::vector<itk::SmartPointer<BaseData> > NrrdTensorImageReader::Read()
  {
    std::vector<itk::SmartPointer<mitk::BaseData> > result;
    std::string location = GetInputLocation();

    if ( location == "")
    {
      throw itk::ImageFileReaderException(__FILE__, __LINE__, "Sorry, the filename is empty!");
    }
    else
    {
      try
      {
        mitk::LocaleSwitch localeSwitch("C");

        try
        {
          std::string fname3 = mitk::IOUtil::GetTempPath()+"/temp_dti.nii.gz";

          int c = 0;
          while( itksys::SystemTools::FileExists(fname3) )
          {
            fname3 = mitk::IOUtil::GetTempPath()+"/temp_dti_" + boost::lexical_cast<std::string>(c) + ".nii.gz";
            ++c;
          }

          itksys::SystemTools::CopyAFile(location.c_str(), fname3.c_str());

          typedef itk::VectorImage<float,3> ImageType;
          itk::NiftiImageIO::Pointer io = itk::NiftiImageIO::New();
          typedef itk::ImageFileReader<ImageType> FileReaderType;
          FileReaderType::Pointer reader = FileReaderType::New();
          reader->SetImageIO(io);
          reader->SetFileName(fname3);
          reader->Update();
          ImageType::Pointer img = reader->GetOutput();

          TensorImage::ItkTensorImageType::Pointer vecImg = TensorImage::ItkTensorImageType::New();
          vecImg->SetSpacing( img->GetSpacing() );   // Set the image spacing
          vecImg->SetOrigin( img->GetOrigin() );     // Set the image origin
          vecImg->SetDirection( img->GetDirection() );  // Set the image direction
          vecImg->SetRegions( img->GetLargestPossibleRegion());
          vecImg->Allocate();

          itk::ImageRegionIterator<TensorImage::ItkTensorImageType> ot (vecImg, vecImg->GetLargestPossibleRegion() );
          ot.GoToBegin();

          itk::ImageRegionIterator<ImageType> it (img, img->GetLargestPossibleRegion() );
          it.GoToBegin();

          typedef ImageType::PixelType  VarPixType;
          typedef TensorImage::PixelType FixPixType;
          int numComponents = img->GetNumberOfComponentsPerPixel();

          if (numComponents==6)
          {
            MITK_INFO << "Trying to load dti as 6-comp nifti ...";
            while (!it.IsAtEnd())
            {
              VarPixType vec = it.Get();
              FixPixType fixVec(vec.GetDataPointer());

              TensorImage::PixelType tensor;
              tensor.SetElement(0, vec.GetElement(0));
              tensor.SetElement(1, vec.GetElement(1));
              tensor.SetElement(2, vec.GetElement(2));
              tensor.SetElement(3, vec.GetElement(3));
              tensor.SetElement(4, vec.GetElement(4));
              tensor.SetElement(5, vec.GetElement(5));

              fixVec = tensor;

              ot.Set(fixVec);
              ++ot;
              ++it;
            }
          }
          else if(numComponents==9)
          {
            MITK_INFO << "Trying to load dti as 9-comp nifti ...";
            while (!it.IsAtEnd())
            {
              VarPixType vec = it.Get();
              TensorImage::PixelType tensor;
              tensor.SetElement(0, vec.GetElement(0));
              tensor.SetElement(1, vec.GetElement(1));
              tensor.SetElement(2, vec.GetElement(2));
              tensor.SetElement(3, vec.GetElement(4));
              tensor.SetElement(4, vec.GetElement(5));
              tensor.SetElement(5, vec.GetElement(8));

              FixPixType fixVec(tensor);
              ot.Set(fixVec);
              ++ot;
              ++it;
            }
          }
          else if (numComponents==1)
          {
            MITK_INFO << "Trying to load dti as 4D nifti ...";
            typedef itk::Image<float,4> ImageType;
            typedef itk::ImageFileReader<ImageType> FileReaderType;
            FileReaderType::Pointer reader = FileReaderType::New();
            reader->SetImageIO(io);
            reader->SetFileName(fname3);
            reader->Update();
            ImageType::Pointer img = reader->GetOutput();

            itk::Size<4> size = img->GetLargestPossibleRegion().GetSize();

            while (!ot.IsAtEnd())
            {
              TensorImage::PixelType tensor;
              ImageType::IndexType idx;
              idx[0] = ot.GetIndex()[0]; idx[1] = ot.GetIndex()[1]; idx[2] = ot.GetIndex()[2];

              if (size[3]==6)
              {
                for (unsigned int te=0; te<size[3]; te++)
                {
                  idx[3] = te;
                  tensor.SetElement(te, img->GetPixel(idx));
                }
              }
              else if (size[3]==9)
              {
                idx[3] = 0;
                tensor.SetElement(0, img->GetPixel(idx));
                idx[3] = 1;
                tensor.SetElement(1, img->GetPixel(idx));
                idx[3] = 2;
                tensor.SetElement(2, img->GetPixel(idx));
                idx[3] = 4;
                tensor.SetElement(3, img->GetPixel(idx));
                idx[3] = 5;
                tensor.SetElement(4, img->GetPixel(idx));
                idx[3] = 8;
                tensor.SetElement(5, img->GetPixel(idx));
              }
              else
                throw itk::ImageFileReaderException(__FILE__, __LINE__, "Unknown number of components for DTI file. Should be 6 or 9!");

              FixPixType fixVec(tensor);
              ot.Set(fixVec);
              ++ot;
            }
          }
          OutputType::Pointer resultImage = OutputType::New();
          resultImage->InitializeByItk( vecImg.GetPointer() );
          resultImage->SetVolume( vecImg->GetBufferPointer() );
          result.push_back( resultImage.GetPointer() );
        }
        catch(...)
        {
          MITK_INFO << "Trying to load dti as nrrd ...";

          typedef itk::VectorImage<float,3> ImageType;
          itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();
          typedef itk::ImageFileReader<ImageType> FileReaderType;
          FileReaderType::Pointer reader = FileReaderType::New();
          reader->SetImageIO(io);
          reader->SetFileName(location);
          reader->Update();
          ImageType::Pointer img = reader->GetOutput();

          TensorImage::ItkTensorImageType::Pointer vecImg = TensorImage::ItkTensorImageType::New();
          vecImg->SetSpacing( img->GetSpacing() );   // Set the image spacing
          vecImg->SetOrigin( img->GetOrigin() );     // Set the image origin
          vecImg->SetDirection( img->GetDirection() );  // Set the image direction
          vecImg->SetRegions( img->GetLargestPossibleRegion());
          vecImg->Allocate();

          itk::ImageRegionIterator<TensorImage::ItkTensorImageType> ot (vecImg, vecImg->GetLargestPossibleRegion() );
          ot.GoToBegin();

          itk::ImageRegionIterator<ImageType> it (img, img->GetLargestPossibleRegion() );
          it.GoToBegin();

          typedef ImageType::PixelType  VarPixType;
          typedef TensorImage::PixelType FixPixType;
          int numComponents = img->GetNumberOfComponentsPerPixel();

          itk::MetaDataDictionary imgMetaDictionary = img->GetMetaDataDictionary();
          std::vector<std::string> imgMetaKeys = imgMetaDictionary.GetKeys();
          std::vector<std::string>::const_iterator itKey = imgMetaKeys.begin();
          std::string metaString;

          bool readFrame = false;
          double xx, xy, xz, yx, yy, yz, zx, zy, zz;
          MeasurementFrameType measFrame;
          measFrame.SetIdentity();
          MeasurementFrameType measFrameTransp;
          measFrameTransp.SetIdentity();

          for (; itKey != imgMetaKeys.end(); itKey ++)
          {
            itk::ExposeMetaData<std::string> (imgMetaDictionary, *itKey, metaString);
            if (itKey->find("measurement frame") != std::string::npos)
            {
              sscanf(metaString.c_str(), " ( %lf , %lf , %lf ) ( %lf , %lf , %lf ) ( %lf , %lf , %lf ) \n", &xx, &xy, &xz, &yx, &yy, &yz, &zx, &zy, &zz);

              if (xx>10e-10 || xy>10e-10 || xz>10e-10 ||
                yx>10e-10 || yy>10e-10 || yz>10e-10 ||
                zx>10e-10 || zy>10e-10 || zz>10e-10 )
              {
                readFrame = true;

                measFrame(0,0) = xx;
                measFrame(0,1) = xy;
                measFrame(0,2) = xz;
                measFrame(1,0) = yx;
                measFrame(1,1) = yy;
                measFrame(1,2) = yz;
                measFrame(2,0) = zx;
                measFrame(2,1) = zy;
                measFrame(2,2) = zz;

                measFrameTransp = measFrame.GetTranspose();
              }
            }
          }

          if (numComponents==6)
          {
            while (!it.IsAtEnd())
            {
              // T'=RTR'
              VarPixType vec = it.Get();
              FixPixType fixVec(vec.GetDataPointer());

              if(readFrame)
              {
                TensorImage::PixelType tensor;
                tensor.SetElement(0, vec.GetElement(0));
                tensor.SetElement(1, vec.GetElement(1));
                tensor.SetElement(2, vec.GetElement(2));
                tensor.SetElement(3, vec.GetElement(3));
                tensor.SetElement(4, vec.GetElement(4));
                tensor.SetElement(5, vec.GetElement(5));

                tensor = ConvertMatrixTypeToFixedArrayType(tensor.PreMultiply(measFrame));
                tensor = ConvertMatrixTypeToFixedArrayType(tensor.PostMultiply(measFrameTransp));
                fixVec = tensor;
              }

              ot.Set(fixVec);
              ++ot;
              ++it;
            }
          }
          else if(numComponents==9)
          {
            while (!it.IsAtEnd())
            {
              VarPixType vec = it.Get();
              TensorImage::PixelType tensor;
              tensor.SetElement(0, vec.GetElement(0));
              tensor.SetElement(1, vec.GetElement(1));
              tensor.SetElement(2, vec.GetElement(2));
              tensor.SetElement(3, vec.GetElement(4));
              tensor.SetElement(4, vec.GetElement(5));
              tensor.SetElement(5, vec.GetElement(8));

              if(readFrame)
              {
                tensor = ConvertMatrixTypeToFixedArrayType(tensor.PreMultiply(measFrame));
                tensor = ConvertMatrixTypeToFixedArrayType(tensor.PostMultiply(measFrameTransp));
              }

              FixPixType fixVec(tensor);
              ot.Set(fixVec);
              ++ot;
              ++it;
            }
          }
          else if (numComponents==1)
          {
            typedef itk::Image<float,4> ImageType;
            itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();
            typedef itk::ImageFileReader<ImageType> FileReaderType;
            FileReaderType::Pointer reader = FileReaderType::New();
            reader->SetImageIO(io);
            reader->SetFileName(location);
            reader->Update();
            ImageType::Pointer img = reader->GetOutput();

            itk::Size<4> size = img->GetLargestPossibleRegion().GetSize();

            while (!ot.IsAtEnd())
            {
              TensorImage::PixelType tensor;
              ImageType::IndexType idx;
              idx[0] = ot.GetIndex()[0]; idx[1] = ot.GetIndex()[1]; idx[2] = ot.GetIndex()[2];

              if (size[3]==6)
              {
                for (unsigned int te=0; te<size[3]; te++)
                {
                  idx[3] = te;
                  tensor.SetElement(te, img->GetPixel(idx));
                }
              }
              else if (size[3]==9)
              {
                idx[3] = 0;
                tensor.SetElement(0, img->GetPixel(idx));
                idx[3] = 1;
                tensor.SetElement(1, img->GetPixel(idx));
                idx[3] = 2;
                tensor.SetElement(2, img->GetPixel(idx));
                idx[3] = 4;
                tensor.SetElement(3, img->GetPixel(idx));
                idx[3] = 5;
                tensor.SetElement(4, img->GetPixel(idx));
                idx[3] = 8;
                tensor.SetElement(5, img->GetPixel(idx));
              }
              else
                throw itk::ImageFileReaderException(__FILE__, __LINE__, "Unknown number of komponents for DTI file. Should be 6 or 9!");

              if(readFrame)
              {
                tensor = ConvertMatrixTypeToFixedArrayType(tensor.PreMultiply(measFrame));
                tensor = ConvertMatrixTypeToFixedArrayType(tensor.PostMultiply(measFrameTransp));
              }
              FixPixType fixVec(tensor);
              ot.Set(fixVec);
              ++ot;
            }
          }
          else
          {
            throw itk::ImageFileReaderException(__FILE__, __LINE__, "Image has wrong number of pixel components!");
          }

          OutputType::Pointer resultImage = OutputType::New();
          resultImage->InitializeByItk( vecImg.GetPointer() );
          resultImage->SetVolume( vecImg->GetBufferPointer() );
          result.push_back( resultImage.GetPointer() );
        }

      }
      catch(std::exception& e)
      {
        throw itk::ImageFileReaderException(__FILE__, __LINE__, e.what());
      }
      catch(...)
      {
        throw itk::ImageFileReaderException(__FILE__, __LINE__, "Sorry, an error occurred while reading the requested DTI file!");
      }
    }

    return result;
  }
Пример #13
0
  void NrrdTensorImageReader
    ::GenerateData()
  {
    if ( m_FileName == "")
    {
      throw itk::ImageFileReaderException(__FILE__, __LINE__, "Sorry, the filename is empty!");
    }
    else
    {
      try
      {
        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;
          }
        }

        typedef itk::VectorImage<float,3> ImageType;
        itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();
        typedef itk::ImageFileReader<ImageType> FileReaderType;
        FileReaderType::Pointer reader = FileReaderType::New();
        reader->SetImageIO(io);
        reader->SetFileName(this->m_FileName);
        reader->Update();
        ImageType::Pointer img = reader->GetOutput();

        typedef itk::Image<itk::DiffusionTensor3D<float>,3> VecImgType;
        VecImgType::Pointer vecImg = VecImgType::New();
        vecImg->SetSpacing( img->GetSpacing() );   // Set the image spacing
        vecImg->SetOrigin( img->GetOrigin() );     // Set the image origin
        vecImg->SetDirection( img->GetDirection() );  // Set the image direction
        vecImg->SetRegions( img->GetLargestPossibleRegion());
        vecImg->Allocate();

        itk::ImageRegionIterator<VecImgType> ot (vecImg, vecImg->GetLargestPossibleRegion() );
        ot = ot.Begin();

        itk::ImageRegionIterator<ImageType> it (img, img->GetLargestPossibleRegion() );
        it = it.Begin();

        typedef ImageType::PixelType  VarPixType;
        typedef VecImgType::PixelType FixPixType;
        int numComponents = img->GetNumberOfComponentsPerPixel();

        itk::MetaDataDictionary imgMetaDictionary = img->GetMetaDataDictionary();
        std::vector<std::string> imgMetaKeys = imgMetaDictionary.GetKeys();
        std::vector<std::string>::const_iterator itKey = imgMetaKeys.begin();
        std::string metaString;

        bool readFrame = false;
        double xx, xy, xz, yx, yy, yz, zx, zy, zz;
        MeasurementFrameType measFrame;
        measFrame.SetIdentity();
        MeasurementFrameType measFrameTransp;
        measFrameTransp.SetIdentity();

        for (; itKey != imgMetaKeys.end(); itKey ++)
        {
          itk::ExposeMetaData<std::string> (imgMetaDictionary, *itKey, metaString);
          if (itKey->find("measurement frame") != std::string::npos)
          {
            sscanf(metaString.c_str(), " ( %lf , %lf , %lf ) ( %lf , %lf , %lf ) ( %lf , %lf , %lf ) \n", &xx, &xy, &xz, &yx, &yy, &yz, &zx, &zy, &zz);

            if (xx>10e-10 || xy>10e-10 || xz>10e-10 ||
                yx>10e-10 || yy>10e-10 || yz>10e-10 ||
                zx>10e-10 || zy>10e-10 || zz>10e-10 )
            {
              readFrame = true;

              measFrame(0,0) = xx;
              measFrame(0,1) = xy;
              measFrame(0,2) = xz;
              measFrame(1,0) = yx;
              measFrame(1,1) = yy;
              measFrame(1,2) = yz;
              measFrame(2,0) = zx;
              measFrame(2,1) = zy;
              measFrame(2,2) = zz;

              measFrameTransp = measFrame.GetTranspose();
            }
          }
        }

        if (numComponents==6)
        {
          while (!it.IsAtEnd())
          {
            // T'=RTR'
            VarPixType vec = it.Get();
            FixPixType fixVec(vec.GetDataPointer());

            if(readFrame)
            {
              itk::DiffusionTensor3D<float> tensor;
              tensor.SetElement(0, vec.GetElement(0));
              tensor.SetElement(1, vec.GetElement(1));
              tensor.SetElement(2, vec.GetElement(2));
              tensor.SetElement(3, vec.GetElement(3));
              tensor.SetElement(4, vec.GetElement(4));
              tensor.SetElement(5, vec.GetElement(5));

              tensor = tensor.PreMultiply(measFrame);
              tensor = tensor.PostMultiply(measFrameTransp);
              fixVec = tensor;
            }

            ot.Set(fixVec);
            ++ot;
            ++it;
          }
        }
        else if(numComponents==9)
        {
          while (!it.IsAtEnd())
          {
            VarPixType vec = it.Get();
            itk::DiffusionTensor3D<float> tensor;
            tensor.SetElement(0, vec.GetElement(0));
            tensor.SetElement(1, vec.GetElement(1));
            tensor.SetElement(2, vec.GetElement(2));
            tensor.SetElement(3, vec.GetElement(4));
            tensor.SetElement(4, vec.GetElement(5));
            tensor.SetElement(5, vec.GetElement(8));

            if(readFrame)
            {
              tensor = tensor.PreMultiply(measFrame);
              tensor = tensor.PostMultiply(measFrameTransp);
            }

            FixPixType fixVec(tensor);
            ot.Set(fixVec);
            ++ot;
            ++it;
          }
        }
        else
        {
          throw itk::ImageFileReaderException(__FILE__, __LINE__, "Image has wrong number of pixel components!");
        }

        this->GetOutput()->InitializeByItk(vecImg.GetPointer());
        this->GetOutput()->SetVolume(vecImg->GetBufferPointer());

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

      }
      catch(std::exception& e)
      {
        throw itk::ImageFileReaderException(__FILE__, __LINE__, e.what());
      }
      catch(...)
      {
        throw itk::ImageFileReaderException(__FILE__, __LINE__, "Sorry, an error occurred while reading the requested DTI file!");
      }
    }
  }
void QmitkBasicImageProcessing::StartButtonClicked()
{
  if(!m_SelectedImageNode->GetNode()) return;

  this->BusyCursorOn();

  mitk::Image::Pointer newImage;

  try
  {
    newImage = dynamic_cast<mitk::Image*>(m_SelectedImageNode->GetNode()->GetData());
  }
  catch ( std::exception &e )
  {
  QString exceptionString = "An error occured during image loading:\n";
  exceptionString.append( e.what() );
    QMessageBox::warning( NULL, "Basic Image Processing", exceptionString , QMessageBox::Ok, QMessageBox::NoButton );
    this->BusyCursorOff();
    return;
  }

  // check if input image is valid, casting does not throw exception when casting from 'NULL-Object'
  if ( (! newImage) || (newImage->IsInitialized() == false) )
  {
    this->BusyCursorOff();

    QMessageBox::warning( NULL, "Basic Image Processing", "Input image is broken or not initialized. Returning.", QMessageBox::Ok, QMessageBox::NoButton );
    return;
  }

  // check if operation is done on 4D a image time step
  if(newImage->GetDimension() > 3)
  {
    mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New();
    timeSelector->SetInput(newImage);
    timeSelector->SetTimeNr( ((QmitkSliderNavigatorWidget*)m_Controls->sliceNavigatorTime)->GetPos() );
    timeSelector->Update();
    newImage = timeSelector->GetOutput();
  }



  // check if image or vector image
  ImageType::Pointer itkImage = ImageType::New();
  VectorImageType::Pointer itkVecImage = VectorImageType::New();

  int isVectorImage = newImage->GetPixelType().GetNumberOfComponents();

  if(isVectorImage > 1)
  {
    CastToItkImage( newImage, itkVecImage );
  }
  else
  {
    CastToItkImage( newImage, itkImage );
  }

  std::stringstream nameAddition("");

  int param1 = m_Controls->sbParam1->value();
  int param2 = m_Controls->sbParam2->value();
  double dparam1 = m_Controls->dsbParam1->value();
  double dparam2 = m_Controls->dsbParam2->value();
  double dparam3 = m_Controls->dsbParam3->value();

  try{

  switch (m_SelectedAction)
  {

  case GAUSSIAN:
    {
      GaussianFilterType::Pointer gaussianFilter = GaussianFilterType::New();
      gaussianFilter->SetInput( itkImage );
      gaussianFilter->SetVariance( param1 );
      gaussianFilter->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(gaussianFilter->GetOutput())->Clone();
      nameAddition << "_Gaussian_var_" << param1;
      std::cout << "Gaussian filtering successful." << std::endl;
      break;
    }

  case MEDIAN:
    {
      MedianFilterType::Pointer medianFilter = MedianFilterType::New();
      MedianFilterType::InputSizeType size;
      size.Fill(param1);
      medianFilter->SetRadius( size );
      medianFilter->SetInput(itkImage);
      medianFilter->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(medianFilter->GetOutput())->Clone();
      nameAddition << "_Median_radius_" << param1;
      std::cout << "Median Filtering successful." << std::endl;
      break;
    }

  case TOTALVARIATION:
    {
      if(isVectorImage > 1)
      {
        VectorTotalVariationFilterType::Pointer TVFilter
          = VectorTotalVariationFilterType::New();
        TVFilter->SetInput( itkVecImage.GetPointer() );
        TVFilter->SetNumberIterations(param1);
        TVFilter->SetLambda(double(param2)/1000.);
        TVFilter->UpdateLargestPossibleRegion();

        newImage = mitk::ImportItkImage(TVFilter->GetOutput())->Clone();
      }
      else
      {
        ImagePTypeToFloatPTypeCasterType::Pointer floatCaster = ImagePTypeToFloatPTypeCasterType::New();
        floatCaster->SetInput( itkImage );
        floatCaster->Update();
        FloatImageType::Pointer fImage = floatCaster->GetOutput();

        TotalVariationFilterType::Pointer TVFilter
          = TotalVariationFilterType::New();
        TVFilter->SetInput( fImage.GetPointer() );
        TVFilter->SetNumberIterations(param1);
        TVFilter->SetLambda(double(param2)/1000.);
        TVFilter->UpdateLargestPossibleRegion();

        newImage = mitk::ImportItkImage(TVFilter->GetOutput())->Clone();
      }

      nameAddition << "_TV_Iter_" << param1 << "_L_" << param2;
      std::cout << "Total Variation Filtering successful." << std::endl;
      break;
    }

  case DILATION:
    {
      BallType binaryBall;
      binaryBall.SetRadius( param1 );
      binaryBall.CreateStructuringElement();

      DilationFilterType::Pointer dilationFilter = DilationFilterType::New();
      dilationFilter->SetInput( itkImage );
      dilationFilter->SetKernel( binaryBall );
      dilationFilter->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(dilationFilter->GetOutput())->Clone();
      nameAddition << "_Dilated_by_" << param1;
      std::cout << "Dilation successful." << std::endl;
      break;
    }

  case EROSION:
    {
      BallType binaryBall;
      binaryBall.SetRadius( param1 );
      binaryBall.CreateStructuringElement();

      ErosionFilterType::Pointer erosionFilter = ErosionFilterType::New();
      erosionFilter->SetInput( itkImage );
      erosionFilter->SetKernel( binaryBall );
      erosionFilter->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(erosionFilter->GetOutput())->Clone();
      nameAddition << "_Eroded_by_" << param1;
      std::cout << "Erosion successful." << std::endl;
      break;
    }

  case OPENING:
    {
      BallType binaryBall;
      binaryBall.SetRadius( param1 );
      binaryBall.CreateStructuringElement();

      OpeningFilterType::Pointer openFilter = OpeningFilterType::New();
      openFilter->SetInput( itkImage );
      openFilter->SetKernel( binaryBall );
      openFilter->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(openFilter->GetOutput())->Clone();
      nameAddition << "_Opened_by_" << param1;
      std::cout << "Opening successful." << std::endl;
      break;
    }

  case CLOSING:
    {
      BallType binaryBall;
      binaryBall.SetRadius( param1 );
      binaryBall.CreateStructuringElement();

      ClosingFilterType::Pointer closeFilter = ClosingFilterType::New();
      closeFilter->SetInput( itkImage );
      closeFilter->SetKernel( binaryBall );
      closeFilter->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(closeFilter->GetOutput())->Clone();
      nameAddition << "_Closed_by_" << param1;
      std::cout << "Closing successful." << std::endl;
      break;
    }

  case GRADIENT:
    {
      GradientFilterType::Pointer gradientFilter = GradientFilterType::New();
      gradientFilter->SetInput( itkImage );
      gradientFilter->SetSigma( param1 );
      gradientFilter->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(gradientFilter->GetOutput())->Clone();
      nameAddition << "_Gradient_sigma_" << param1;
      std::cout << "Gradient calculation successful." << std::endl;
      break;
    }

  case LAPLACIAN:
    {
      // the laplace filter requires a float type image as input, we need to cast the itkImage
      // to correct type
      ImagePTypeToFloatPTypeCasterType::Pointer caster = ImagePTypeToFloatPTypeCasterType::New();
      caster->SetInput( itkImage );
      caster->Update();
      FloatImageType::Pointer fImage = caster->GetOutput();

      LaplacianFilterType::Pointer laplacianFilter = LaplacianFilterType::New();
      laplacianFilter->SetInput( fImage );
      laplacianFilter->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(laplacianFilter->GetOutput())->Clone();
      nameAddition << "_Second_Derivative";
      std::cout << "Laplacian filtering successful." << std::endl;
      break;
    }

  case SOBEL:
    {
      // the sobel filter requires a float type image as input, we need to cast the itkImage
      // to correct type
      ImagePTypeToFloatPTypeCasterType::Pointer caster = ImagePTypeToFloatPTypeCasterType::New();
      caster->SetInput( itkImage );
      caster->Update();
      FloatImageType::Pointer fImage = caster->GetOutput();

      SobelFilterType::Pointer sobelFilter = SobelFilterType::New();
      sobelFilter->SetInput( fImage );
      sobelFilter->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(sobelFilter->GetOutput())->Clone();
      nameAddition << "_Sobel";
      std::cout << "Edge Detection successful." << std::endl;
      break;
    }

  case THRESHOLD:
    {
      ThresholdFilterType::Pointer thFilter = ThresholdFilterType::New();
      thFilter->SetLowerThreshold(param1 < param2 ? param1 : param2);
      thFilter->SetUpperThreshold(param2 > param1 ? param2 : param1);
      thFilter->SetInsideValue(1);
      thFilter->SetOutsideValue(0);
      thFilter->SetInput(itkImage);
      thFilter->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(thFilter->GetOutput())->Clone();
      nameAddition << "_Threshold";
      std::cout << "Thresholding successful." << std::endl;
      break;
    }

  case INVERSION:
    {
      InversionFilterType::Pointer invFilter = InversionFilterType::New();
      mitk::ScalarType min = newImage->GetScalarValueMin();
      mitk::ScalarType max = newImage->GetScalarValueMax();
      invFilter->SetMaximum( max + min );
      invFilter->SetInput(itkImage);
      invFilter->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(invFilter->GetOutput())->Clone();
      nameAddition << "_Inverted";
      std::cout << "Image inversion successful." << std::endl;
      break;
    }

  case DOWNSAMPLING:
    {
      ResampleImageFilterType::Pointer downsampler = ResampleImageFilterType::New();
      downsampler->SetInput( itkImage );

      NearestInterpolatorType::Pointer interpolator = NearestInterpolatorType::New();
      downsampler->SetInterpolator( interpolator );

      downsampler->SetDefaultPixelValue( 0 );

      ResampleImageFilterType::SpacingType spacing = itkImage->GetSpacing();
      spacing *= (double) param1;
      downsampler->SetOutputSpacing( spacing );

      downsampler->SetOutputOrigin( itkImage->GetOrigin() );
      downsampler->SetOutputDirection( itkImage->GetDirection() );

      ResampleImageFilterType::SizeType size = itkImage->GetLargestPossibleRegion().GetSize();
      for ( int i = 0; i < 3; ++i )
      {
        size[i] /= param1;
      }
      downsampler->SetSize( size );
      downsampler->UpdateLargestPossibleRegion();

      newImage = mitk::ImportItkImage(downsampler->GetOutput())->Clone();
      nameAddition << "_Downsampled_by_" << param1;
      std::cout << "Downsampling successful." << std::endl;
      break;
    }

  case FLIPPING:
    {
      FlipImageFilterType::Pointer flipper = FlipImageFilterType::New();
      flipper->SetInput( itkImage );
      itk::FixedArray<bool, 3> flipAxes;
      for(int i=0; i<3; ++i)
      {
        if(i == param1)
        {
          flipAxes[i] = true;
        }
        else
        {
          flipAxes[i] = false;
        }
      }
      flipper->SetFlipAxes(flipAxes);
      flipper->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(flipper->GetOutput())->Clone();
      std::cout << "Image flipping successful." << std::endl;
      break;
    }

  case RESAMPLING:
    {
      std::string selectedInterpolator;
      ResampleImageFilterType::Pointer resampler = ResampleImageFilterType::New();
      switch (m_SelectedInterpolation)
      {
      case LINEAR:
        {
          LinearInterpolatorType::Pointer interpolator = LinearInterpolatorType::New();
          resampler->SetInterpolator(interpolator);
          selectedInterpolator = "Linear";
          break;
        }
      case NEAREST:
        {
          NearestInterpolatorType::Pointer interpolator = NearestInterpolatorType::New();
          resampler->SetInterpolator(interpolator);
          selectedInterpolator = "Nearest";
          break;
        }
      default:
        {
          LinearInterpolatorType::Pointer interpolator = LinearInterpolatorType::New();
          resampler->SetInterpolator(interpolator);
          selectedInterpolator = "Linear";
          break;
        }
      }
      resampler->SetInput( itkImage );
      resampler->SetOutputOrigin( itkImage->GetOrigin() );

      ImageType::SizeType input_size = itkImage->GetLargestPossibleRegion().GetSize();
      ImageType::SpacingType input_spacing = itkImage->GetSpacing();

      ImageType::SizeType output_size;
      ImageType::SpacingType output_spacing;

      output_size[0] = input_size[0] * (input_spacing[0] / dparam1);
      output_size[1] = input_size[1] * (input_spacing[1] / dparam2);
      output_size[2] = input_size[2] * (input_spacing[2] / dparam3);
      output_spacing [0] = dparam1;
      output_spacing [1] = dparam2;
      output_spacing [2] = dparam3;

      resampler->SetSize( output_size );
      resampler->SetOutputSpacing( output_spacing );
      resampler->SetOutputDirection( itkImage->GetDirection() );

      resampler->UpdateLargestPossibleRegion();

      ImageType::Pointer resampledImage = resampler->GetOutput();

      newImage = mitk::ImportItkImage( resampledImage );
      nameAddition << "_Resampled_" << selectedInterpolator;
      std::cout << "Resampling successful." << std::endl;
      break;
    }


  case RESCALE:
    {
      FloatImageType::Pointer floatImage = FloatImageType::New();
      CastToItkImage( newImage, floatImage );
      itk::RescaleIntensityImageFilter<FloatImageType,FloatImageType>::Pointer filter = itk::RescaleIntensityImageFilter<FloatImageType,FloatImageType>::New();
      filter->SetInput(0, floatImage);
      filter->SetOutputMinimum(dparam1);
      filter->SetOutputMaximum(dparam2);
      filter->Update();
      floatImage = filter->GetOutput();

      newImage = mitk::Image::New();
      newImage->InitializeByItk(floatImage.GetPointer());
      newImage->SetVolume(floatImage->GetBufferPointer());
      nameAddition << "_Rescaled";
      std::cout << "Rescaling successful." << std::endl;

      break;
    }

  default:
    this->BusyCursorOff();
    return;
  }
  }
  catch (...)
  {
    this->BusyCursorOff();
    QMessageBox::warning(NULL, "Warning", "Problem when applying filter operation. Check your input...");
    return;
  }

  newImage->DisconnectPipeline();

  // adjust level/window to new image
  mitk::LevelWindow levelwindow;
  levelwindow.SetAuto( newImage );
  mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New();
  levWinProp->SetLevelWindow( levelwindow );

  // compose new image name
  std::string name = m_SelectedImageNode->GetNode()->GetName();
  if (name.find(".pic.gz") == name.size() -7 )
  {
    name = name.substr(0,name.size() -7);
  }
  name.append( nameAddition.str() );

  // create final result MITK data storage node
  mitk::DataNode::Pointer result = mitk::DataNode::New();
  result->SetProperty( "levelwindow", levWinProp );
  result->SetProperty( "name", mitk::StringProperty::New( name.c_str() ) );
  result->SetData( newImage );

  // for vector images, a different mapper is needed
  if(isVectorImage > 1)
  {
    mitk::VectorImageMapper2D::Pointer mapper =
      mitk::VectorImageMapper2D::New();
    result->SetMapper(1,mapper);
  }

  // reset GUI to ease further processing
//  this->ResetOneImageOpPanel();

  // add new image to data storage and set as active to ease further processing
  GetDefaultDataStorage()->Add( result, m_SelectedImageNode->GetNode() );
  if ( m_Controls->cbHideOrig->isChecked() == true )
    m_SelectedImageNode->GetNode()->SetProperty( "visible", mitk::BoolProperty::New(false) );
  // TODO!! m_Controls->m_ImageSelector1->SetSelectedNode(result);

  // show the results
  mitk::RenderingManager::GetInstance()->RequestUpdateAll();
  this->BusyCursorOff();
}
Пример #15
0
void NrrdTensorImageReader
::GenerateData()
{
    if ( m_FileName == "")
    {
        throw itk::ImageFileReaderException(__FILE__, __LINE__, "Sorry, the filename is empty!");
    }
    else
    {
        try
        {
            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;
                }
            }

            try
            {
                MITK_INFO << "Trying to load dti as nifti ...";
                std::string fname3 = "temp_dti.nii";
                itksys::SystemTools::CopyAFile(m_FileName.c_str(), fname3.c_str());

                typedef itk::Image<float,4> ImageType;
                itk::NiftiImageIO::Pointer io = itk::NiftiImageIO::New();
                typedef itk::ImageFileReader<ImageType> FileReaderType;
                FileReaderType::Pointer reader = FileReaderType::New();
                reader->SetImageIO(io);
                reader->SetFileName(fname3);
                reader->Update();
                itksys::SystemTools::RemoveFile(fname3.c_str());

                ImageType::Pointer img = reader->GetOutput();
                itk::Size<4> size = img->GetLargestPossibleRegion().GetSize();

                itk::ImageRegion< 3 > region;
                region.SetSize(0,size[0]);
                region.SetSize(1,size[1]);
                region.SetSize(2,size[2]);
                itk::Vector<double,3> spacing;
                spacing[0] = img->GetSpacing()[0];
                spacing[1] = img->GetSpacing()[1];
                spacing[2] = img->GetSpacing()[2];
                itk::Point<double,3> origin;
                origin[0] = img->GetOrigin()[0];
                origin[1] = img->GetOrigin()[1];
                origin[2] = img->GetOrigin()[2];
                itk::Matrix<double,3,3> direction;
                direction[0][0] = img->GetDirection()[0][0];
                direction[1][0] = img->GetDirection()[1][0];
                direction[2][0] = img->GetDirection()[2][0];
                direction[0][1] = img->GetDirection()[0][1];
                direction[1][1] = img->GetDirection()[1][1];
                direction[2][1] = img->GetDirection()[2][1];
                direction[0][2] = img->GetDirection()[0][2];
                direction[1][2] = img->GetDirection()[1][2];
                direction[2][2] = img->GetDirection()[2][2];

                typedef itk::Image<itk::DiffusionTensor3D<float>,3> VecImgType;
                typedef VecImgType::PixelType FixPixType;
                VecImgType::Pointer vecImg = VecImgType::New();
                vecImg->SetSpacing( spacing );
                vecImg->SetOrigin( origin );
                vecImg->SetDirection( direction );
                vecImg->SetRegions( region );
                vecImg->Allocate();

                itk::ImageRegionIterator<VecImgType> ot (vecImg, vecImg->GetLargestPossibleRegion() );
                ot = ot.Begin();

                while (!ot.IsAtEnd())
                {
                    itk::DiffusionTensor3D<float> tensor;
                    ImageType::IndexType idx;
                    idx[0] = ot.GetIndex()[0]; idx[1] = ot.GetIndex()[1]; idx[2] = ot.GetIndex()[2];

                    if (size[3]==6)
                    {
                        for (int te=0; te<size[3]; te++)
                        {
                            idx[3] = te;
                            tensor.SetElement(te, img->GetPixel(idx));
                        }
                    }
                    else if (size[3]==9)
                    {
                        idx[3] = 0;
                        tensor.SetElement(0, img->GetPixel(idx));
                        idx[3] = 1;
                        tensor.SetElement(1, img->GetPixel(idx));
                        idx[3] = 2;
                        tensor.SetElement(2, img->GetPixel(idx));
                        idx[3] = 4;
                        tensor.SetElement(3, img->GetPixel(idx));
                        idx[3] = 5;
                        tensor.SetElement(4, img->GetPixel(idx));
                        idx[3] = 8;
                        tensor.SetElement(5, img->GetPixel(idx));
                    }
                    else
                        throw itk::ImageFileReaderException(__FILE__, __LINE__, "Unknown number of komponents for DTI file. Should be 6 or 9!");

                    FixPixType fixVec(tensor);
                    ot.Set(fixVec);
                    ++ot;
                }
                this->GetOutput()->InitializeByItk(vecImg.GetPointer());
                this->GetOutput()->SetVolume(vecImg->GetBufferPointer());
            }
            catch(...)
            {
                MITK_INFO << "Trying to load dti as nrrd ...";

                typedef itk::VectorImage<float,3> ImageType;
                itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();
                typedef itk::ImageFileReader<ImageType> FileReaderType;
                FileReaderType::Pointer reader = FileReaderType::New();
                reader->SetImageIO(io);
                reader->SetFileName(this->m_FileName);
                reader->Update();
                ImageType::Pointer img = reader->GetOutput();

                typedef itk::Image<itk::DiffusionTensor3D<float>,3> VecImgType;
                VecImgType::Pointer vecImg = VecImgType::New();
                vecImg->SetSpacing( img->GetSpacing() );   // Set the image spacing
                vecImg->SetOrigin( img->GetOrigin() );     // Set the image origin
                vecImg->SetDirection( img->GetDirection() );  // Set the image direction
                vecImg->SetRegions( img->GetLargestPossibleRegion());
                vecImg->Allocate();

                itk::ImageRegionIterator<VecImgType> ot (vecImg, vecImg->GetLargestPossibleRegion() );
                ot = ot.Begin();

                itk::ImageRegionIterator<ImageType> it (img, img->GetLargestPossibleRegion() );
                it = it.Begin();

                typedef ImageType::PixelType  VarPixType;
                typedef VecImgType::PixelType FixPixType;
                int numComponents = img->GetNumberOfComponentsPerPixel();

                itk::MetaDataDictionary imgMetaDictionary = img->GetMetaDataDictionary();
                std::vector<std::string> imgMetaKeys = imgMetaDictionary.GetKeys();
                std::vector<std::string>::const_iterator itKey = imgMetaKeys.begin();
                std::string metaString;

                bool readFrame = false;
                double xx, xy, xz, yx, yy, yz, zx, zy, zz;
                MeasurementFrameType measFrame;
                measFrame.SetIdentity();
                MeasurementFrameType measFrameTransp;
                measFrameTransp.SetIdentity();

                for (; itKey != imgMetaKeys.end(); itKey ++)
                {
                    itk::ExposeMetaData<std::string> (imgMetaDictionary, *itKey, metaString);
                    if (itKey->find("measurement frame") != std::string::npos)
                    {
                        sscanf(metaString.c_str(), " ( %lf , %lf , %lf ) ( %lf , %lf , %lf ) ( %lf , %lf , %lf ) \n", &xx, &xy, &xz, &yx, &yy, &yz, &zx, &zy, &zz);

                        if (xx>10e-10 || xy>10e-10 || xz>10e-10 ||
                                yx>10e-10 || yy>10e-10 || yz>10e-10 ||
                                zx>10e-10 || zy>10e-10 || zz>10e-10 )
                        {
                            readFrame = true;

                            measFrame(0,0) = xx;
                            measFrame(0,1) = xy;
                            measFrame(0,2) = xz;
                            measFrame(1,0) = yx;
                            measFrame(1,1) = yy;
                            measFrame(1,2) = yz;
                            measFrame(2,0) = zx;
                            measFrame(2,1) = zy;
                            measFrame(2,2) = zz;

                            measFrameTransp = measFrame.GetTranspose();
                        }
                    }
                }

                if (numComponents==6)
                {
                    while (!it.IsAtEnd())
                    {
                        // T'=RTR'
                        VarPixType vec = it.Get();
                        FixPixType fixVec(vec.GetDataPointer());

                        if(readFrame)
                        {
                            itk::DiffusionTensor3D<float> tensor;
                            tensor.SetElement(0, vec.GetElement(0));
                            tensor.SetElement(1, vec.GetElement(1));
                            tensor.SetElement(2, vec.GetElement(2));
                            tensor.SetElement(3, vec.GetElement(3));
                            tensor.SetElement(4, vec.GetElement(4));
                            tensor.SetElement(5, vec.GetElement(5));

                            tensor = ConvertMatrixTypeToFixedArrayType(tensor.PreMultiply(measFrame));
                            tensor = ConvertMatrixTypeToFixedArrayType(tensor.PostMultiply(measFrameTransp));
                            fixVec = tensor;
                        }

                        ot.Set(fixVec);
                        ++ot;
                        ++it;
                    }
                }
                else if(numComponents==9)
                {
                    while (!it.IsAtEnd())
                    {
                        VarPixType vec = it.Get();
                        itk::DiffusionTensor3D<float> tensor;
                        tensor.SetElement(0, vec.GetElement(0));
                        tensor.SetElement(1, vec.GetElement(1));
                        tensor.SetElement(2, vec.GetElement(2));
                        tensor.SetElement(3, vec.GetElement(4));
                        tensor.SetElement(4, vec.GetElement(5));
                        tensor.SetElement(5, vec.GetElement(8));

                        if(readFrame)
                        {
                            tensor = ConvertMatrixTypeToFixedArrayType(tensor.PreMultiply(measFrame));
                            tensor = ConvertMatrixTypeToFixedArrayType(tensor.PostMultiply(measFrameTransp));
                        }

                        FixPixType fixVec(tensor);
                        ot.Set(fixVec);
                        ++ot;
                        ++it;
                    }
                }
                else if (numComponents==1)
                {
                    typedef itk::Image<float,4> ImageType;
                    itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();
                    typedef itk::ImageFileReader<ImageType> FileReaderType;
                    FileReaderType::Pointer reader = FileReaderType::New();
                    reader->SetImageIO(io);
                    reader->SetFileName(this->m_FileName);
                    reader->Update();
                    ImageType::Pointer img = reader->GetOutput();

                    itk::Size<4> size = img->GetLargestPossibleRegion().GetSize();

                    MITK_INFO << size;

                    while (!ot.IsAtEnd())
                    {
                        itk::DiffusionTensor3D<float> tensor;
                        ImageType::IndexType idx;
                        idx[0] = ot.GetIndex()[0]; idx[1] = ot.GetIndex()[1]; idx[2] = ot.GetIndex()[2];

                        if (size[3]==6)
                        {
                            for (int te=0; te<size[3]; te++)
                            {
                                idx[3] = te;
                                tensor.SetElement(te, img->GetPixel(idx));
                            }

                            //                        idx[3] = 0;
                            //                        tensor.SetElement(0, img->GetPixel(idx));
                            //                        idx[3] = 1;
                            //                        tensor.SetElement(1, img->GetPixel(idx));
                            //                        idx[3] = 3;
                            //                        tensor.SetElement(2, img->GetPixel(idx));
                            //                        idx[3] = 2;
                            //                        tensor.SetElement(3, img->GetPixel(idx));
                            //                        idx[3] = 4;
                            //                        tensor.SetElement(4, img->GetPixel(idx));
                            //                        idx[3] = 5;
                            //                        tensor.SetElement(5, img->GetPixel(idx));
                        }
                        else if (size[3]==9)
                        {
                            idx[3] = 0;
                            tensor.SetElement(0, img->GetPixel(idx));
                            idx[3] = 1;
                            tensor.SetElement(1, img->GetPixel(idx));
                            idx[3] = 2;
                            tensor.SetElement(2, img->GetPixel(idx));
                            idx[3] = 4;
                            tensor.SetElement(3, img->GetPixel(idx));
                            idx[3] = 5;
                            tensor.SetElement(4, img->GetPixel(idx));
                            idx[3] = 8;
                            tensor.SetElement(5, img->GetPixel(idx));
                        }
                        else
                            throw itk::ImageFileReaderException(__FILE__, __LINE__, "Unknown number of komponents for DTI file. Should be 6 or 9!");

                        if(readFrame)
                        {
                            tensor = ConvertMatrixTypeToFixedArrayType(tensor.PreMultiply(measFrame));
                            tensor = ConvertMatrixTypeToFixedArrayType(tensor.PostMultiply(measFrameTransp));
                        }
                        FixPixType fixVec(tensor);
                        ot.Set(fixVec);
                        ++ot;
                    }
                }
                else
                {
                    throw itk::ImageFileReaderException(__FILE__, __LINE__, "Image has wrong number of pixel components!");
                }

                this->GetOutput()->InitializeByItk(vecImg.GetPointer());
                this->GetOutput()->SetVolume(vecImg->GetBufferPointer());

            }

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

        }
        catch(std::exception& e)
        {
            throw itk::ImageFileReaderException(__FILE__, __LINE__, e.what());
        }
        catch(...)
        {
            throw itk::ImageFileReaderException(__FILE__, __LINE__, "Sorry, an error occurred while reading the requested DTI file!");
        }
    }
}
int main(int, char ** argv)
{
	OptionsData options;
	readXMLValues(argv[2], options);
	
	exit(1);


	// parse the dicom directory
	gdcm::Directory dir;
	dir.Load(argv[1], true);
	gdcm::Directory::FilenamesType filenames = dir.GetFilenames();

	
	gdcm::Tag seriesDescription = gdcm::Tag(0x0008,0x103e);
	gdcm::Tag seriesNumber = gdcm::Tag(0x0020,0x0011);
	gdcm::Tag instanceNumber = gdcm::Tag(0x0020,0x0013);
	gdcm::Tag sliceThickness = gdcm::Tag(0x0018,0x0050);
	gdcm::Tag triggerTime = gdcm::Tag(0x0018,0x1060);
	gdcm::Tag numberOfImages = gdcm::Tag(0x0018,0x1090);
	gdcm::Tag slicePosition = gdcm::Tag(0x0019,0x1015);
	gdcm::Tag imagePosition = gdcm::Tag(0x0020,0x0032);
	gdcm::Tag imageOrientation = gdcm::Tag(0x0020,0x0037);
	gdcm::Tag sliceLocation = gdcm::Tag(0x0020,0x1041);
	gdcm::Tag rows = gdcm::Tag(0x0028,0x0010);
	gdcm::Tag cols = gdcm::Tag(0x0028,0x0011);
	gdcm::Tag pixelSpacing = gdcm::Tag(0x0028,0x0030);

	gdcm::Scanner scanner;
	scanner.AddTag(seriesDescription);
	scanner.AddTag(seriesNumber);
	scanner.AddTag(instanceNumber);
	scanner.AddTag(sliceThickness);
	scanner.AddTag(triggerTime);
	scanner.AddTag(numberOfImages);
	scanner.AddTag(slicePosition);
	scanner.AddTag(imagePosition);
	scanner.AddTag(imageOrientation);
	scanner.AddTag(sliceLocation);
	scanner.AddTag(rows);
	scanner.AddTag(cols);
	scanner.AddTag(pixelSpacing);

	scanner.Scan(filenames);
	gdcm::Scanner::MappingType mapping = scanner.GetMappings();


	// extract all the images that are Short axis and are the first instance
	gdcm::Directory::FilenamesType targetFilenames;
	for(unsigned int i = 0; i < filenames.size(); i++)
	{
		const char * fname = filenames[i].c_str();
		if(mapping.count(fname) == 0) continue;


		// extract the image information
		std::string descriptionStr = mapping[fname][seriesDescription];
		std::string instanceNumberStr = mapping[fname][instanceNumber];
		QString description = QString::fromStdString(descriptionStr);
		unsigned int instanceNumber = QString::fromStdString(instanceNumberStr).toInt();

		// check that the description is a short axis one and is instance 1
		if(instanceNumber == 1 && description.contains("sa", Qt::CaseInsensitive))
		{
			targetFilenames.push_back(filenames[i]);
		}
	}


	// sort the images based on their slice position
	/*
	gdcm::Sorter sorter;
	sorter.SetSortFunction(position_sort);
	sorter.StableSort(targetFilenames);

	gdcm::Directory::FilenamesType sorted = sorter.GetFilenames();
	for(unsigned int i = 0; i < sorted.size(); i++)
	{
		const char * fname = sorted[i].c_str();
		std::string position = mapping[fname][imagePosition];
		std::cout << position << std::endl;
		std::cout << mapping[fname][sliceLocation] << std::endl;
	}
	*/

	std::cout << targetFilenames.size() << std::endl;


	// find the slice with the smallest slice position
	double smallest = 1000000.0;
	int smallestIndex;
	for(unsigned int i = 0; i < targetFilenames.size(); i++)
	{
		const char * fname = targetFilenames[i].c_str();
		std::string slicePosition = mapping[fname][sliceLocation];
		double pos = QString::fromStdString(slicePosition).toDouble();

		std::cout << pos << std::endl;
		if(pos < smallest)
		{	
			smallest = pos;
			smallestIndex = i;
		}
	}

	// load the image
	typedef itk::Image<unsigned short, 3> ImageType;
	typedef itk::ImageFileReader<ImageType> ReaderType;
	ReaderType::Pointer reader = ReaderType::New();
	reader->SetFileName(targetFilenames[smallestIndex]);
	reader->SetImageIO(itk::GDCMImageIO::New());
	reader->Update();

	
	// flip the x and y axis
	typedef itk::PermuteAxesImageFilter<ImageType> FlipperType;
	FlipperType::Pointer flipper = FlipperType::New();
	itk::FixedArray<unsigned int, 3> order;
	order[0] = 1;
	order[1] = 0;
	order[2] = 2;
	flipper->SetOrder(order);
	flipper->SetInput(reader->GetOutput());
	flipper->Update();


	ImageType::Pointer referenceImage = flipper->GetOutput();
	ImageType::DirectionType direction = referenceImage->GetDirection();
	direction.SetIdentity();
	referenceImage->SetDirection(direction);
	
	ImageType::PointType origin = referenceImage->GetOrigin();
	origin.Fill(20.0);
	referenceImage->SetOrigin(origin);

	ImageType::SpacingType spacing;
	spacing.Fill(1.0);

	referenceImage->SetSpacing(spacing);


	
	flipper->GetOutput()->Print(std::cout);

	typedef itk::ImageFileWriter<ImageType> WriterType;
	WriterType::Pointer writer = WriterType::New();
	writer->SetInput(referenceImage);
	writer->SetImageIO(itk::NrrdImageIO::New());
	writer->SetFileName("test.nrrd");
	writer->Update();

	std::cout << targetFilenames[smallestIndex] << std::endl;

	return 0;
}
Пример #17
0
vtkSmartPointer<vtkImageData> GNC::GCS::ControladorCarga::CargarITKMultidimensionalUnsignedShort(IComando* cmd, ListaRutas& listaFicheros, int* orientacion, double* spacing)
{
        vtkSmartPointer<vtkImageData> img = vtkSmartPointer<vtkImageData>::New();
        //int bitsStored, highBit, bitsAllocated,pixelRepresentation = 0;

        wxCriticalSectionLocker locker(*m_pCriticalSection);

        typedef double PixelType;
        typedef itk::Image<PixelType, 3 > ImageType;
        typedef itk::GDCMImageIO ImageIOType;
        typedef itk::ImageSeriesReader<ImageType> GenericReaderType;

        ImageIOType::Pointer              dicomIO    = ImageIOType::New();
        GenericReaderType::Pointer        reader     = GenericReaderType::New();
        CargaItkProgressCallback::Pointer cbProgreso = CargaItkProgressCallback::New();


        try {
                reader->SetImageIO(dicomIO);

                if (listaFicheros.size() > 0) {
                        std::vector<std::string> filesCopy(listaFicheros.size());
                        GNC::GCS::IControladorCarga::ListaRutas::iterator it = listaFicheros.begin();
                        std::vector<std::string>::size_type off = 0;
                        while (it != listaFicheros.end()) {
                                filesCopy[off++] = *(it++);
                        }
                        reader->SetFileNames(filesCopy);
                } else {
                        throw GNC::GCS::ControladorCargaException( "No input files", "ControladorCarga/CargarITKMultidimensionalUnsignedShort");
                }
                //reader->GetOutput()->ReleaseDataFlagOn();

                cbProgreso->SetCommand(cmd);
                cbProgreso->SetTexto(_Std("Reading properties"));

                reader->AddObserver (itk::ProgressEvent(), cbProgreso);

                reader->UpdateOutputInformation();
        } catch (itk::ExceptionObject& ex) {
                reader->ResetPipeline();
                throw GNC::GCS::ControladorCargaException( _Std("Error reading the study: ") + ex.GetDescription(), "ControladorCarga/CargaMultidimensional");
        } catch (std::exception& ex) {
                reader->ResetPipeline();
                throw GNC::GCS::ControladorCargaException( _Std("Internal error reading the study: "), std::string("ControladorCarga/CargaMultidimensional") + ex.what());
        } catch (...) {
                reader->ResetPipeline();
                throw GNC::GCS::ControladorCargaException( _Std("Internal error reading the study: "), "ControladorCarga/CargaMultidimensional");
        }

        if (orientacion != NULL) {

                ImageType::Pointer im = reader->GetOutput();
                ImageType::DirectionType dir = im->GetDirection();

                /*
                std::cout << dir[0][0] << ", " << dir[0][1] << ", " << dir[0][2] << std::endl;
                std::cout << dir[1][0] << ", " << dir[1][1] << ", " << dir[1][2] << std::endl;
                std::cout << dir[2][0] << ", " << dir[2][1] << ", " << dir[2][2] << std::endl;
                */

                if( std::abs( dir[0][2] ) > std::abs(dir[1][2]) && std::abs( dir[0][2]) > std::abs(dir[2][2])) {
                        //std::cout << "SAGITAL" << std::endl;
                        *orientacion = 0;
                } else if( std::abs( dir[1][2] ) > std::abs(dir[0][2]) && std::abs( dir[1][2]) > std::abs(dir[2][2])) {
                        //std::cout << "CORONAL" << std::endl;
                        *orientacion = 1;
                } else if( std::abs( dir[2][2] ) > std::abs(dir[0][2]) && std::abs( dir[2][2]) > std::abs(dir[1][2])) {
                        //std::cout << "AXIAL" << std::endl;
                        *orientacion = 2;
                }
        }

        GenericReaderType::OutputImageType::SizeType dims = reader->GetOutput()->GetLargestPossibleRegion().GetSize();

        img->SetDimensions(dims[0], dims[1], dims[2]);
        img->SetOrigin(dicomIO->GetOrigin(0), dicomIO->GetOrigin(1), dicomIO->GetOrigin(2));

        if(spacing == NULL) {
                double chk_spacing[3] = {dicomIO->GetSpacing(0), dicomIO->GetSpacing(1), dicomIO->GetSpacing(2)};
                if (chk_spacing[0] < std::numeric_limits<double>::epsilon() || chk_spacing[1] < std::numeric_limits<double>::epsilon()) {
                        std::stringstream ss;
                        ss << _Std("Spacing is not valid: (") << chk_spacing[0] << ", " << chk_spacing[1] << ", " << chk_spacing[2] << ")";
                        GNC::GCS::ControladorEventos::Instance()->ProcesarEvento(new GNC::GCS::Events::EventoMensajes(NULL,ss.str(),GNC::GCS::Events::EventoMensajes::PopUpMessage,GNC::GCS::Events::EventoMensajes::Aviso));
                        chk_spacing[0] = 1.0f;
                        chk_spacing[1] = 1.0f;
                        chk_spacing[2] = 1.0f;
                }
                img->SetSpacing(chk_spacing);
        } else {
                double chk_spacing[3] = {spacing[0], spacing[1], spacing[2]};
                if (chk_spacing[0] < std::numeric_limits<double>::epsilon() || chk_spacing[1] < std::numeric_limits<double>::epsilon()) {
                        std::stringstream ss;
                        ss << _Std("Spacing is not valid: (") << chk_spacing[0] << ", " << chk_spacing[1] << ", " << chk_spacing[2] << ")";
                        GNC::GCS::ControladorEventos::Instance()->ProcesarEvento(new GNC::GCS::Events::EventoMensajes(NULL,ss.str(),GNC::GCS::Events::EventoMensajes::PopUpMessage,GNC::GCS::Events::EventoMensajes::Aviso));
                        chk_spacing[0] = 1.0f;
                        chk_spacing[1] = 1.0f;
                        chk_spacing[2] = 1.0f;
                }
                img->SetSpacing(chk_spacing);
        }

        itk::ProcessObject::Pointer processObject;
        switch(dicomIO->GetComponentType()) {
        case ImageIOType::UCHAR: {
                typedef unsigned char TypedPixelType;
                typedef itk::Image<TypedPixelType, 3 > TypedImageType;
                typedef itk::ImageSeriesReader<TypedImageType> TypedReaderType;

                try {
                        img->AllocateScalars(VTK_UNSIGNED_CHAR, dicomIO->GetNumberOfComponents());
                } catch (...) {
                        throw GNC::GCS::ControladorCargaException( _Std("Error loading the study: Out of memory"), "ControladorCarga/CargaMultidimensional");
                }

                TypedReaderType::Pointer treader = TypedReaderType::New();
                ImageIOType::Pointer     tdicomIO = ImageIOType::New();
                treader->SetImageIO(tdicomIO);
                if (listaFicheros.size() > 0) {
                        std::vector<std::string> filesCopy(listaFicheros.size());
                        GNC::GCS::IControladorCarga::ListaRutas::iterator it = listaFicheros.begin();
                        std::vector<std::string>::size_type off = 0;

                        while (it != listaFicheros.end()) {
                                filesCopy[off++] = *(it++);
                        }
                        treader->SetFileNames(filesCopy);
                }
                treader->SetUseStreaming(true);
                //treader->GetOutput()->ReleaseDataFlagOn();
                treader->GetOutput()->GetPixelContainer()->SetImportPointer((TypedReaderType::OutputImageType::PixelType*)(img->GetScalarPointer()), dims[0] * dims[1] * dims[2], false );
                processObject = treader;
        }
        break;
        case ImageIOType::CHAR: {
                typedef char TypedPixelType;
                typedef itk::Image<TypedPixelType, 3 > TypedImageType;
                typedef itk::ImageSeriesReader<TypedImageType> TypedReaderType;

                try {
                        img->AllocateScalars(VTK_CHAR, dicomIO->GetNumberOfComponents());
                } catch (...) {
                        throw GNC::GCS::ControladorCargaException( _Std("Error loading the study: Out of memory"), "ControladorCarga/CargaMultidimensional");
                }

                TypedReaderType::Pointer treader = TypedReaderType::New();
                ImageIOType::Pointer     tdicomIO = ImageIOType::New();
                treader->SetImageIO(tdicomIO);
                if (listaFicheros.size() > 0) {
                        std::vector<std::string> filesCopy(listaFicheros.size());
                        GNC::GCS::IControladorCarga::ListaRutas::iterator it = listaFicheros.begin();
                        std::vector<std::string>::size_type off = 0;

                        while (it != listaFicheros.end()) {
                                filesCopy[off++] = *(it++);
                        }
                        treader->SetFileNames(filesCopy);
                }
                treader->SetUseStreaming(true);
                //treader->GetOutput()->ReleaseDataFlagOn();
                treader->GetOutput()->GetPixelContainer()->SetImportPointer((TypedReaderType::OutputImageType::PixelType*)(img->GetScalarPointer()), dims[0] * dims[1] * dims[2], false );
                processObject = treader;
        }
        break;
        case ImageIOType::USHORT: {
                typedef unsigned short TypedPixelType;
                typedef itk::Image<TypedPixelType, 3 > TypedImageType;
                typedef itk::ImageSeriesReader<TypedImageType> TypedReaderType;

                try {
                        img->AllocateScalars(VTK_UNSIGNED_SHORT, dicomIO->GetNumberOfComponents());
                } catch(const std::bad_alloc&) {
                        throw GNC::GCS::ControladorCargaException( _Std("Error loading the study: Out of memory"), "ControladorCarga/CargaMultidimensional");
                } catch (...) {
                        throw GNC::GCS::ControladorCargaException( _Std("Error loading the study: Internal Error"), "ControladorCarga/CargaMultidimensional");
                }

                TypedReaderType::Pointer treader = TypedReaderType::New();
                ImageIOType::Pointer     tdicomIO = ImageIOType::New();
                treader->SetImageIO(tdicomIO);
                if (listaFicheros.size() > 0) {
                        std::vector<std::string> filesCopy(listaFicheros.size());
                        GNC::GCS::IControladorCarga::ListaRutas::iterator it = listaFicheros.begin();
                        std::vector<std::string>::size_type off = 0;

                        while (it != listaFicheros.end()) {
                                filesCopy[off++] = *(it++);
                        }
                        treader->SetFileNames(filesCopy);
                }
                treader->SetUseStreaming(true);
                //treader->GetOutput()->ReleaseDataFlagOn();
                treader->GetOutput()->GetPixelContainer()->SetImportPointer((TypedReaderType::OutputImageType::PixelType*)(img->GetScalarPointer()), dims[0] * dims[1] * dims[2], false );
                processObject = treader;
        }
        break;
        case ImageIOType::SHORT: {
                typedef short TypedPixelType;
                typedef itk::Image<TypedPixelType, 3 > TypedImageType;
                typedef itk::ImageSeriesReader<TypedImageType> TypedReaderType;

                try {
                        img->AllocateScalars(VTK_SHORT, dicomIO->GetNumberOfComponents());
                } catch (...) {
                        throw GNC::GCS::ControladorCargaException( _Std("Error loading the study: Out of memory"), "ControladorCarga/CargaMultidimensional");
                }

                TypedReaderType::Pointer treader = TypedReaderType::New();
                ImageIOType::Pointer     tdicomIO = ImageIOType::New();
                treader->SetImageIO(tdicomIO);
                if (listaFicheros.size() > 0) {
                        std::vector<std::string> filesCopy(listaFicheros.size());
                        GNC::GCS::IControladorCarga::ListaRutas::iterator it = listaFicheros.begin();
                        std::vector<std::string>::size_type off = 0;

                        while (it != listaFicheros.end()) {
                                filesCopy[off++] = *(it++);
                        }
                        treader->SetFileNames(filesCopy);
                }
                treader->SetUseStreaming(true);
                //treader->GetOutput()->ReleaseDataFlagOn();
                treader->GetOutput()->GetPixelContainer()->SetImportPointer((TypedReaderType::OutputImageType::PixelType*)(img->GetScalarPointer()), dims[0] * dims[1] * dims[2], false );
                processObject = treader;
        }
        break;
        case ImageIOType::UINT: {
                typedef unsigned int TypedPixelType;
                typedef itk::Image<TypedPixelType, 3 > TypedImageType;
                typedef itk::ImageSeriesReader<TypedImageType> TypedReaderType;


                try {
                        img->AllocateScalars(VTK_UNSIGNED_INT, dicomIO->GetNumberOfComponents());
                } catch (...) {
                        throw GNC::GCS::ControladorCargaException( _Std("Error loading the study: Out of memory"), "ControladorCarga/CargaMultidimensional");
                }

                TypedReaderType::Pointer treader = TypedReaderType::New();
                ImageIOType::Pointer     tdicomIO = ImageIOType::New();
                treader->SetImageIO(tdicomIO);
                if (listaFicheros.size() > 0) {
                        std::vector<std::string> filesCopy(listaFicheros.size());
                        GNC::GCS::IControladorCarga::ListaRutas::iterator it = listaFicheros.begin();
                        std::vector<std::string>::size_type off = 0;

                        while (it != listaFicheros.end()) {
                                filesCopy[off++] = *(it++);
                        }
                        treader->SetFileNames(filesCopy);
                }
                treader->SetUseStreaming(true);
                //treader->GetOutput()->ReleaseDataFlagOn();
                treader->GetOutput()->GetPixelContainer()->SetImportPointer((TypedReaderType::OutputImageType::PixelType*)(img->GetScalarPointer()), dims[0] * dims[1] * dims[2], false );
                processObject = treader;
        }
        break;
        case ImageIOType::INT: {
                typedef int TypedPixelType;
                typedef itk::Image<TypedPixelType, 3 > TypedImageType;
                typedef itk::ImageSeriesReader<TypedImageType> TypedReaderType;


                try {
                        img->AllocateScalars(VTK_INT, dicomIO->GetNumberOfComponents());
                } catch (...) {
                        throw GNC::GCS::ControladorCargaException( _Std("Error loading the study: Out of memory"), "ControladorCarga/CargaMultidimensional");
                }

                TypedReaderType::Pointer treader = TypedReaderType::New();
                ImageIOType::Pointer     tdicomIO = ImageIOType::New();
                treader->SetImageIO(tdicomIO);
                if (listaFicheros.size() > 0) {
                        std::vector<std::string> filesCopy(listaFicheros.size());
                        GNC::GCS::IControladorCarga::ListaRutas::iterator it = listaFicheros.begin();
                        std::vector<std::string>::size_type off = 0;

                        while (it != listaFicheros.end()) {
                                filesCopy[off++] = *(it++);
                        }
                        treader->SetFileNames(filesCopy);
                }
                treader->SetUseStreaming(true);
                //treader->GetOutput()->ReleaseDataFlagOn();
                treader->GetOutput()->GetPixelContainer()->SetImportPointer((TypedReaderType::OutputImageType::PixelType*)(img->GetScalarPointer()), dims[0] * dims[1] * dims[2], false );
                processObject = treader;
        }
        break;
        case ImageIOType::ULONG: {
                typedef unsigned long TypedPixelType;
                typedef itk::Image<TypedPixelType, 3 > TypedImageType;
                typedef itk::ImageSeriesReader<TypedImageType> TypedReaderType;


                try {
                        img->AllocateScalars(VTK_UNSIGNED_LONG, dicomIO->GetNumberOfComponents());
                } catch (...) {
                        throw GNC::GCS::ControladorCargaException( _Std("Error loading the study: Out of memory"), "ControladorCarga/CargaMultidimensional");
                }

                TypedReaderType::Pointer treader = TypedReaderType::New();
                ImageIOType::Pointer     tdicomIO = ImageIOType::New();
                treader->SetImageIO(tdicomIO);
                if (listaFicheros.size() > 0) {
                        std::vector<std::string> filesCopy(listaFicheros.size());
                        GNC::GCS::IControladorCarga::ListaRutas::iterator it = listaFicheros.begin();
                        std::vector<std::string>::size_type off = 0;

                        while (it != listaFicheros.end()) {
                                filesCopy[off++] = *(it++);
                        }
                        treader->SetFileNames(filesCopy);
                }
                treader->SetUseStreaming(true);
                //treader->GetOutput()->ReleaseDataFlagOn();
                treader->GetOutput()->GetPixelContainer()->SetImportPointer((TypedReaderType::OutputImageType::PixelType*)(img->GetScalarPointer()), dims[0] * dims[1] * dims[2], false );
                processObject = treader;
        }
        break;
        case ImageIOType::LONG: {
                typedef long TypedPixelType;
                typedef itk::Image<TypedPixelType, 3 > TypedImageType;
                typedef itk::ImageSeriesReader<TypedImageType> TypedReaderType;

                try {
                        img->AllocateScalars(VTK_LONG, dicomIO->GetNumberOfComponents());
                } catch (...) {
                        throw GNC::GCS::ControladorCargaException( _Std("Error loading the study: Out of memory"), "ControladorCarga/CargaMultidimensional");
                }

                TypedReaderType::Pointer treader = TypedReaderType::New();
                ImageIOType::Pointer     tdicomIO = ImageIOType::New();
                treader->SetImageIO(tdicomIO);
                if (listaFicheros.size() > 0) {
                        std::vector<std::string> filesCopy(listaFicheros.size());
                        GNC::GCS::IControladorCarga::ListaRutas::iterator it = listaFicheros.begin();
                        std::vector<std::string>::size_type off = 0;

                        while (it != listaFicheros.end()) {
                                filesCopy[off++] = *(it++);
                        }
                        treader->SetFileNames(filesCopy);
                }
                treader->SetUseStreaming(true);
                //treader->GetOutput()->ReleaseDataFlagOn();
                treader->GetOutput()->GetPixelContainer()->SetImportPointer((TypedReaderType::OutputImageType::PixelType*)(img->GetScalarPointer()), dims[0] * dims[1] * dims[2], false );
                processObject = treader;
        }
        break;
        case ImageIOType::FLOAT: {
                typedef float TypedPixelType;
                typedef itk::Image<TypedPixelType, 3 > TypedImageType;
                typedef itk::ImageSeriesReader<TypedImageType> TypedReaderType;

                try {
                        img->AllocateScalars(VTK_FLOAT, dicomIO->GetNumberOfComponents());
                } catch (...) {
                        throw GNC::GCS::ControladorCargaException( _Std("Error loading the study: Out of memory"), "ControladorCarga/CargaMultidimensional");
                }

                TypedReaderType::Pointer treader = TypedReaderType::New();
                ImageIOType::Pointer     tdicomIO = ImageIOType::New();
                treader->SetImageIO(tdicomIO);
                if (listaFicheros.size() > 0) {
                        std::vector<std::string> filesCopy(listaFicheros.size());
                        GNC::GCS::IControladorCarga::ListaRutas::iterator it = listaFicheros.begin();
                        std::vector<std::string>::size_type off = 0;

                        while (it != listaFicheros.end()) {
                                filesCopy[off++] = *(it++);
                        }
                        treader->SetFileNames(filesCopy);
                }
                treader->SetUseStreaming(true);
                //treader->GetOutput()->ReleaseDataFlagOn();
                treader->GetOutput()->GetPixelContainer()->SetImportPointer((TypedReaderType::OutputImageType::PixelType*)(img->GetScalarPointer()), dims[0] * dims[1] * dims[2], false );
                processObject = treader;
        }
        break;
        case ImageIOType::DOUBLE: {
                typedef double TypedPixelType;
                typedef itk::Image<TypedPixelType, 3 > TypedImageType;
                typedef itk::ImageSeriesReader<TypedImageType> TypedReaderType;

                try {
                        img->AllocateScalars(VTK_DOUBLE, dicomIO->GetNumberOfComponents());
                } catch (...) {
                        throw GNC::GCS::ControladorCargaException( _Std("Error loading the study: Out of memory"), "ControladorCarga/CargaMultidimensional");
                }

                TypedReaderType::Pointer treader = TypedReaderType::New();
                ImageIOType::Pointer     tdicomIO = ImageIOType::New();
                treader->SetImageIO(tdicomIO);
                if (listaFicheros.size() > 0) {
                        std::vector<std::string> filesCopy(listaFicheros.size());
                        GNC::GCS::IControladorCarga::ListaRutas::iterator it = listaFicheros.begin();
                        std::vector<std::string>::size_type off = 0;

                        while (it != listaFicheros.end()) {
                                filesCopy[off++] = *(it++);
                        }
                        treader->SetFileNames(filesCopy);
                }
                treader->SetUseStreaming(true);
                //treader->GetOutput()->ReleaseDataFlagOn();
                treader->GetOutput()->GetPixelContainer()->SetImportPointer((TypedReaderType::OutputImageType::PixelType*)(img->GetScalarPointer()), dims[0] * dims[1] * dims[2], false );
                processObject = treader;
        }
        break;
        case ImageIOType::UNKNOWNCOMPONENTTYPE:
        default:
                throw GNC::GCS::ControladorCargaException( _Std("Error reading the study: unsupported pixel format"), "ControladorCarga/CargaMultidimensional");
        }

        cbProgreso->SetTexto("Leyendo dataset");
        processObject->AddObserver (itk::ProgressEvent(), cbProgreso);

        try {
                processObject->UpdateLargestPossibleRegion();
        } catch (itk::ExceptionObject& ex) {
                reader->ResetPipeline();
                throw GNC::GCS::ControladorCargaException( _Std("Error reading the study: ") + ex.GetDescription(), "ControladorCarga/CargaMultidimensional");
        } catch (...) {
                reader->ResetPipeline();
                throw GNC::GCS::ControladorCargaException( _Std("Internal error reading the study: "), "ControladorCarga/CargaMultidimensional");
        }
        if (processObject->GetAbortGenerateData()) {
                reader->ResetPipeline();
                throw GNC::GCS::ControladorCargaException( _Std("Process canceled by user."), "ControladorCarga/CargaMultidimensional");
        }


        //se modifica si es necesario
        /*
        {
        	typedef itk::MetaDataObject< std::string > MetaDataStringType;
        	for (itk::MetaDataDictionary::ConstIterator it = dicomIO->GetMetaDataDictionary().Begin(); it != dicomIO->GetMetaDataDictionary().End(); ++it) {
        		itk::MetaDataObjectBase::Pointer entry = it->second;
        		MetaDataStringType::Pointer entryvalue = dynamic_cast<MetaDataStringType *> (entry.GetPointer());
        		if(it->first == "0028|0100") { //bits allocated
        			std::istringstream is(entryvalue->GetMetaDataObjectValue());
        			is >>bitsAllocated;
        		} else if(it->first == "0028|0101") { //bits stored
        			std::istringstream is(entryvalue->GetMetaDataObjectValue());
        			is >>bitsStored;
        		} else if(it->first == "0028|0102") {//high bit
        			std::istringstream is(entryvalue->GetMetaDataObjectValue());
        			is >>highBit;
        		}	else if(it->first == "0028|0103") {//pixel representation=> 0 es unsigned 1 es signed
        			std::istringstream is(entryvalue->GetMetaDataObjectValue());
        			is >>pixelRepresentation;
        		}
        	}
        	if(bitsAllocated != bitsStored)
        	{
        		switch(dicomIO->GetComponentType()) {
        			case ImageIOType::UCHAR:
        				pixelRepresentation = 0;
        				//a partir de aqui se trata el pixelrepresentation
        			case ImageIOType::CHAR:
        				{
        					unsigned char* data = (unsigned char*) img->GetScalarPointer();
        					unsigned char desplazamientoSigno;
        					desplazamientoSigno = highBit;
        					unsigned char maskComprobarSigno = 1;
        					maskComprobarSigno <<= desplazamientoSigno;

        					unsigned char maskClearParteAltaPositivo = 0;
        					//se meten unos en la parte baja
        					if(pixelRepresentation == 0) {
        						for(int i = 0; i<= desplazamientoSigno; ++i)
        						{
        							maskClearParteAltaPositivo <<=1;
        							maskClearParteAltaPositivo |=1;
        						}
        					} else {
        						for(int i = 0; i< desplazamientoSigno; ++i)
        						{
        							maskClearParteAltaPositivo <<=1;
        							maskClearParteAltaPositivo |=1;
        						}
        					}
        					//se meten unos en la parte alta
        					unsigned char maskSetParteAltaNegativo = 0x80;
        					if(pixelRepresentation != 0) {
        						for(int i=0; i< 8-desplazamientoSigno; ++i)
        						{
        							maskSetParteAltaNegativo >>=1;
        							maskSetParteAltaNegativo |=0x80;
        						}
        					}

        					int size = dims[0] * dims[1] * dims[2];
        					if(pixelRepresentation == 0) {
        						if(maskClearParteAltaPositivo != 0xFF) { // si es ff no tiene sentido hacer nada
        							int size = dims[0] * dims[1] * dims[2] * 2;
        							for(int i= 0; i< size; i+=2)
        							{
        								//es positivo
        								data[i] &= maskClearParteAltaPositivo;
        							}
        						}
        					} else {
        						for(int i= 0; i< size; ++i)
        						{
        							if((data[i] & maskComprobarSigno) == 0)
        							{
        								//es positivo
        								data[i] &= maskClearParteAltaPositivo;
        							} else {
        								//es negativo => aplicar el complemento a dos...
        								data[i] |= maskSetParteAltaNegativo;
        							}
        						}
        					}
        				}
        				break;
        			case ImageIOType::USHORT:
        				pixelRepresentation = 0;
        				//a partir de aqui se trata el pixelrepresentation
        			case ImageIOType::SHORT:
        				{
        					unsigned char* data = (unsigned char*) img->GetScalarPointer();
        					unsigned char posicionInicial;
        					unsigned char desplazamientoSigno;
        					if(highBit>=8) { //little endian
        						desplazamientoSigno = highBit - 8 ;
        						posicionInicial = 1;
        					} else { //bigEndian
        						desplazamientoSigno = highBit;
        						posicionInicial = 0;
        					}
        					unsigned char maskComprobarSigno = 1;
        					maskComprobarSigno <<= desplazamientoSigno;

        					unsigned char maskClearParteAltaPositivo = 0;
        					//se meten unos en la parte baja
        					if(pixelRepresentation == 0) {
        						for(int i = 0; i<= desplazamientoSigno; ++i)
        						{
        							maskClearParteAltaPositivo <<=1;
        							maskClearParteAltaPositivo |=1;
        						}
        					} else {
        						for(int i = 0; i< desplazamientoSigno; ++i)
        						{
        							maskClearParteAltaPositivo <<=1;
        							maskClearParteAltaPositivo |=1;
        						}
        					}
        					//se meten unos en la parte alta
        					unsigned char maskSetParteAltaNegativo = 0x80;
        					if(pixelRepresentation != 0) {
        						for(int i=0; i< 8-desplazamientoSigno; ++i)
        						{
        							maskSetParteAltaNegativo >>=1;
        							maskSetParteAltaNegativo |=0x80;
        						}
        					}

        					int size = dims[0] * dims[1] * dims[2] * 2;

        					if(pixelRepresentation == 0) {
        						if(maskClearParteAltaPositivo != 0xFF) { // si es ff no tiene sentido hacer nada
        							int size = dims[0] * dims[1] * dims[2] * 2;
        							for(int i= posicionInicial; i< size; i+=2)
        							{
        								//es positivo
        								data[i] &= maskClearParteAltaPositivo;
        							}
        						}
        					} else {
        						for(int i= posicionInicial; i< size; i+=2)
        						{
        							if((data[i] & maskComprobarSigno) == 0)
        							{
        								//es positivo
        								data[i] &= maskClearParteAltaPositivo;
        							} else {
        								//es negativo => aplicar el complemento a dos...
        								data[i] |= maskSetParteAltaNegativo;
        							}
        						}
        					}
        				}
        				break;
        			case ImageIOType::UINT:
        				{
        					//d momento no hago na
        				}
        				break;
        			case ImageIOType::INT:
        				{
        					//d momento no hago na
        				}
        				break;
        			case ImageIOType::ULONG:
        				{
        					//d momento no hago na
        				}
        				break;
        			case ImageIOType::LONG:
        				{
        					//d momento no hago na
        				}
        				break;
        			case ImageIOType::FLOAT:
        			case ImageIOType::DOUBLE:
        				break;
        			case ImageIOType::UNKNOWNCOMPONENTTYPE:
        			default:
        				throw GNC::GCS::ControladorCargaException( std::string("Error reading the study: Formato de pixel no soportado"), "ControladorCarga/CargaMultidimensional");
        		}
        	}
        }*/



        return img;
}
Пример #18
0
int main(int argc, char ** argv)
{
	// load the input matrix
	utils::MatrixReader::Pointer reader = utils::MatrixReader::New();
	reader->SetFilename("/home/om0000/ValveTracking/TrainingData/conf6/conf6-MV-2C-0.hdf5");
	reader->Read();
	

	Params pparams("/home/om0000/ValveTracking/TrainingData/conf6/extract_features.json");

	MatrixType pos = reader->GetOutput()->doubleData["p1-pos"];
	MatrixType neg = reader->GetOutput()->doubleData["p1-neg"];
	

	for(unsigned int tNum = 0; tNum < pos.rows(); tNum++)
	{
		MatrixType test = pos.row(tNum);		
		MatrixType others(pos.rows()-1, pos.cols());
		unsigned int count = 0;
		for(unsigned int i = 0; i < pos.rows(); i++)
		{
			if(i != tNum)
			{
				others.row(count) = pos.row(i);			
				count++;
			}
		}

		unsigned int T = others.rows();
		unsigned int Knn = 5;
		unsigned int newCount = 0;
		unsigned int NN = 50;
		srand (time(NULL));

		MatrixType smotePos(NN*T, pos.cols());

		for(unsigned int i = 0; i < T; i++)
		{
			MatrixType s1 = others.row(i);
			MatrixType dists(T,1);
			std::vector<IndexDistPair> sortList;
			for(unsigned int j = 0; j < T; j++)
			{
				if(i == j) continue;
				std::pair<int, double> p(j, (others.row(j)-s1).norm());
				sortList.push_back(p);
			}

			std::sort(sortList.begin(), sortList.end(), index_sort);

			unsigned int N = NN;
			while(N != 0)
			{
				int nn = sortList[rand() % Knn].first;
				MatrixType newF(1, others.cols());
				for(unsigned int j = 0; j < others.cols(); j++)
				{
					double diff = others(nn,j) - s1(0,j);
					double gap = (double) rand() / RAND_MAX;
					smotePos(newCount, j) = round(s1(0,j) + (gap*diff));
				}
				newCount++;
				N--;
			}
		}

		// combine the pos and neg 
		MatrixType newAll, all;
		IntMatrixType newLabels, labels;
		combine(others, neg,  all, labels);
		combine(smotePos, neg, newAll, newLabels);

		/*
		cv::Mat vType = cv::Mat(pos.cols()+1, 1, CV_8U);
		vType.setTo(cv::Scalar(CV_VAR_NUMERICAL));
		vType.at<uchar>(pos.cols(), 0) = CV_VAR_CATEGORICAL;

		cv::Mat X = convert(newAll);
		cv::Mat y = convert(newLabels);
		cv::Mat cvtest = convert(test);

		cv::BoostParams params;
		params.boost_type = CvBoost::GENTLE;
		cv::Boost cls;
		std::cout << "Training" << std::endl;
		//cls.train(X, CV_ROW_SAMPLE, y,
				//cv::Mat(), cv::Mat(), vType, cv::Mat(), params);

		cls.load("cls.cls", "hello");

		std::cout << "Testing" << std::endl;
		std::cout << cls.predict(cvtest, cv::Mat(), cv::Range::all(), false, true) << std::endl;

		/*
		cv::RandomTreeParams params;
		params.max_depth = 25;
		params.regression_accuracy = 0.00001;
		

		cv::NormalBayesClassifier cls;
		cls.train(X, y);

		cv::Mat out;
		cls.predict(cvtest, &out);
		std::cout << out << std::endl;
		*/

		//cv::RandomTrees trees;
		//trees.train(X, CV_ROW_SAMPLE, y,
				//cv::Mat(), cv::Mat(), vType, cv::Mat(), params);

		//std::cout << trees.predict(cvtest) << std::endl;
		/*
		MatrixType probs1, probs2;
		IntMatrixType cls1, cls2;

		*/
		vt::SVMClassifier::Pointer svm1 = vt::SVMClassifier::New();
		svm1->Train(all, labels);


		vt::SVMClassifier::Pointer svm2 = vt::SVMClassifier::New();
		svm2->Train(newAll, newLabels);




		// load the image 
		ValveSequenceReader<3>::Pointer reader = ValveSequenceReader<3>::New();
		reader->SetFileName(argv[1]);
		ValveSequence<3>::Pointer sequence = reader->GetOutput();

		typedef ValveLine<3> ValveType;
		typedef ValveType::ImageType ImageType;
		ValveType::Pointer valve = sequence->GetValveLine(0);
		ImageType::Pointer image = valve->GetImage();
		
		typedef itk::Image<double, 3> RealImageType;
		RealImageType::Pointer output = RealImageType::New();
		output->SetOrigin(image->GetOrigin());
		output->SetSpacing(image->GetSpacing());
		output->SetRegions(image->GetLargestPossibleRegion());
		output->SetDirection(image->GetDirection());
		output->Allocate();

		RealImageType::Pointer output2 = RealImageType::New();
		output2->SetOrigin(image->GetOrigin());
		output2->SetSpacing(image->GetSpacing());
		output2->SetRegions(image->GetLargestPossibleRegion());
		output2->SetDirection(image->GetDirection());
		output2->Allocate();
	
		
		itk::ImageRegionIterator<RealImageType> it(output, output->GetLargestPossibleRegion());
		itk::ImageRegionIterator<RealImageType> it2(output2, output2->GetLargestPossibleRegion());
		while(!it.IsAtEnd())
		{
			ImageType::IndexType index = it.GetIndex();
			ImageType::PointType pt;
			output->TransformIndexToPhysicalPoint(index, pt);

			MatrixType feature;
			extractLBPFeature(pparams, valve, pt, feature);

			MatrixType p1,p2;
			IntMatrixType c1, c2;

			svm1->PredictProbability(feature, c1, p1);
			svm2->PredictProbability(feature, c2, p2);

			it.Set(p1(0,0));
			it2.Set(p2(0,0));


			++it2;
			++it;
		}

		utils::RealVolumeIO::Write("votes.nrrd", output);
		utils::RealVolumeIO::Write("votes2.nrrd", output);
		utils::ImageVolumeIO::Write("image.nrrd", image);
		return 0;


	}







	
	return 0;



}
Пример #19
0
void mitk::DiffusionPropertyHelper::AverageRedundantGradients(double precision)
{

  mitk::GradientDirectionsProperty* DirectionsProperty = static_cast<mitk::GradientDirectionsProperty*>( m_Image->GetProperty(mitk::DiffusionPropertyHelper::GRADIENTCONTAINERPROPERTYNAME.c_str()).GetPointer() );
  GradientDirectionsContainerType::Pointer oldDirs = DirectionsProperty->GetGradientDirectionsContainer();

  GradientDirectionsContainerType::Pointer newDirs =
    CalcAveragedDirectionSet(precision, oldDirs);

  // if sizes equal, we do not need to do anything in this function
  if(oldDirs->size() == newDirs->size())
    return;

  // new image
  ImageType::Pointer oldImage = ImageType::New();
  mitk::CastToItkImage( m_Image, oldImage);
  ImageType::Pointer newITKImage = ImageType::New();
  newITKImage->SetSpacing( oldImage->GetSpacing() );   // Set the image spacing
  newITKImage->SetOrigin( oldImage->GetOrigin() );     // Set the image origin
  newITKImage->SetDirection( oldImage->GetDirection() );  // Set the image direction
  newITKImage->SetLargestPossibleRegion( oldImage->GetLargestPossibleRegion() );
  newITKImage->SetVectorLength( newDirs->size() );
  newITKImage->SetBufferedRegion( oldImage->GetLargestPossibleRegion() );
  newITKImage->Allocate();

  // average image data that corresponds to identical directions
  itk::ImageRegionIterator< ImageType > newIt(newITKImage, newITKImage->GetLargestPossibleRegion());
  newIt.GoToBegin();
  itk::ImageRegionIterator< ImageType > oldIt(oldImage, oldImage->GetLargestPossibleRegion());
  oldIt.GoToBegin();

  // initial new value of voxel
  ImageType::PixelType newVec;
  newVec.SetSize(newDirs->size());
  newVec.AllocateElements(newDirs->size());

  // find which gradients should be averaged
  GradientDirectionsContainerType::Pointer oldDirections = oldDirs;
  std::vector<std::vector<int> > dirIndices;
  for(GradientDirectionsContainerType::ConstIterator gdcitNew = newDirs->Begin();
    gdcitNew != newDirs->End(); ++gdcitNew)
  {
    dirIndices.push_back(std::vector<int>(0));
    for(GradientDirectionsContainerType::ConstIterator gdcitOld = oldDirs->Begin();
      gdcitOld != oldDirections->End(); ++gdcitOld)
    {
      if(AreAlike(gdcitNew.Value(), gdcitOld.Value(), precision))
      {
        //MITK_INFO << gdcitNew.Value() << "  " << gdcitOld.Value();
        dirIndices[gdcitNew.Index()].push_back(gdcitOld.Index());
      }
    }
  }

  //int ind1 = -1;
  while(!newIt.IsAtEnd())
  {

    // progress
    //typename ImageType::IndexType ind = newIt.GetIndex();
    //ind1 = ind.m_Index[2];

    // init new vector with zeros
    newVec.Fill(0.0);

    // the old voxel value with duplicates
    ImageType::PixelType oldVec = oldIt.Get();

    for(unsigned int i=0; i<dirIndices.size(); i++)
    {
      // do the averaging
      const unsigned int numavg = dirIndices[i].size();
      unsigned int sum = 0;
      for(unsigned int j=0; j<numavg; j++)
      {
        //MITK_INFO << newVec[i] << " << " << oldVec[dirIndices[i].at(j)];
        sum += oldVec[dirIndices[i].at(j)];
      }
      if(numavg == 0)
      {
        MITK_ERROR << "VectorImage: Error on averaging. Possibly due to corrupted data";
        return;
      }
      newVec[i] = sum / numavg;
    }

    newIt.Set(newVec);

    ++newIt;
    ++oldIt;
  }

  mitk::GrabItkImageMemory( newITKImage, m_Image );

  m_Image->SetProperty( mitk::DiffusionPropertyHelper::GRADIENTCONTAINERPROPERTYNAME.c_str(), mitk::GradientDirectionsProperty::New( newDirs ) );
  m_Image->SetProperty( mitk::DiffusionPropertyHelper::ORIGINALGRADIENTCONTAINERPROPERTYNAME.c_str(), mitk::GradientDirectionsProperty::New( newDirs ) );
  ApplyMeasurementFrame();
  UpdateBValueMap();
  std::cout << std::endl;
}