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);

}
示例#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
void setup_snapshot_image(string basename, ImageType::Pointer model)
{
   ImageType::SpacingType spacing = model->GetSpacing();
   spacing[0] /= constants::SnapshotImageZoom;
   spacing[1] /= constants::SnapshotImageZoom;
   spacing[2] /= constants::SnapshotImageZoom;

   g_snapshot_image = ImageType::New();
   g_snapshot_image->SetSpacing( spacing );
   g_snapshot_image->SetOrigin( model->GetOrigin() );

   ImageType::RegionType const& region = model->GetLargestPossibleRegion();
   ImageType::RegionType::SizeType size = region.GetSize();

   // size is in pixels
   ImageType::SizeType doubled_size(size);
   doubled_size[0] *= constants::SnapshotImageZoom;
   doubled_size[1] *= constants::SnapshotImageZoom;
   doubled_size[2] *= constants::SnapshotImageZoom;
   g_snapshot_image->SetRegions( doubled_size );

   g_snapshot_image->Allocate();

   s_snapshot_basename = basename;
}
示例#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);
	
}
// ------------------------------------------------------------------------
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();

}
// ------------------------------------------------------------------------
InitialTransformExtractor::TranslationType InitialTransformExtractor::ComputeTranslation(
    const ImageType::Pointer &image,
    const OptionsData &options)
{
    // set the offsets
    TranslationType translation;
    translation.Fill(0);
    translation[0] -= options.roiOffset[0];
    translation[1] -= options.roiOffset[1];
    translation[2] -= options.roiOffset[2];


    ImageType::PointType origin = image->GetOrigin();
    translation[0] -= origin[0];
    translation[1] -= origin[1];
    translation[2] -= origin[2];

    return translation;
}
// ------------------------------------------------------------------------
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;
}
  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
  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;
  }
        virtual ReadResult readImage(const std::string& file, const osgDB::ReaderWriter::Options* options) const
        {
            std::string ext = osgDB::getLowerCaseFileExtension(file);
            if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;

            std::string fileName = osgDB::findDataFile( file, options );
            if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;

            notice()<<"Reading DICOM file "<<fileName<<std::endl;

            typedef unsigned short PixelType;
            const unsigned int Dimension = 3;
            typedef itk::Image< PixelType, Dimension > ImageType;


            typedef itk::ImageFileReader< ImageType > ReaderType;
            ReaderType::Pointer reader = ReaderType::New();
            reader->SetFileName( fileName.c_str() );

            typedef itk::GDCMImageIO           ImageIOType;
            ImageIOType::Pointer gdcmImageIO = ImageIOType::New();
            reader->SetImageIO( gdcmImageIO );

            try
            {
                reader->Update();
            }
            catch (itk::ExceptionObject & e)
            {
                std::cerr << "exception in file reader " << std::endl;
                std::cerr << e.GetDescription() << std::endl;
                std::cerr << e.GetLocation() << std::endl;
                return ReadResult::ERROR_IN_READING_FILE;
            }
            
            ImageType::Pointer inputImage = reader->GetOutput();
            
            ImageType::RegionType region = inputImage->GetBufferedRegion();
            ImageType::SizeType size = region.GetSize();
            ImageType::IndexType start = region.GetIndex();
            
            //inputImage->GetSpacing();
            //inputImage->GetOrigin();
            
            unsigned int width = size[0];
            unsigned int height = size[1];
            unsigned int depth = size[2];
            
            osg::RefMatrix* matrix = new osg::RefMatrix;
            
            notice()<<"width = "<<width<<" height = "<<height<<" depth = "<<depth<<std::endl;
            for(unsigned int i=0; i<Dimension; ++i)
            {
                (*matrix)(i,i) = inputImage->GetSpacing()[i];
                (*matrix)(3,i) = inputImage->GetOrigin()[i];
            }
            
            osg::Image* image = new osg::Image;
            image->allocateImage(width, height, depth, GL_LUMINANCE, GL_UNSIGNED_BYTE, 1);

            unsigned char* data = image->data();            
            typedef itk::ImageRegionConstIterator< ImageType > IteratorType;
            IteratorType it(inputImage, region);
            
            it.GoToBegin();
            while (!it.IsAtEnd())
            {
                *data = it.Get();
                ++data;
                ++it;
            }
            
            image->setUserData(matrix);
            
            matrix->preMult(osg::Matrix::scale(double(image->s()), double(image->t()), double(image->r())));

            return image;
        }
