Beispiel #1
0
void TDimImage::fromItkImage( const ImageType *image ) {
  
  ImageType::RegionType region;
  region = image->GetBufferedRegion();
  ImageType::SizeType size = region.GetSize();
  ImageType::IndexType start = region.GetIndex();
  unsigned int nx = size[0];
  unsigned int ny = size[1];

  // allocate this image
  if (this->alloc( nx, ny, 1, sizeof(PixelType))<=0) return;

  // copy data
  typedef itk::ImageRegionConstIterator< ImageType >  IteratorType;
  IteratorType it( image, region );
  it.GoToBegin();
  const PixelType *data = (PixelType *) this->sampleBits(0);
  while( !it.IsAtEnd() ) {
    *data = it.Get();
    ++it;
    ++data;
  }
}
void mitk::AutoCropImageFilter::ComputeNewImageBounds()
{
  mitk::Image::ConstPointer inputMitk = this->GetInput();

  if (m_OverrideCroppingRegion)
  {
    for (unsigned int i=0; i<3; ++i)
    {
      m_RegionIndex[i] = m_CroppingRegion.GetIndex()[i];
      m_RegionSize[i] = m_CroppingRegion.GetSize()[i];

      if (m_RegionIndex[i] >= inputMitk->GetDimension(i))
      {
        itkExceptionMacro("Cropping index is not inside the image. "
                       << std::endl << "Index:"
                       << std::endl << m_CroppingRegion.GetIndex()
                       << std::endl << "Size:"
                       << std::endl << m_CroppingRegion.GetSize());
      }

      if (m_RegionIndex[i] + m_RegionSize[i] >= inputMitk->GetDimension(i))
      {
        m_RegionSize[i] = inputMitk->GetDimension(i) - m_RegionIndex[i];
      }
    }

    for (unsigned int i=0; i<3; ++i)
    {
      m_RegionIndex[i] = m_CroppingRegion.GetIndex()[i];
      m_RegionSize[i] = m_CroppingRegion.GetSize()[i];
    }
  }
  else
  {
    // Check if a 3D or 4D image is present
    unsigned int timeSteps = 1;
    if (inputMitk->GetDimension() == 4 )
      timeSteps = inputMitk->GetDimension(3);

    ImageType::IndexType minima,maxima;

    if (inputMitk->GetDimension() == 4)
    {
      // initialize with time step 0
      m_TimeSelector = mitk::ImageTimeSelector::New();
      m_TimeSelector->SetInput( inputMitk );
      m_TimeSelector->SetTimeNr( 0 );
      m_TimeSelector->UpdateLargestPossibleRegion();
      inputMitk = m_TimeSelector->GetOutput();
    }

    ImagePointer inputItk = ImageType::New();
    mitk::CastToItkImage( inputMitk , inputItk );

    // it is assumed that all volumes in a time series have the same 3D dimensions
    ImageType::RegionType origRegion = inputItk->GetLargestPossibleRegion();

    // Initialize min and max on the first (or only) time step
    maxima = inputItk->GetLargestPossibleRegion().GetIndex();
    minima[0] = inputItk->GetLargestPossibleRegion().GetSize()[0];
    minima[1] = inputItk->GetLargestPossibleRegion().GetSize()[1];
    minima[2] = inputItk->GetLargestPossibleRegion().GetSize()[2];

    typedef itk::ImageRegionConstIterator< ImageType > ConstIteratorType;

    for(unsigned int idx = 0; idx < timeSteps; ++idx)
    {
       // if 4D image, update time step and itk image
      if( idx > 0)
      {
        m_TimeSelector->SetTimeNr( idx );
        m_TimeSelector->UpdateLargestPossibleRegion();
        inputMitk = m_TimeSelector->GetOutput();
        mitk::CastToItkImage( inputMitk , inputItk );
      }

      ConstIteratorType inIt( inputItk,  origRegion );

      for ( inIt.GoToBegin(); !inIt.IsAtEnd(); ++inIt)
      {
        float pix_val = inIt.Get();
        if ( fabs(pix_val - m_BackgroundValue) > mitk::eps )
        {
          for (int i=0; i < 3; i++)
          {
            minima[i] = vnl_math_min((int)minima[i],(int)(inIt.GetIndex()[i]));
            maxima[i] = vnl_math_max((int)maxima[i],(int)(inIt.GetIndex()[i]));
          }
        }
      }
    }

    typedef ImageType::RegionType::SizeType::SizeValueType  SizeValueType;

    m_RegionSize[0] = (SizeValueType)(m_MarginFactor * (maxima[0] - minima[0] + 1 ));
    m_RegionSize[1] = (SizeValueType)(m_MarginFactor * (maxima[1] - minima[1] + 1 ));
    m_RegionSize[2] = (SizeValueType)(m_MarginFactor * (maxima[2] - minima[2] + 1 ));
    m_RegionIndex = minima;

    m_RegionIndex[0] -= (m_RegionSize[0] - maxima[0] + minima[0] - 1 )/2;
    m_RegionIndex[1] -= (m_RegionSize[1] - maxima[1] + minima[1] - 1 )/2;
    m_RegionIndex[2] -= (m_RegionSize[2] - maxima[2] + minima[2] - 1 )/2;

    ImageType::RegionType cropRegion(m_RegionIndex,m_RegionSize);
    origRegion.Crop(cropRegion);

    m_RegionSize[0] = origRegion.GetSize()[0];
    m_RegionSize[1] = origRegion.GetSize()[1];
    m_RegionSize[2] = origRegion.GetSize()[2];

    m_RegionIndex[0] = origRegion.GetIndex()[0];
    m_RegionIndex[1] = origRegion.GetIndex()[1];
    m_RegionIndex[2] = origRegion.GetIndex()[2];

    m_CroppingRegion = origRegion;
  }
}
        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;
        }
