示例#1
0
void transform(string inputFilename, string outputFilename)
{
    typedef itk::Image< TPixelType, N > ImageType;
    typedef itk::ImageFileReader< ImageType > ReaderType;
    typedef itk::ImageFileWriter< ImageType > WriterType;
    
	typename ReaderType::Pointer reader = ReaderType::New();
    itk::NiftiImageIO::Pointer io = itk::NiftiImageIO::New();
	reader->SetImageIO(io);
	reader->SetFileName(inputFilename);
    try {
        reader->Update();
    } catch( itk::ExceptionObject & e ) {
		std::cerr << "Exception caught while reading image " << std::endl;
		std::cerr << e << std::endl;
	}
    
    typename WriterType::Pointer writer = WriterType::New();
	writer->SetImageIO(io);
	writer->SetFileName(outputFilename);
	writer->SetInput(reader->GetOutput());
	try {
		writer->Update();
	} catch( itk::ExceptionObject & e ) {
		std::cerr << "Exception caught while writing image " << std::endl;
		std::cerr << e << std::endl;
	}
}
示例#2
0
文件: load.cpp 项目: tkuhlengel/Fish
void ReadFile(std::string filename, typename TImageType::Pointer image)
{
	typedef itk::ImageFileReader<TImageType> ReaderType;
	typename ReaderType::Pointer reader = ReaderType::New();

	reader->SetFileName(filename);
	reader->Update();

	image->Graft(reader->GetOutput());
}
template<class TImage> typename TImage::Pointer ttt::JSONTissueTrackingProject::readImage(const std::string & table, int frame) {
		typedef itk::ImageFileReader<TImage> ReaderType;
		typename ReaderType::Pointer reader = ReaderType::New();

		std::stringstream ssQuery, ssFileName;

		try {
			ssQuery << "SELECT fileName FROM " << table << " WHERE " << table
					<< ".idProject=? AND " << table << ".t=?";

			std::auto_ptr<sql::PreparedStatement> prep_stmt(
					m_DB->prepareStatement(ssQuery.str()));

			prep_stmt->setInt(1, m_ProjectID); //IDproject==2
			prep_stmt->setInt(2, frame); //IDproject==2
			prep_stmt->execute();

			std::auto_ptr<sql::ResultSet> res(prep_stmt->getResultSet());

			assert(res->next());

			std::string fileName = res->getString("fileName");

			ssFileName << m_WorkingDirectory << "/" << fileName;

			reader->SetFileName(ssFileName.str());
			;
			reader->Update();
			reader->GetOutput()->SetSpacing(m_Spacing);
			return reader->GetOutput();

		} catch (sql::SQLException &e) {
			/*
			 The MySQL Connector/C++ throws three different exceptions:

			 - sql::MethodNotImplementedException (derived from sql::SQLException)
			 - sql::InvalidArgumentException (derived from sql::SQLException)
			 - sql::SQLException (derived from std::runtime_error)
			 */
			cout << "# ERR: SQLException in " << __FILE__;
			//    cout << "(" << EXAMPLE_FUNCTION << ") on line " << __LINE__ << endl;
			/* Use what() (derived from std::runtime_error) to fetch the error message */
			cout << "# ERR: " << e.what();
			cout << " (MySQL error code: " << e.getErrorCode();
			cout << ", SQLState: " << e.getSQLState() << " )" << endl;

		}
		return NULL;
	}