示例#13
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);
}
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();
}
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
  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!");
      }
    }
  }
示例#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;
}
示例#20
0
int main( int argc, char* argv[] )
{
    if( argc != 3 )
    {
        std::cerr << "Usage: "<< std::endl;
        std::cerr << argv[0];
        std::cerr << " <InputFileName> n";
        std::cerr << std::endl;
        return EXIT_FAILURE;
    }



    int operations = atoi(argv[2]);
    //sscanf(&operations,"%d",argv[2]);
    //printf("%d\n", operations);

    itk::TimeProbe itkClock;
    double t0 = 0.0;
    double tf = 0.0;

    itk::MultiThreader::SetGlobalDefaultNumberOfThreads(1);

    // Loading file
    ReaderType::Pointer reader = ReaderType::New();
    reader->SetFileName( argv[1] );
    reader->Update();
    ImageType::Pointer image = reader->GetOutput();

#ifdef GPU
    GPUReaderType::Pointer gpureader = GPUReaderType::New();
    gpureader->SetFileName( argv[1] );
    gpureader->Update();
    GPUImageType::Pointer gpuImage = gpureader->GetOutput();
#endif


    saveFile((char*) "/tmp/itk_input.dcm", image);

    // Allocate output image
    ImageType::Pointer output = ImageType::New();
    ImageType::RegionType region = image->GetBufferedRegion();
    output->SetRegions( region );
    output->SetOrigin(  image->GetOrigin()  );
    output->SetSpacing( image->GetSpacing() );
    output->Allocate();


    // Negative
    typedef itk::UnaryFunctorImageFilter<ImageType,ImageType,
                  Negate<ImageType::PixelType,ImageType::PixelType> > NegateImageFilterType;
 
    NegateImageFilterType::Pointer negateFilter = NegateImageFilterType::New();

    negateFilter = NegateImageFilterType::New();
    negateFilter->SetInput(image);
#ifndef GPU_only
    itkClock.Start();
    TimerStart();
    for(int n = 0; n < operations; n++)
    {
      negateFilter->Modified();
      negateFilter->Update();    
    }
    itkClock.Stop();
    printf("Tempo gasto para fazer %d negative: %s\n",operations, getTimeElapsedInSeconds());
    tf = itkClock.GetTotal();
    std::cout << "My: "    << (tf - t0) << std::endl;
    t0 = tf;
#endif
    // Saving Not result
    saveFile((char*) "/tmp/itk_not.dcm", negateFilter->GetOutput());


#ifdef GPU
    // GPU Negative
    typedef itk::GPUUnaryFunctorImageFilter<ImageType,ImageType,
                  Negate<ImageType::PixelType,ImageType::PixelType> > GPUNegateImageFilterType;
 
    GPUNegateImageFilterType::Pointer gpuNegateFilter = GPUNegateImageFilterType::New();
    gpuNegateFilter->SetInput(gpureader->GetOutput());
    gpuNegateFilter->Update();    
    // Saving Not result
    //saveFile("/tmp/itk_gpu_not.dcm", gpuNegateFilter->GetOutput());
#endif

    // Common Threshold
    int lowerThreshold = 100;
    int upperThreshold = 200;


    // Threshold
    typedef itk::BinaryThresholdImageFilter <ImageType, ImageType>
       BinaryThresholdImageFilterType;
    
    BinaryThresholdImageFilterType::Pointer thresholdFilter
      = BinaryThresholdImageFilterType::New();

    thresholdFilter = BinaryThresholdImageFilterType::New();
    thresholdFilter->SetInput(reader->GetOutput());
    thresholdFilter->SetLowerThreshold(lowerThreshold);
    thresholdFilter->SetUpperThreshold(upperThreshold);
    thresholdFilter->SetInsideValue(255);
    thresholdFilter->SetOutsideValue(0);
#ifndef GPU_only
    itkClock.Start();
    TimerStart();
    for(int n = 0; n < operations; n++)
    {
	thresholdFilter->Modified();
	thresholdFilter->Update();
    }
    itkClock.Stop();
    printf("Tempo gasto para fazer %d threshold: %s\n",operations, getTimeElapsedInSeconds());
    tf = itkClock.GetTotal();
    std::cout << "My: "    << (tf - t0) << std::endl;
    t0 = tf;
    // Saving Threshold result
    saveFile((char*) "/tmp/itk_thresh.dcm", thresholdFilter->GetOutput());
#endif


#ifdef GPU
    // GPU Threshold

    typedef itk::GPUBinaryThresholdImageFilter <GPUImageType, GPUImageType> 
			GPUBinaryThresholdImageFilterType;
    
    GPUBinaryThresholdImageFilterType::Pointer gpuThresholdFilter
      = GPUBinaryThresholdImageFilterType::New();

    gpuThresholdFilter->SetInput(gpureader->GetOutput());
    gpuThresholdFilter->SetLowerThreshold(lowerThreshold);
    gpuThresholdFilter->SetUpperThreshold(upperThreshold);
    gpuThresholdFilter->SetInsideValue(255);
    gpuThresholdFilter->SetOutsideValue(0);

    itkClock.Start();
    TimerStart();
    for(int n = 0; n < operations; n++)
    {
      gpuThresholdFilter->Modified();
      gpuThresholdFilter->Update();
    }
    itkClock.Stop();
    printf("Tempo gasto para fazer %d GPU threshold: %s\n",operations, getTimeElapsedInSeconds());
    tf = itkClock.GetTotal();
    std::cout << "My: "    << (tf - t0) << std::endl;
    t0 = tf;
    // Saving GPU Threshold result
    gpuThresholdFilter->GetOutput()->UpdateBuffers();
    saveFile((char*) "/tmp/itk_gpu_thresh.dcm", gpuThresholdFilter->GetOutput());
#endif

    // Mean
    typedef itk::MeanImageFilter< ImageType, ImageType > MeanFilterType;
    MeanFilterType::Pointer meanFilter = MeanFilterType::New();

    meanFilter = MeanFilterType::New();
    meanFilter->SetInput( image );
    meanFilter->SetRadius( 1 );
#ifndef GPU_only
    itkClock.Start();
    TimerStart();
    for(int n = 0; n < operations; n++)
    {
       meanFilter->Modified();
       meanFilter->Update();
    }
    itkClock.Stop();
    printf("Tempo gasto para fazer %d mean blur: %s\n",operations, getTimeElapsedInSeconds());
    tf = itkClock.GetTotal();
    std::cout << "My: "    << (tf - t0) << std::endl;
    t0 = tf;
    // Saving Convolution result
    saveFile((char*) "/tmp/itk_mean3x3.dcm", meanFilter->GetOutput());
#endif

    // Binomial Blur (aproximation of gaussian blur)
    typedef itk::BinomialBlurImageFilter<ImageType, ImageType> BinomialBlurImageFilterType;
 
    int repetitions = 1;
    BinomialBlurImageFilterType::Pointer blurFilter = BinomialBlurImageFilterType::New();

    blurFilter = BinomialBlurImageFilterType::New();
    blurFilter->SetInput( reader->GetOutput() );
    blurFilter->SetRepetitions( repetitions );
#ifndef GPU_only
    itkClock.Start();
    TimerStart();
    for(int n = 0; n < operations; n++)
    {
      blurFilter->Modified();
      blurFilter->Update();
    }
    itkClock.Stop();
    printf("Tempo gasto para fazer %d blur: %s\n",operations, getTimeElapsedInSeconds());
    tf = itkClock.GetTotal();
    std::cout << "My: "    << (tf - t0) << std::endl;
    t0 = tf;
    // Saving Blur result
    saveFile((char*) "/tmp/itk_blur.dcm", blurFilter->GetOutput());
#endif


#ifdef GPU
    // GPU Blur
    typedef itk::BoxImageFilter< GPUImageType, GPUImageType > BoxImageFilterType;
    typedef itk::GPUBoxImageFilter< GPUImageType, GPUImageType, BoxImageFilterType > GPUBoxImageFilterType;

    GPUBoxImageFilterType::Pointer GPUBlurFilter = GPUBoxImageFilterType::New();

	//ImageType::SizeType indexRadius;
	//indexRadius[0] = 2;
	//indexRadius[1] = 2;
	//indexRadius[2] = 2;

    GPUBlurFilter->SetInput(gpureader->GetOutput());
	//GPUBlurFilter->SetRadius(indexRadius);
    itkClock.Start();
    TimerStart();
    for(int n = 0; n < operations; n++)
    {
        GPUBlurFilter->Update();
        GPUBlurFilter->Modified();
    }
    itkClock.Stop();
    printf("Tempo gasto para fazer %d gpu blur: %s\n",operations, getTimeElapsedInSeconds());
    tf = itkClock.GetTotal();
    std::cout << "My: "    << (tf - t0) << std::endl;
    t0 = tf;
    GPUBlurFilter->GetOutput()->UpdateBuffers();
    // Saving GPU Blur result
    saveFile((char*) "/tmp/itk_gpu_blur.dcm", GPUBlurFilter->GetOutput());

#endif


    //Erosion Common
    typedef itk::BinaryBallStructuringElement<
      ImageType::PixelType, 3>                  StructuringElementType;
    typedef itk::GrayscaleErodeImageFilter <ImageType, ImageType, StructuringElementType>
      GrayscaleErodeImageFilterType;
    unsigned int radius;

    // Erosion 3x3
    StructuringElementType structuringElement3x3;
    radius = 1;
    structuringElement3x3.SetRadius(radius);
    structuringElement3x3.CreateStructuringElement();

    GrayscaleErodeImageFilterType::Pointer erodeFilter3x3;

    erodeFilter3x3= GrayscaleErodeImageFilterType::New();
    erodeFilter3x3->SetInput(reader->GetOutput());
    erodeFilter3x3->SetKernel(structuringElement3x3);
#ifndef GPU_only
    itkClock.Start();
    TimerStart();
    for(int n = 0; n < operations; n++)
    {
        erodeFilter3x3->Modified();
        erodeFilter3x3->Update();
    }
    itkClock.Stop();
    printf("Tempo gasto para fazer %d erosion 3x3: %s\n",operations, getTimeElapsedInSeconds());
    tf = itkClock.GetTotal();
    std::cout << "My: "    << (tf - t0) << std::endl;
    t0 = tf;

    // Saving Erosion result
    saveFile((char*) "/tmp/itk_erode3x3.dcm", erodeFilter3x3->GetOutput());
#endif

    // Erosion 5x5
    StructuringElementType structuringElement5x5;
    radius = 2;
    structuringElement5x5.SetRadius(radius);
    structuringElement5x5.CreateStructuringElement();

    GrayscaleErodeImageFilterType::Pointer erodeFilter5x5;

    erodeFilter5x5 = GrayscaleErodeImageFilterType::New();
    erodeFilter5x5->SetInput(reader->GetOutput());
    erodeFilter5x5->SetKernel(structuringElement5x5);
#ifndef GPU_only
    itkClock.Start();
    TimerStart();
    for(int n = 0; n < operations; n++)
    {
      erodeFilter5x5->Modified();
      erodeFilter5x5->Update();
    }
    itkClock.Stop();
    printf("Tempo gasto para fazer %d erosion 5x5: %s\n",operations, getTimeElapsedInSeconds());
    tf = itkClock.GetTotal();
    std::cout << "My: "    << (tf - t0) << std::endl;
    t0 = tf;

    // Saving Erosion result
    saveFile((char*) "/tmp/itk_erode5x5.dcm", erodeFilter5x5->GetOutput());
#endif

    // Copy
    typedef itk::ImageDuplicator< ImageType > DuplicatorType;
    DuplicatorType::Pointer duplicator;

    duplicator = DuplicatorType::New();
    duplicator->SetInputImage(image);
#ifndef GPU_only
    itkClock.Start();
    TimerStart();
    for(int n = 0; n < operations; n++)
    { 
       duplicator->Modified();
       duplicator->Update();
    }
    itkClock.Stop();
    printf("Tempo gasto para fazer %d copias cpu: %s\n",operations, getTimeElapsedInSeconds());
    tf = itkClock.GetTotal();
    std::cout << "My: "    << (tf - t0) << std::endl;
    t0 = tf;
    // Saving Copy result
    saveFile((char*) "/tmp/itk_copy.dcm", duplicator->GetOutput());
#endif

    // Convolution common
    typedef itk::ConvolutionImageFilter<ImageType> ConvolutionImageFilterType;

    ConvolutionImageFilterType::Pointer convolutionFilter;

    convolutionFilter = ConvolutionImageFilterType::New();
    convolutionFilter->SetInput(reader->GetOutput());
    int convWidth;

    // Convolution 3x3
    ImageType::Pointer kernel3x3 = ImageType::New();
    convWidth = 3;
    CreateKernel(kernel3x3, convWidth);

    convolutionFilter->SetKernelImage(kernel3x3);
#ifndef GPU_only
    itkClock.Start();
    TimerStart();
    for(int n = 0; n < operations; n++)
    {  
       convolutionFilter->Modified();
       convolutionFilter->Update();
    }
    itkClock.Stop();
    printf("Tempo gasto para fazer %d convolucoes 3x3 cpu: %s\n",operations, getTimeElapsedInSeconds());
    tf = itkClock.GetTotal();
    std::cout << "My: "    << (tf - t0) << std::endl;
    t0 = tf;
    // Saving Convolution result
    saveFile((char*) "/tmp/itk_convolution3x3.dcm", convolutionFilter->GetOutput());
#endif

    // Convolution 5x5
    ImageType::Pointer kernel5x5 = ImageType::New();
    convWidth = 5;
    CreateKernel(kernel5x5, convWidth);

    convolutionFilter->SetKernelImage(kernel5x5);
#ifndef GPU_only
    itkClock.Start();
    TimerStart();
    for(int n = 0; n < operations; n++)
    {  
       convolutionFilter->Modified();
       convolutionFilter->Update();
    }
    itkClock.Stop();
    printf("Tempo gasto para fazer %d convolucoes 5x5 cpu: %s\n",operations, getTimeElapsedInSeconds());
    tf = itkClock.GetTotal();
    std::cout << "My: "    << (tf - t0) << std::endl;
    t0 = tf;
    // Saving Convolution result
    saveFile((char*) "/tmp/itk_convolution5x5.dcm", convolutionFilter->GetOutput());
#endif

#ifdef GPU

    // GPU Mean
    typedef itk::GPUMeanImageFilter<GPUImageType, GPUImageType> GPUMeanFilterType;
	GPUMeanFilterType::Pointer GPUMean = GPUMeanFilterType::New();
	GPUMean->SetInput(gpureader->GetOutput());
	GPUMean->SetRadius( 1 );
	TimerStart();
	for(int n = 0; n < operations; n++)
	{
	   GPUMean->Update();
	   GPUMean->Modified();
	}
    itkClock.Stop();
    printf("Tempo gasto para fazer %d GPU mean blur: %s\n",operations, getTimeElapsedInSeconds());
    tf = itkClock.GetTotal();
    std::cout << "My: "    << (tf - t0) << std::endl;
    t0 = tf;
	GPUMean->GetOutput()->UpdateBuffers();
    saveFile((char*) "/tmp/itk_gpu_blurmean.dcm", GPUMean->GetOutput());
#endif

    // Visualize
    /*
    QuickView viewer;
    viewer.AddImage<ImageType>(
      image,true,
      itksys::SystemTools::GetFilenameName(argv[1]));  
    std::stringstream desc;
    desc << "ITK QuickView: " 
         << argv[1];
    viewer.Visualize();
    */

    // Saving input image as is
    saveFile((char*) "/tmp/itk_input.dcm", image);


    return EXIT_SUCCESS;
}