int main(int, char ** argv)
{
	std::string inputFolder = argv[1];
	std::string outputFolder = argv[2];
	std::string lookupFilename = argv[3];


	// load the lookup file and read the image filenames
	LookupMap lookup;
	FilenamesType imageFilenames;
	readFilenames(inputFolder, imageFilenames);
	loadLookupFile(lookupFilename, lookup);

	// looop through the list of images
	for(unsigned int i = 0; i < imageFilenames.size(); i++)
	{
		std::string fname = imageFilenames[i];
		QFileInfo finfo(QString::fromStdString(fname));
		std::string basename = finfo.completeBaseName().toStdString() + ".nrrd";
		FilenamesType dicomFilenames = lookup[basename];

		// slice up the input image to recreate the output
		typedef utils::ImageVolume ImageType;
		ImageType::Pointer input = utils::ImageVolumeIO::Read(fname);

		const unsigned int slices = input->GetLargestPossibleRegion().GetSize()[2];

		for(unsigned int slice = 0; slice < slices; slice++)
		{
			typedef itk::RegionOfInterestImageFilter<ImageType, ImageType> ROIFilter;
			ROIFilter::Pointer roiFilter = ROIFilter::New();
			roiFilter->SetInput(input);

			ImageType::RegionType roi = input->GetLargestPossibleRegion();
			ImageType::IndexType roiIndex = roi.GetIndex();
			ImageType::SizeType roiSize = roi.GetSize();

			roiIndex[2] = slice;
			roiSize[2] = 1;
			roi.SetSize(roiSize);
			roi.SetIndex(roiIndex);

			roiFilter->SetRegionOfInterest(roi);
			roiFilter->Update();

			ImageType::Pointer imSlice = roiFilter->GetOutput();


			// load the dicom file
			std::string dicomFilename = dicomFilenames[slice];
			DcmFileFormat fileFormat;
			fileFormat.loadFile(dicomFilename.c_str());

			unsigned int numberOfPixels = imSlice->GetLargestPossibleRegion().GetNumberOfPixels();
			unsigned short * buffer = new unsigned short[numberOfPixels];
			fileFormat.getDataset()->putAndInsertUint16Array(DCM_PixelData, buffer, imSlice->GetLargestPossibleRegion().GetNumberOfPixels());

			// reset the pixel values
			itk::ImageRegionConstIterator<ImageType> it(imSlice, imSlice->GetLargestPossibleRegion());
			unsigned int count = 0;
			while(!it.IsAtEnd())
			{
				buffer[count] = it.Get();
				++it; ++count;
			}
			
			fileFormat.getDataset()->putAndInsertUint16Array(DCM_PixelData, buffer, imSlice->GetLargestPossibleRegion().GetNumberOfPixels());
			// create the output filename 
			std::stringstream ss;
			ss << outputFolder << "/dicom_" << i << "_" << slice << ".dcm";


			fileFormat.saveFile(ss.str().c_str());
		}
	}

	return 0;
}
void MyImageClass::SaveDICOMSeries(QString save_path, std::string subfolder)
{
    std::string output_directory = save_path.toStdString();
    output_directory +=subfolder;

    itksys::SystemTools::MakeDirectory( output_directory.c_str() );

    typedef signed short OutputPixelType;
    const unsigned int output_pixel_dimension = 2;

    typedef itk::Image < OutputPixelType, output_pixel_dimension > Image2Dtype;
    typedef itk::CastImageFilter<InternalImageType, ImageType> CastFilterType;

    typedef itk::ImageSeriesWriter < ImageType, Image2Dtype> SeriesWriterType;


    CastFilterType::Pointer caster = CastFilterType::New();
    SeriesWriterType::Pointer series_writer = SeriesWriterType::New();

    typedef itk::NumericSeriesFileNames NumericNamesGeneratorType;

    NumericNamesGeneratorType::Pointer namesGenerator = NumericNamesGeneratorType::New();

    itk::MetaDataDictionary &dict = gdcmIO_->GetMetaDataDictionary();
    std::string tagkey,value;
    tagkey = "0008|0060";
    value = "MR";
    itk::EncapsulateMetaData<std::string>(dict,tagkey,value);
    tagkey = "0008|0008";
    value = "DERIVED\\SECONDARY";
    itk::EncapsulateMetaData<std::string>(dict,tagkey,value);
    tagkey = "0008|0064";
    value = "DV";
    itk::EncapsulateMetaData<std::string>(dict,tagkey,value);

    caster->SetInput(reader_->GetOutput());
    series_writer->SetInput( caster->GetOutput());
    series_writer->SetImageIO(gdcmIO_);

    ImageType::RegionType region = reader_->GetOutput()->GetLargestPossibleRegion();
    ImageType::IndexType start = region.GetIndex();
    ImageType::SizeType size = region.GetSize();

    std::string format = output_directory;
    format += "/image%03d.dcm";

    namesGenerator->SetSeriesFormat(format.c_str());

    namesGenerator->SetStartIndex(start[2]);
    namesGenerator->SetEndIndex(start[2]+size[2]-1);
    namesGenerator->SetIncrementIndex(1);

    series_writer->SetFileNames (namesGenerator->GetFileNames());

    series_writer->SetMetaDataDictionaryArray(reader_->GetMetaDataDictionaryArray());

    try
    {
        series_writer->Update();
    }
    catch( itk::ExceptionObject &excp)
    {
        msg_box_.setText(excp.GetDescription());
        msg_box_.exec();
    }

}
bool VolumeProcess::DialateImage(int iterations)
{
	int border = 2;

	ImageType::Pointer tempImg = ImageType::New();
	tempImg->SetRegions( m_outputImage->GetLargestPossibleRegion() );
	tempImg->Allocate();
	tempImg->FillBuffer(0);

	ImageType::RegionType fullRegion = m_outputImage->GetBufferedRegion();
	ImageType::RegionType borderRegion;
	borderRegion.SetIndex(0, fullRegion.GetIndex(0)+border);
	borderRegion.SetIndex(1, fullRegion.GetIndex(1)+border);
	borderRegion.SetIndex(2, fullRegion.GetIndex(2)+border);
	borderRegion.SetSize(0, fullRegion.GetSize(0)-(2*border));
	borderRegion.SetSize(1, fullRegion.GetSize(1)-(2*border));
	borderRegion.SetSize(2, fullRegion.GetSize(2)-(2*border));
	itk::ImageRegionIteratorWithIndex< ImageType > itr( m_outputImage, borderRegion );
	while(iterations > 0)
	{
		for(itr.GoToBegin(); !itr.IsAtEnd(); ++itr)
		{
			double blockMax = itr.Get();
			for(int k=-1; k<=1; k++)
			{
				for(int j=-1; j<=1; j++)
				{
					for(int i=-1; i<=1; i++)
					{
						ImageType::IndexType index = itr.GetIndex();
						index[0] += i;
						index[1] += j;
						index[2] += k;
						ImageType::PixelType pix = m_outputImage->GetPixel(index);
						if((double)pix > blockMax) 
						{
							blockMax = (double)pix;
						}
					}
				}
			}
			// Keep the peak of the original intensity
			if (blockMax == itr.Get() && blockMax != 0)
            {
				blockMax = blockMax + 1;
            }
			tempImg->SetPixel(itr.GetIndex(), blockMax);
		}

		//Copy temp img back to image for next dialation
		itk::ImageRegionIterator< ImageType > itr1( tempImg, tempImg->GetLargestPossibleRegion() );
		itk::ImageRegionIterator< ImageType > itr2( m_outputImage, m_outputImage->GetLargestPossibleRegion() );
		for(itr1.GoToBegin(), itr2.GoToBegin() ; !itr1.IsAtEnd(); ++itr1, ++itr2)
		{
			itr2.Set( itr1.Get() );
		}

		iterations--;
	}
	
	if(debug)
		std::cerr << "Dialation Done" << std::endl;
	return true;
}