示例#4
0
template <typename T> typename T::Pointer readImage(const char *filename)
{	
	printf("Reading %s ... \n",filename);	
	typedef typename itk::ImageFileReader<T> ReaderType;
	typename ReaderType::Pointer reader = ReaderType::New();
	ReaderType::GlobalWarningDisplayOff();	reader->SetFileName(filename);	
	try	{	
		reader->Update();	
	}	
	catch(itk::ExceptionObject &err)	{
		std::cerr << "ExceptionObject caught!" <<std::endl;
		std::cerr << err << std::endl;
		_exit(0);		
		//return EXIT_FAILURE;	
	}
	printf("Done\n");	return reader->GetOutput();
}
void DicomDiffusionImageReader<TPixelType, TDimension>
::GenerateOutputInformation(void)
{
  typename OutputImageType::Pointer output = this->GetOutput();
  typedef itk::ImageSeriesReader<InputImageType> ReaderType;

  // Read the first (or last) volume and use its size.
  if (m_Headers.size() > 0)
  {
    typename ReaderType::Pointer reader = ReaderType::New();

    try
    {
      // Read the image
      reader->SetFileNames (m_Headers[0]->m_DicomFilenames);
      reader->UpdateOutputInformation();

      output->SetSpacing( reader->GetOutput()->GetSpacing() );   // Set the image spacing
      output->SetOrigin( reader->GetOutput()->GetOrigin() );     // Set the image origin
      output->SetDirection( reader->GetOutput()->GetDirection() );  // Set the image direction
      output->SetLargestPossibleRegion( reader->GetOutput()->GetLargestPossibleRegion() );
      output->SetVectorLength( m_Headers.size() );
    }
    catch (itk::ExceptionObject &e)
    {
      throw e;
    }
  }
  else
  {
    itkExceptionMacro(<< "At least one filename is required." );
  }
}
示例#6
0
typename T::Pointer readImage(const std::string &filename)
{
	std::cout << "Reading " << filename << " ..." << std::endl;
	typedef typename itk::ImageFileReader<T> ReaderType;
	typename ReaderType::Pointer reader = ReaderType::New();

	ReaderType::GlobalWarningDisplayOff();
	reader->SetFileName(filename);
	try
	{
		reader->Update();
	}
	catch(itk::ExceptionObject &err)
	{
		std::cerr << "Exception object caught!" << std::endl;
		std::cerr << err << std::endl;
	}
	std::cout << "Done." << std::endl;
	return reader->GetOutput();
}
示例#7
0
    Volume* readScalarVolume(const std::string fileName) {
        typedef itk::Image<T,3> ImageNDType;
        typedef itk::ImageFileReader<ImageNDType> ReaderType;

        typename ReaderType::Pointer reader = ReaderType::New();
        reader->SetFileName(fileName.c_str());
        int status = 1;
        try
        {
            reader->Update();
            status = 0;
        }
        catch(itk::ExceptionObject &excp)
        {
            throw tgt::FileException("ITK Exception: " + std::string(excp.GetDescription()), fileName);
        }
        if (status)
        {
            throw tgt::FileException("Other error reading file using ITK!", fileName);
        }

        return ITKToVoreenCopy<T>(reader->GetOutput());
    }
mitk::BaseData::Pointer mitk::RawImageFileReaderService::TypedRead(const std::string& path, EndianityType endianity, int* size)
{
  typedef itk::Image< TPixel, VImageDimensions > ImageType;
  typedef itk::ImageFileReader< ImageType > ReaderType;
  typedef itk::RawImageIO< TPixel, VImageDimensions >  IOType;

  typename ReaderType::Pointer reader = ReaderType::New();
  typename IOType::Pointer io = IOType::New();

  io->SetFileDimensionality(VImageDimensions);

  for (unsigned short int dim = 0; dim < VImageDimensions; ++dim)
  {
    io->SetDimensions(dim, size[dim] );
  }

  if (endianity == LITTLE)
  {
    io->SetByteOrderToLittleEndian();
  }
  else if (endianity == BIG)
  {
    io->SetByteOrderToBigEndian();
  }
  else
  {
    MITK_INFO << "Warning: endianity not properly set. Resulting image might be incorrect";
  }

  reader->SetImageIO( io );
  reader->SetFileName(path);

  try
  {
    reader->Update();
  }
  catch( itk::ExceptionObject & err )
  {
    MITK_ERROR <<"An error occurred during the raw image reading process: ";
    MITK_INFO << err << std::endl;
  }

  mitk::Image::Pointer image = mitk::Image::New();
  mitk::CastToMitkImage(reader->GetOutput(), image);
  image->SetVolume(  reader->GetOutput()->GetBufferPointer());
  return image.GetPointer();
}
示例#9
0
int StartShConversion(int argc, char* argv[])
{
    ctkCommandLineParser parser;
    parser.setArgumentPrefix("--", "-");
    parser.addArgument("input", "i", ctkCommandLineParser::String, "MITK SH image", us::Any(), false);
    parser.addArgument("output", "o", ctkCommandLineParser::String, "MRtrix SH image", us::Any(), false);
    parser.addArgument("shOrder", "sh", ctkCommandLineParser::Int, "spherical harmonics order");

    map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
    if (parsedArgs.size()==0)
        return EXIT_FAILURE;

    string inFile = us::any_cast<string>(parsedArgs["input"]);
    string outFile = us::any_cast<string>(parsedArgs["output"]);

    try
    {

        typedef itk::Image< float, 4 > OutImageType;
        typedef itk::Image< itk::Vector< float, (shOrder*shOrder + shOrder + 2)/2 + shOrder >, 3 > InputImageType;

        typename InputImageType::Pointer itkInImage = InputImageType::New();
        typedef itk::ImageFileReader< InputImageType > ReaderType;
        typename ReaderType::Pointer reader = ReaderType::New();
        MITK_INFO << "reading " << inFile;
        reader->SetFileName(inFile.c_str());
        reader->Update();
        itkInImage = reader->GetOutput();

        // extract directions from fiber bundle
        typename itk::ShCoefficientImageExporter<float, shOrder>::Pointer filter = itk::ShCoefficientImageExporter<float,shOrder>::New();
        filter->SetInputImage(itkInImage);
        filter->GenerateData();
        OutImageType::Pointer outImage = filter->GetOutputImage();

        typedef itk::ImageFileWriter< OutImageType > WriterType;
        WriterType::Pointer writer = WriterType::New();
        MITK_INFO << "writing " << outFile;
        writer->SetFileName(outFile.c_str());
        writer->SetInput(outImage);
        writer->Update();

        MITK_INFO << "DONE";
    }
    catch (itk::ExceptionObject e)
    {
        MITK_INFO << e;
        return EXIT_FAILURE;
    }
    catch (std::exception e)
    {
        MITK_INFO << e.what();
        return EXIT_FAILURE;
    }
    catch (...)
    {
        MITK_INFO << "ERROR!?!";
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
void DicomDiffusionImageReader<TPixelType, TDimension>
::GenerateData()
{
  typedef itk::ImageSeriesReader<InputImageType> ReaderType;

  typename OutputImageType::Pointer output = this->GetOutput();

  typedef typename OutputImageType::RegionType   RegionType;
  RegionType requestedRegion = output->GetRequestedRegion();

  // Each file must have the same size.
  SizeType validSize = requestedRegion.GetSize();

  int numberOfVolumes = static_cast<int>(m_Headers.size());

  // Allocate the output buffer
  output->SetBufferedRegion( requestedRegion );
  output->Allocate();

  itk::ProgressReporter progress(this, 0, 
                            m_Headers.size(),
                            m_Headers.size());

  itk::ImageRegionIterator<OutputImageType> ot (output, requestedRegion );

  // Clear the eventual previous content of the MetaDictionary array
  //if( m_MetaDataDictionaryArray.size() )
  //  {
  //  for(unsigned int i=0; i<m_MetaDataDictionaryArray.size(); i++)
  //    {
  //    // each element is a raw pointer, delete them.
  //    delete m_MetaDataDictionaryArray[i];
  //    }
  //  }
  //m_MetaDataDictionaryArray.clear();

  typename OutputImageType::PixelType vec;

  for (int i = 0; i < numberOfVolumes; i ++)
    {
    
    MITK_INFO << "Loading volume " << i+1 << "/" << numberOfVolumes;
    typename ReaderType::Pointer reader = ReaderType::New();
    reader->SetFileNames(m_Headers[i]->m_DicomFilenames);
    reader->UpdateLargestPossibleRegion();

    if (reader->GetOutput()->GetRequestedRegion().GetSize() != validSize)
      {
      itkExceptionMacro(<< "Size mismatch!");
      }

    itk::ImageRegionConstIterator<InputImageType> it (reader->GetOutput(),
                                               reader->GetOutput()->GetLargestPossibleRegion());

    while (!it.IsAtEnd())
      {
        vec = ot.Get();
        vec.SetElement(i, it.Get());
        ot.Set(vec);
        ++it;
        ++ot;
      }
    ot = ot.Begin();
    progress.CompletedPixel();
    }
示例#11
0
int changeOrientationMethod(string inputFilename, string outputFilename, OrientationType orientation, bool changeOrientation, bool displayInitialOrientation, bool displayAvailableOrientation)
{
    typedef itk::Image< TPixelType, N >	ImageType;
    typedef itk::ImageFileReader<ImageType> ReaderType;
    typedef itk::ImageFileWriter<ImageType> WriterType;
    
    typename ReaderType::Pointer reader = ReaderType::New();
	itk::NiftiImageIO::Pointer io = itk::NiftiImageIO::New();
	reader->SetImageIO(io);
	reader->SetFileName(inputFilename);
    
    OrientImage<ImageType> orientationFilter;
    orientationFilter.setInputImage(reader->GetOutput());
    
	if (displayInitialOrientation)
    {
        try {
            io->SetFileName(inputFilename);
            io->ReadImageInformation();
            //reader->Update();
        } catch( itk::ExceptionObject & e ) {
            std::cerr << "Exception caught while reading input image " << std::endl;
            std::cerr << e << std::endl;
        }
        
        typename ImageType::DirectionType direction;
        vector<double> dir0 = io->GetDirection(0);
        for (int i=0; i<dir0.size(); i++)
            direction(i,0) = dir0[i];
        vector<double> dir1 = io->GetDirection(1);
        for (int i=0; i<dir1.size(); i++)
            direction(i,1) = dir1[i];
        vector<double> dir2 = io->GetDirection(2);
        for (int i=0; i<dir2.size(); i++)
            direction(i,2) = dir2[i];
        cout << direction << endl;
        cout << "Input image orientation : " << FlagToString(orientationFilter.getOrientationFromDirection(direction)) << endl;
    }
    
	if (changeOrientation)
	{
        try {
            io->SetFileName(inputFilename);
            io->ReadImageInformation();
            //reader->Update();
        } catch( itk::ExceptionObject & e ) {
            std::cerr << "Exception caught while reading input image " << std::endl;
            std::cerr << e << std::endl;
        }
        
		orientationFilter.orientation(orientation);
        
		typename WriterType::Pointer writer = WriterType::New();
		writer->SetImageIO(io);
		writer->SetFileName(outputFilename);
		writer->SetInput(orientationFilter.getOutputImage());
		try {
			writer->Write();
		} catch( itk::ExceptionObject & e ) {
			std::cerr << "Exception caught while writing output image " << std::endl;
			std::cerr << e << std::endl;
		}
	}
    return EXIT_SUCCESS;
}
示例#12
0
    // -----------------------------------------------------------------------------
    // This is the actual templated algorithm
    // -----------------------------------------------------------------------------
    void static Execute(ReadImage* filter, QString inputFile, IDataArray::Pointer outputIDataArray, DataContainer::Pointer m, QString attrMatName)
    {
      typename DataArrayType::Pointer outputDataPtr = boost::dynamic_pointer_cast<DataArrayType>(outputIDataArray);

      //convert arrays to correct type
      PixelType* outputData = static_cast<PixelType*>(outputDataPtr->getPointer(0));
      size_t numVoxels = outputDataPtr->getNumberOfTuples();

      //read image meta data and get pixel type
      itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO(inputFile.toLocal8Bit().constData(), itk::ImageIOFactory::ReadMode);
      imageIO->SetFileName(inputFile.toLocal8Bit().data());
      imageIO->ReadImageInformation();
      itk::ImageIOBase::IOPixelType pixelType = imageIO->GetPixelType();

      itk::ProcessObject::Pointer readerObject;

      //read based on pixel type
      switch(pixelType)
      {
        case itk::ImageIOBase::SCALAR:
        {
          typedef itk::Image<PixelType, ImageProcessing::ImageDimension> ImageType;
          typedef itk::ImageFileReader<ImageType> ReaderType;
          typename ReaderType::Pointer reader = ReaderType::New();
          reader->SetFileName(inputFile.toLocal8Bit().constData());
          reader->GetOutput()->GetPixelContainer()->SetImportPointer(outputData, numVoxels, false);
          readerObject = reader;
        }
        break;

        case itk::ImageIOBase::RGB:
        {
          typedef itk::Image<itk::RGBPixel<PixelType>, ImageProcessing::ImageDimension> ImageType;
          typedef itk::ImageFileReader<ImageType> ReaderType;
          typename ReaderType::Pointer reader = ReaderType::New();
          reader->SetFileName(inputFile.toLocal8Bit().constData());
          reader->GetOutput()->GetPixelContainer()->SetImportPointer(reinterpret_cast<itk::RGBPixel<PixelType>*>(outputData), numVoxels, false);
          readerObject = reader;
        }
        break;

        case itk::ImageIOBase::RGBA:
        {
          typedef itk::Image<itk::RGBAPixel<PixelType>, ImageProcessing::ImageDimension> ImageType;
          typedef itk::ImageFileReader<ImageType> ReaderType;
          typename ReaderType::Pointer reader = ReaderType::New();
          reader->SetFileName(inputFile.toLocal8Bit().constData());
          reader->GetOutput()->GetPixelContainer()->SetImportPointer(reinterpret_cast<itk::RGBAPixel<PixelType>*>(outputData), numVoxels, false);
          readerObject = reader;
        }
        break;
        /**
        case itk::ImageIOBase::FIXEDARRAY:
          {
            typedef itk::VectorImage<PixelType>, ImageProcessing::ImageDimension> ImageType;
            typedef itk::ImageFileReader<ImageType> ReaderType;
            typename ReaderType::Pointer reader = ReaderType::New();
            reader->SetFileName(inputFile.toLocal8Bit().constData());
            reader->GetOutput()->GetPixelContainer()->SetImportPointer(outputData, numVoxels, false);
            readerObject=reader;
          }break;
          */
        case itk::ImageIOBase::UNKNOWNPIXELTYPE:
        case itk::ImageIOBase::OFFSET:
        case itk::ImageIOBase::VECTOR:
        case itk::ImageIOBase::POINT:
        case itk::ImageIOBase::COVARIANTVECTOR:
        case itk::ImageIOBase::SYMMETRICSECONDRANKTENSOR:
        case itk::ImageIOBase::DIFFUSIONTENSOR3D:
        case itk::ImageIOBase::COMPLEX:
        case itk::ImageIOBase::FIXEDARRAY:
        case itk::ImageIOBase::MATRIX:
          break;
        default:
          filter->setErrorCondition(-2);
          QString message = QObject::tr("Unable to read image '%1'").arg(filter->getInputFileName());
          filter->notifyErrorMessage(filter->getHumanLabel(), message, filter->getErrorCondition());
          outputIDataArray->resize(0);
      }

      try
      {
        readerObject->Update();
      }
      catch( itk::ExceptionObject& err )
      {
        filter->setErrorCondition(-5);
        QString ss = QObject::tr("Failed to read image '%1': %2").arg(inputFile).arg(err.GetDescription());
        filter->notifyErrorMessage(filter->getHumanLabel(), ss, filter->getErrorCondition());
      }
    }