示例#1
0
MriWatcherGUI::ImageType::Pointer MriWatcherGUI::CreateNewImage(int sizex, int sizey, int sizez, float dimx, float dimy,
                                                                float dimz)
{
  int imagesize[3];

  imagesize[0] = sizex;
  imagesize[1] = sizey;
  imagesize[2] = sizez;

  ImageType::Pointer m_outputimage = ImageType::New();
  float              values[3];

  values[0] = dimx;
  values[1] = dimy;
  values[2] = dimz;

  float origin_x = ( (imagesize[0] / 2) * values[0] * (-1) );
  float origin_y = ( (imagesize[1] / 2) * values[1] * (-1) );
  float origin_z = ( (imagesize[0] / 2) * values[2] * (-1) );
  float origin[3] = {origin_x, origin_y, origin_z};

  ImageType::RegionType region;
  ImageType::SizeType   size;
  size[0] = imagesize[0];
  size[1] = imagesize[1];
  size[2] = imagesize[2];
  region.SetSize( size );
  m_outputimage->SetRegions( region );
  m_outputimage->Allocate();
  m_outputimage->SetOrigin(origin);
  m_outputimage->SetSpacing(values);

  return m_outputimage;
}
bool VolumeProcess::RunBinaryForDistanceMapUsingGraphCuts()
{
	ImageType::RegionType region = m_outputImage->GetBufferedRegion();
	int numColumns = region.GetSize(0);
	int numRows = region.GetSize(1);
	int numStacks = region.GetSize(2);
	long numPix = numStacks*numColumns*numRows;

	unsigned short * binImagePtr = new unsigned short[numPix];
	PixelType * dataImagePtr = m_outputImage->GetBufferPointer();

	//int ok = Cell_Binarization_3D(dataImagePtr, binImagePtr, numRows, numColumns, numStacks, 0, 1);	//Do Binarization
    int ok = Neuron_Binarization_3D(dataImagePtr, binImagePtr, numRows, numColumns, numStacks, 0, 1);
	if(!ok)
		return false;

	// background is bright and forground is dark:
	for(long i=0; i<numPix; ++i)
	{
		if( binImagePtr[i] == 0 )
		{
			dataImagePtr[i] = 255;
		}
		else 
            dataImagePtr[i] = 0;
	}

	delete [] binImagePtr;

	return true;
}
示例#3
0
void CreateKernel(ImageType::Pointer kernel, unsigned int width)
{
  ImageType::IndexType start;
  start.Fill(0);
 
  ImageType::SizeType size;
  size.Fill(width);
 
  ImageType::RegionType region;
  region.SetSize(size);
  region.SetIndex(start);
 
  kernel->SetRegions(region);
  kernel->Allocate();
 
  itk::ImageRegionIterator<ImageType> imageIterator(kernel, region);
 
   while(!imageIterator.IsAtEnd())
    {
    //imageIterator.Set(255);
    imageIterator.Set(1);
 
    ++imageIterator;
    }
}
示例#4
0
ImageType::Pointer TDimImage::toItkImage( const unsigned int &channel ) const {

  int sample = std::min<int>( this->samples()-1, channel); 
  int bitdepth = sizeof(PixelType);
  D_DataFormat pf = D_FMT_UNSIGNED;
  if (!std::numeric_limits<PixelType>::is_integer) 
    pf = D_FMT_FLOAT;
  else
  if (std::numeric_limits<PixelType>::is_signed) 
    pf = D_FMT_SIGNED;
  
  TDimImage img;
  if (this->depth()!=bitdepth || this->pixelType()!=pf) {
    img = this->ensureTypedDepth();
    img = img.convertToDepth( bitdepth, DimLut::ltLinearDataRange, pf );
  } else
    img = *this;

  //------------------------------------------------------------------
  // Create Itk Image and copy data
  //------------------------------------------------------------------
  ImageType::Pointer image = ImageType::New();
  ImageType::SizeType size;
  size[0] = nx;
  size[1] = ny;

  ImageType::IndexType start;
  start[0] = 0;
  start[1] = 0;  

  ImageType::RegionType region;
  region.SetSize( size );
  region.SetIndex( start );
  image->SetRegions( region );

  image->Allocate();

  double spacing[2];
  spacing[0] = 1.0;
  spacing[1] = 1.0;
  image->SetSpacing( spacing );

  double origin[2];
  origin[0] = 0.0;
  origin[1] = 0.0;
  image->SetOrigin( origin );

  typedef itk::ImageRegionIterator< ImageType >  IteratorType;
  IteratorType it( image, region );
  it.GoToBegin();

  // copy data
  PixelType *data = (PixelType *) img.sampleBits(sample);
  while( ! it.IsAtEnd() ) {
    it.Set( *data );
    ++it;
    ++data;
  }
  return image;
}
示例#5
0
int main()
{
	std::string votesfilename = "../../half_vessel_votes2.txt";
	std::string outputfilename = "half_vessel_votes2.tif";
	FILE * fp = fopen(votesfilename.c_str(), "r");


	int x,y,z,v;
	int maxx = -1,maxy = -1, maxz = -1;
	while(fscanf(fp,"%d %d %d %d",&x,&y,&z,&v)>0)
	{
		maxx = MAX(maxx, x);
		maxy = MAX(maxy, y);
		maxz = MAX(maxz, z);
	}

	printf("maxx = %d maxy = %d maxz = %d\n",maxx,maxy,maxz);
	fclose(fp);


	fp = fopen(votesfilename.c_str(), "r");


	ImageType::Pointer im = ImageType::New();

	ImageType::SizeType size;
	ImageType::IndexType index;
	ImageType::RegionType region;

	size[0] = maxx+1;
	size[1] = maxy+1;
	size[2] = maxz+1;

	index[0] = index[1] = index[2] = 0;

	region.SetIndex(index);
	region.SetSize(size);
	im->SetRegions(region);
	im->Allocate();

	while(fscanf(fp,"%d %d %d %d",&x,&y,&z,&v)>0)
	{
		index[0] = x;
		index[1] = y;
		index[2] = z;
		im->SetPixel(index,v);
	}

	//	scanf("%*d");

	fclose(fp);

	FileWriterType::Pointer writer = FileWriterType::New();
	writer->SetFileName(outputfilename.c_str());
	writer->SetInput(im);
	writer->Update();


	return 0;
}
示例#6
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;
		}
	}
}
  void setUp()
  {
    typedef itk::Image<double, 3> ImageType;
    typedef itk::VectorImage<double, 3> VectorImageType;
    typedef itk::ImageRegionIterator<ImageType> ImageIteratorType;
    typedef itk::ImageDuplicator<ImageType> DuplicatorType;
    typedef itk::ComposeImageFilter<ImageType> CompositeFilterType;

    // generate two images with one component
    ImageType::Pointer imageComponent1 = itk::Image<double, 3>::New();
    ImageType::IndexType start;
    start.Fill(0);
    ImageType::SizeType size;
    size.Fill(5);
    ImageType::RegionType region;
    region.SetSize(size);
    region.SetIndex(start);
    imageComponent1->SetRegions(region);
    imageComponent1->Allocate();

    DuplicatorType::Pointer duplicator = DuplicatorType::New();
    duplicator->SetInputImage(imageComponent1);
    duplicator->Update();
    ImageType::Pointer imageComponent2 = duplicator->GetOutput();

    // give them differing data
    ImageIteratorType iterator1(imageComponent1, imageComponent1->GetLargestPossibleRegion());
    iterator1.GoToBegin();
    int i = 0;
    while (!iterator1.IsAtEnd())
    {
      iterator1.Set((double)i);
      ++iterator1;
      ++i;
    }

    ImageIteratorType iterator2(imageComponent2, imageComponent2->GetLargestPossibleRegion());
    iterator2.GoToBegin();
    i = 2000;
    while (!iterator2.IsAtEnd())
    {
      iterator2.Set((double)i);
      ++iterator2;
      ++i;
    }

    // copy into single VectorImage
    CompositeFilterType::Pointer compositeFilter = CompositeFilterType::New();
    compositeFilter->SetInput(0, imageComponent1);
    compositeFilter->SetInput(1, imageComponent2);
    compositeFilter->Update();
    itk::VectorImage<double, 3>::Pointer multiComponentImage = compositeFilter->GetOutput();

    // cast images to mitk
    mitk::CastToMitkImage(multiComponentImage, m_mitkMultiComponentImage);
    mitk::CastToMitkImage(imageComponent1, m_mitkImageComponent1);
    mitk::CastToMitkImage(imageComponent2, m_mitkImageComponent2);
  }
  /*
   * random a voxel. define plane through this voxel. reslice at the plane. compare the pixel vaues of the voxel
   * in the volume with the pixel value in the resliced image.
   * there are some indice shifting problems which causes the test to fail for oblique planes. seems like the chosen
   * worldcoordinate is not corrresponding to the index in the 2D image. and so the pixel values are not the same as
   * expected.
   */
  static void PixelvalueBasedTest()
  {
    /* setup itk image */
    typedef itk::Image<unsigned short, 3> ImageType;

    typedef itk::ImageRegionConstIterator< ImageType > ImageIterator;

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

    ImageType::IndexType start;
    start[0] = start[1] = start[2] = 0;

    ImageType::SizeType size;
    size[0] = size[1] = size[2] = 32;

    ImageType::RegionType imgRegion;
    imgRegion.SetSize(size);
    imgRegion.SetIndex(start);

    image->SetRegions(imgRegion);
    image->SetSpacing(1.0);
    image->Allocate();


    ImageIterator imageIterator( image, image->GetLargestPossibleRegion() );
    imageIterator.GoToBegin();


    unsigned short pixelValue = 0;

    //fill the image with distinct values
    while ( !imageIterator.IsAtEnd() )
    {
      image->SetPixel(imageIterator.GetIndex(), pixelValue);
      ++imageIterator;
      ++pixelValue;
    }
    /* end setup itk image */



    mitk::Image::Pointer imageInMitk;
    CastToMitkImage(image, imageInMitk);



    /*mitk::ImageWriter::Pointer writer = mitk::ImageWriter::New();
    writer->SetInput(imageInMitk);
    std::string file = "C:\\Users\\schroedt\\Desktop\\cube.nrrd";
    writer->SetFileName(file);
    writer->Update();*/

                PixelvalueBasedTestByPlane(imageInMitk, mitk::PlaneGeometry::Frontal);
                PixelvalueBasedTestByPlane(imageInMitk, mitk::PlaneGeometry::Sagittal);
                PixelvalueBasedTestByPlane(imageInMitk, mitk::PlaneGeometry::Axial);

  }
示例#9
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);
	
}
int main(int argc,char ** argv){

	typedef itk::Image<float,3> ImageType;
	typedef itk::Image<float,2> SliceType;

	typedef itk::ImageFileReader<ImageType> ReaderType;
	typedef itk::ImageFileWriter<SliceType> WriterType;

	typedef itk::BoundedReciprocalImageFilter<ImageType,ImageType> BoundedReciprocalType;
	BoundedReciprocalType::Pointer boundedReciprocal = BoundedReciprocalType::New();


	typedef ttt::AdvectiveDiffusion2DIterationImageFilter<SliceType,SliceType> AdvectionDiffusion2DIterationType;

	ReaderType::Pointer reader = ReaderType::New();
	reader->SetFileName(argv[1]);
	reader->UpdateOutputInformation();


	typedef itk::ExtractImageFilter<ImageType,SliceType> ExtractorType;

	ExtractorType::Pointer extractor = ExtractorType::New();

	ImageType::RegionType extractionRegion = reader->GetOutput()->GetLargestPossibleRegion();
	extractionRegion.SetSize(2,0);

	boundedReciprocal->SetInput(reader->GetOutput());
	extractor->SetInput(boundedReciprocal->GetOutput());
	extractor->SetExtractionRegion(extractionRegion);
	extractor->SetDirectionCollapseToIdentity();

	AdvectionDiffusion2DIterationType::Pointer advectionDiffusionIteration =AdvectionDiffusion2DIterationType::New();

	advectionDiffusionIteration->SetInput(extractor->GetOutput());
	advectionDiffusionIteration->SetNumberOfThreads(1.0);


	WriterType::Pointer sliceWriter = WriterType::New();
	sliceWriter->SetInput(extractor->GetOutput());
	sliceWriter->SetFileName(argv[2]);
	sliceWriter->Update();


	WriterType::Pointer writer = WriterType::New();
	writer->SetFileName(argv[3]);

	writer->SetInput(advectionDiffusionIteration->GetOutput());
	writer->Update();

}
//get number of slices
int CTImageTreeItem::getNumberOfSlices() const {
	ImageType::Pointer itkImage = peekITKImage();
	if (itkImage.IsNotNull()) {
		ImageType::RegionType imageRegion = itkImage->GetLargestPossibleRegion();
		return static_cast<uint>(imageRegion.GetSize(2));
	} else {
		int num = m_fnList.size();
		if (num > 1) 
			return num;
		else {
			std::string t;
			itk::ExposeMetaData( m_dict, getNumberOfFramesTag(), t );
			std::istringstream buffer(t);
			buffer >> num;
			return num;
		}  
	}
}
bool VolumeProcess:: RunFillingZeroOnBouandary(int Bx,int By,int Bz)
{
	ImageType::Pointer tempImg = ImageType::New();
	tempImg->SetRegions( m_outputImage->GetLargestPossibleRegion() );
	tempImg->Allocate();
	tempImg->FillBuffer(0);

	ImageType::RegionType fullRegion = m_outputImage->GetBufferedRegion();

	int numColumns = fullRegion.GetSize(0);
	int numRows = fullRegion.GetSize(1);
	int numStacks = fullRegion.GetSize(2);
	int i, j,k; 

	itk::ImageRegionIteratorWithIndex< ImageType > itr( m_outputImage, fullRegion );

	for(itr.GoToBegin(); !itr.IsAtEnd(); ++itr)
	{
		
		ImageType::IndexType index = itr.GetIndex();
	    ImageType::PixelType pix = m_outputImage->GetPixel(index);
        i = index[0];
		j = index[1];
		k = index[2];
		if (i < Bx || i > numColumns -Bx || j < By || j > numRows-By ||k <Bz ||k > numStacks-Bz )
		    tempImg->SetPixel(itr.GetIndex(), 0);
		else 
			tempImg->SetPixel(itr.GetIndex(), pix);
     }
		//Copy temp img back to image 
	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() );
	}

	if(debug)
		std::cerr << "RunFillingZero Done" << std::endl;

	return true;
  
}
示例#13
0
void ITKImplicit::initScalingAndOriginFromBoundingBox(const gmVector3 & minV, const gmVector3 & maxV)
{
	//we make the bounding box slightly bigger
	
	gmVector3 originalCenter=(minV+maxV)/2;
	gmVector3 newMinV=(minV-originalCenter)*boundingBoxScaling+originalCenter;
	gmVector3 newMaxV=(maxV-originalCenter)*boundingBoxScaling+originalCenter;

	//for the moment we will use a scaling, 
	//that leads to a unit cube
	ImageType::SpacingType spacing;
	gmVector3 lengthV=newMaxV-newMinV;
	spacing[0]=fabs(lengthV[0])/((double)voxelRes[0]);
	spacing[1]=fabs(lengthV[1])/((double)voxelRes[1]);
	spacing[2]=fabs(lengthV[2])/((double)voxelRes[2]);
	myImage->SetSpacing(spacing);
	
	//we set the origin such that center lies at (0,0,0)
	ImageType::PointType origin;
	origin[0]=newMinV[0];
	origin[1]=newMinV[1];
	origin[2]=newMinV[2];
	myImage->SetOrigin(origin);
	
	//we want an image with voxelRes voxels
	ImageType::IndexType start;
	start[0]=0;
	start[1]=0;
	start[2]=0;
	ImageType::SizeType size;
	size[0]=max(1,voxelRes[0]);
	size[1]=max(1,voxelRes[1]);
	size[2]=max(1,voxelRes[2]);
	ImageType::RegionType region;
	region.SetIndex(start);
	region.SetSize(size);
	myImage->SetRegions(region);
	
	//allocate memory
	myImage->Allocate();
}
bool VolumeProcess::RunDistanceTransform(void)
{
	ImageType::RegionType region = m_outputImage->GetBufferedRegion();
	int numColumns = region.GetSize(0);
	int numRows = region.GetSize(1);
	int numStacks = region.GetSize(2);
	long numPix = numStacks*numColumns*numRows;

	PixelType * dataImagePtr = m_outputImage->GetBufferPointer();
	unsigned char * binImagePtr = new unsigned char[numPix];

	itk::ImageRegionIterator< ImageType > itr( m_outputImage, m_outputImage->GetLargestPossibleRegion() );

    long idx = 0;
	for(itr.GoToBegin(); !itr.IsAtEnd(); ++itr)
	{
		binImagePtr[idx++]=itr.Get();
	}

	bool ok= distTransform(binImagePtr, numRows, numColumns, numStacks);	//Do distance transform
	if(!ok)
		return false;

	if(debug)
	{
		std::cerr << " Distance Transform is done and we will replace image with the value of DT!" << std::endl;
	}
	//repalce the image by the distance transform
	
	idx = 0;
	for(itr.GoToBegin(); !itr.IsAtEnd(); ++itr)
	{
		itr.Set( binImagePtr[idx++] );
	}

	delete [] binImagePtr;
	return true;
}
示例#15
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;
  }
}
示例#16
0
void
NrrdPlugin::readSlice(int idx[3], int sz[3],
		       int nbytes, uchar *slice)
{
  typedef itk::Image<T, 3> ImageType;

  typedef itk::ImageFileReader<ImageType> ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(m_fileName[0].toAscii().data());
  typedef itk::NrrdImageIO NrrdIOType;
  NrrdIOType::Pointer nrrdIO = NrrdIOType::New();
  reader->SetImageIO(nrrdIO);

  typedef itk::RegionOfInterestImageFilter<ImageType,ImageType> RegionExtractor;

  ImageType::RegionType region;
  ImageType::SizeType size;
  ImageType::IndexType index;
  index[2] = idx[2];
  index[1] = idx[1];
  index[0] = idx[0];
  size[2] = sz[2];
  size[1] = sz[1];
  size[0] = sz[0];
  region.SetIndex(index);
  region.SetSize(size);
  
  // Extract the relevant sub-region.
  RegionExtractor::Pointer extractor = RegionExtractor::New();
  extractor->SetInput(reader->GetOutput());
  extractor->SetRegionOfInterest(region);
  extractor->Update();
  ImageType *dimg = extractor->GetOutput();
  char *tdata = (char*)(dimg->GetBufferPointer());
  memcpy(slice, tdata, nbytes);
}
示例#17
0
bool CCropDialog::GetCropX(QString strSrcImage, quint32 &nStartX)
{
	if(QFile::exists(strSrcImage) != true)
	{
		return false; // error
	}

	QString strTemplateFilename(tr("%1/%2")
								.arg(ui.lineEditSourceFolder->text())
								.arg(sTEMPLATE_IMAGE_FILENAME));
	///////////////////////////////
	// read the template image file
	
	ReaderType::Pointer pTemplateReader = ReaderType::New();
	pTemplateReader->SetFileName(strTemplateFilename.toStdString().c_str());
	try
	{
		pTemplateReader->Update();
	}
	catch( itk::ExceptionObject & err ) 
	{ 
		std::cerr << "ExceptionObject caught !" << std::endl; 
		std::cerr << err << std::endl; 
		return false; // EXIT_FAILURE;
	} 

	quint32 nX, nY;
	quint32 nMinSAD, nSAD, nMinSADX;
	quint32 nRightEdgeX;
	
	nMinSADX = nDEF_START_X; // just in case
	nMinSAD = 0xFFFFFFFF;
	
	ImageType::SizeType size;
	size[0] = nTEMPLATE_WIDTH;
	size[1] = nTEMPLATE_LENGHT;
	ImageType::IndexType start;

	ReaderType::Pointer pReader = ReaderType::New();
	pReader->SetFileName( strSrcImage.toStdString().c_str() );
	//////////////////////
	// loop start
	
	for(nY = 0, nX = nSTART_X; nX < nEND_X; nX++)
	{
		///////////////////////////////////////
		// read a region from the search image
		start[0] = nX, start[1] = nY;
	
		ImageType::RegionType DesiredRegion;
		DesiredRegion.SetSize(  size  );
		DesiredRegion.SetIndex( start );
		FilterType::Pointer pFilter = FilterType::New();
		pFilter->SetRegionOfInterest( DesiredRegion );
		pFilter->SetInput( pReader->GetOutput() );
		
		//bool bbErrorInSourceImage = false;
		try 
		{ 
			pFilter->Update(); 
		} 
		catch( itk::ExceptionObject & err ) 
		{ 
			std::cerr << "ExceptionObject caught !" << std::endl; 
			std::cerr << err << std::endl; 
			return false; // EXIT_FAILURE;
		} 
		
		ConstIteratorType SearchIt(pFilter->GetOutput(), pFilter->GetOutput()->GetRequestedRegion());
		ConstIteratorType TemplateIt(pTemplateReader->GetOutput(), pTemplateReader->GetOutput()->GetRequestedRegion());
	
		nSAD = SumOfAbsoluteDifferences(SearchIt, TemplateIt);
		if(nSAD < nMinSAD)
		{
			nMinSAD = nSAD;
			nMinSADX = nX;
		}
	}
	////////////////
	// loop end
	nRightEdgeX = nMinSADX +  nTEMPLATE_WIDTH/2;
	nStartX = nRightEdgeX - m_TissueBlock.m_nWidth;
	return true;
}
        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 argc, char ** argv)
{
	std::string folderName = argv[1];
	std::string filter = argv[2];

	typedef utils::Directory Directory;
	Directory::FilenamesType filenames = Directory::GetFiles(folderName, ".nrrd");

	Directory::FilenamesType goodFilenames;
	filterFilenames(filenames, filter, goodFilenames);

	// load the images
	std::vector<ImageType::Pointer> imageList;
	for(unsigned int i = 0; i < goodFilenames.size(); i++)
	{
		std::cout << goodFilenames[i] << std::endl;

		typedef itk::ImageFileReader<ImageType> ReaderType;

		ReaderType::Pointer reader = ReaderType::New();
		reader->SetFileName(goodFilenames[i]);
		reader->SetImageIO(itk::NrrdImageIO::New());
		reader->Update();

		imageList.push_back(reader->GetOutput());

	}

	std::sort(imageList.begin(), imageList.end(), imageSort);

	ImageType::Pointer outputImage = ImageType::New();
	ImageType::RegionType outputRegion;
	ImageType::SizeType outputSize = imageList.front()->GetLargestPossibleRegion().GetSize();
	outputSize[2] = imageList.size(); 
	ImageType::IndexType outputIndex;
	outputIndex.Fill(0);
	outputRegion.SetSize(outputSize);
	outputRegion.SetIndex(outputIndex);

	// compute the spacing 
	double meanSpacing = 0.0;
	for(unsigned int i = 1; i < imageList.size(); i++)
	{
		ImageType::Pointer im1 = imageList[i-1];
		ImageType::Pointer im2 = imageList[i];

		meanSpacing += (im1->GetOrigin()-im2->GetOrigin()).GetNorm();
	}

	meanSpacing /= (double) (imageList.size()-1);
	ImageType::SpacingType spacing = imageList.front()->GetSpacing();
	spacing[2] = meanSpacing;

	outputImage->SetRegions(outputRegion);
	outputImage->SetSpacing(spacing);
	outputImage->SetOrigin(imageList.front()->GetOrigin());
	outputImage->SetDirection(imageList.front()->GetDirection());
	outputImage->Allocate();

	itk::ImageRegionIterator<ImageType> outIt(outputImage, outputImage->GetLargestPossibleRegion());
	outIt.GoToBegin();

	while(!outIt.IsAtEnd())
	{
		ImageType::IndexType index = outIt.GetIndex();
		ImageType::IndexType testIndex = index;
		testIndex[2] = 0;

		outIt.Set(imageList[index[2]]->GetPixel(testIndex));


		++outIt;
	}

	std::string stackFilename = folderName + "/stack.nrrd";


	typedef itk::ImageFileWriter<ImageType> WriterType;
	WriterType::Pointer writer = WriterType::New();
	writer->SetInput(outputImage);
	writer->SetFileName(stackFilename);
	writer->SetImageIO(itk::NrrdImageIO::New());
	writer->Update();

	return 0;

}
示例#20
0
int main(int argc, char *argv[])
{

  //check that the user specified the right number of command line arguments
  if(argc < 3)
    {
    cerr << argv[0] << " <input file> <output file>" << endl;
    cerr << argv[0] << " <raw input file> <sizeX> <sizeY> <sizeZ> <output file>"
         << endl;
    return EXIT_FAILURE;
    }

  //check if the input image is .raw
  bool rawInput = false;
  string inputFileName = argv[1];
  const char *outputFileName;
  //double space[3]={1,1,1};
  if(inputFileName.rfind(".raw") != string::npos)
    {
    //if so, the user is also required to pass in image dimensions
    if(argc < 6)
      {
      cerr << "Usage: <raw input file> <sizeX> <sizeY> <sizeZ> <output file>" << endl;
      return EXIT_FAILURE;
      }
    rawInput = true;
    sizeX = atoi(argv[2]);
    sizeY = atoi(argv[3]);
    sizeZ = atoi(argv[4]);
    outputFileName = argv[5];
    }
  else
    {
    outputFileName = argv[2];
    }

  FILE *infile = 0;
  FILE *outfile;
  int i,j,k;
  int ii, jj, kk;
  DATATYPEOUT *volout;
  long idx;

 
  int sizeExpand = 0;
  DATATYPEOUT blockMax;
  int timesDilate;
  int border;
  unsigned short *GraphcutResults;

  cout << "Volume Processing..." << endl;
  //make sure we can write to the output file
  if((outfile=fopen(outputFileName, "wb")) == NULL)
    {
    cerr << "Output file open error!" << endl;
    return EXIT_FAILURE;
    }

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

   if(rawInput)
    {
    if((infile=fopen(inputFileName.c_str(), "rb"))==NULL)
      {
      cout << "Input file open error!" << endl;
      return EXIT_FAILURE;
      }

    volin = (DATATYPEIN*)malloc(sizeX*sizeY*(sizeZ+sizeExpand*2)*sizeof(DATATYPEIN));

    if (fread(volin, sizeof(DATATYPEIN), sizeX*sizeY*sizeZ, infile) < (unsigned int)(sizeX*sizeY*sizeZ))
      {
      cerr << "File size is not the same as volume size" << endl;
      return EXIT_FAILURE;
      }
    
	inputImage = ImageType::New();

	ImageType::PointType origin;
    origin[0] = 0.; 
    origin[1] = 0.;    
    origin[2] = 0.;    
	inputImage->SetOrigin( origin );

	ImageType::IndexType start;
    start[0] =   0;  
    start[1] =   0;  
	start[2] =   0;  

	ImageType::SizeType  size;
    size[0]  = sizeX;  
    size[1]  = sizeY;  
	size[2]  = sizeZ;  

    ImageType::RegionType region;
    region.SetSize( size );
    region.SetIndex( start );
    
    inputImage->SetRegions( region );
    inputImage->Allocate();
    inputImage->FillBuffer(0);
	inputImage->Update();
	
	typedef itk::ImageRegionIteratorWithIndex< ImageType > IteratorType;
	IteratorType iterator1(inputImage,inputImage->GetRequestedRegion());
	int lng = sizeX*sizeY*sizeZ;
	
	for(int i=0; i<lng; i++)
	{
	 iterator1.Set((float)volin[i]);
	 ++iterator1;	
	}
  } // end if(rawInput)

   else
    {
  
    typedef itk::ImageFileReader< ImageType >  ReaderType;
    ReaderType::Pointer reader = ReaderType::New();

    inputImage = reader->GetOutput();
    reader->SetFileName( inputFileName.c_str()  );
    try 
      { 
      reader->Update(); 
      } 
    catch( itk::ExceptionObject & err ) 
      { 
      cerr << "ExceptionObject caught!" << endl; 
      cerr << err << endl; 
      return EXIT_FAILURE;
      } 
	} // end of itk image read 

 
	 // ---------------Linear Mapping --------------------//
    typedef itk::RescaleIntensityImageFilter<
               ImageType, ImageType>  RescaleFilterType;
    RescaleFilterType::Pointer    rescaleFilter    = RescaleFilterType::New();
    rescaleFilter->SetInput(inputImage);
	rescaleFilter->SetOutputMinimum(  0 );
    rescaleFilter->SetOutputMaximum( 255 );
	
	try 
      { 
       rescaleFilter->Update();
      } 
    catch( itk::ExceptionObject & err ) 
      { 
      cerr << "ExceptionObject caught!" << endl; 
      cerr << err << endl; 
      return EXIT_FAILURE;
      }

	inputImage = rescaleFilter->GetOutput();
	cout << "The Linear Mapping is done\n";

    # if Curvature_Anistropic_Diffusion 
	{
     cout << "The Curvature Diffusion is doing\n"; 
	 typedef itk::CurvatureAnisotropicDiffusionImageFilter<
               ImageType, ImageType >  MCD_FilterType;

     MCD_FilterType::Pointer MCDFilter = MCD_FilterType::New();
    
     //Initialnization,  using the paper's optimal parameters
     const unsigned int numberOfIterations = 5;
     const double       timeStep = 0.0425;
     const double       conductance = 3;
     MCDFilter->SetNumberOfIterations(numberOfIterations);
     MCDFilter->SetTimeStep( timeStep );
     MCDFilter->SetConductanceParameter( conductance );
     MCDFilter->SetInput(inputImage);
	 try 
      { 
       MCDFilter->Update();
      } 
     catch( itk::ExceptionObject & err ) 
      { 
      cerr << "ExceptionObject caught!" << endl; 
      cerr << err << endl; 
      return EXIT_FAILURE;
      } 
     inputImage=MCDFilter->GetOutput(); 
     cout << "The Curvature Diffusion is done\n";
	}
	#endif

    ImageType::RegionType region = inputImage->GetBufferedRegion();
    ImageType::SizeType  size = region.GetSize();
    cout << "input image size: " << size << endl;
    sizeX = size[0];
    sizeY = size[1];
    sizeZ = size[2];
    itk::ImageRegionIterator< ImageType >
      itr( inputImage, inputImage->GetBufferedRegion() );
    itr.GoToBegin();
    idx = 0;
    volin = (DATATYPEIN*)malloc(sizeX*sizeY*(sizeZ+sizeExpand*2)*sizeof(DATATYPEIN));
    while( ! itr.IsAtEnd() )
      {
      volin[idx] = itr.Get();
      ++itr;
      ++idx;
      }
  //allocate memory for the output image
  volout = (DATATYPEOUT*)malloc(sizeX*sizeY*(sizeZ+sizeExpand*2)*sizeof(DATATYPEOUT));
  
  // one pre-processing  scheme 
  
  GraphcutResults = (unsigned short*)malloc(sizeX*sizeY*(sizeZ+sizeExpand*2)*sizeof(unsigned short));
  Neuron_Binarization_3D(volin,GraphcutResults,sizeX,sizeY,sizeZ,0,1);
  
  for (k=0; k<(sizeZ+sizeExpand*2); k++)
      for (j=0; j<sizeY; j++)
        for (i=0; i<sizeX; i++) {
          volout[k *sizeX*sizeY + j *sizeX + i] = 0; 
        }  //initial to zeros
   
  
  std::cout << "Do you think we need the distance transform to make the centerline of image become bright with higher intensity?";
  
  char tmpAnswer = 'n';
  //tmpAnswer = getchar();
  if (tmpAnswer =='Y' || tmpAnswer =='y')
  {
  unsigned char *GraphcutResultsTmp;
  GraphcutResultsTmp = (unsigned char*)malloc(sizeX*sizeY*(sizeZ+sizeExpand*2)*sizeof(unsigned char));
  for (k=0; k<(sizeZ+sizeExpand*2); k++)
      for (j=0; j<sizeY; j++)
        for (i=0; i<sizeX; i++) 
		{
          GraphcutResultsTmp[k *sizeX*sizeY + j *sizeX + i] = (unsigned char) GraphcutResults[k *sizeX*sizeY + j *sizeX + i]; 
        }  //initial to zeros

  distTransform(GraphcutResultsTmp,sizeX,sizeY,sizeZ);
  
  for (k=0; k<sizeZ; k++)
    {
    // threshold first
     for (j=0; j<sizeY; j++)
       {
       for (i=0; i<sizeX; i++)
        {
        idx = k *sizeX*sizeY + j *sizeX + i;
        volin[idx] = GraphcutResultsTmp [idx];
        } // end for 
      } // end for 
    } // end for 
  
  free(GraphcutResultsTmp);
  GraphcutResultsTmp=NULL;
  } // end if 

  else {
 
   for (k=0; k<sizeZ; k++)
    {
    // threshold first
     for (j=0; j<sizeY; j++)
       {
       for (i=0; i<sizeX; i++)
        {
        idx = k *sizeX*sizeY + j *sizeX + i;
		
        if (GraphcutResults [idx] == 0) 
          {
          volin[idx] = 0;
          }
        }
      }
    }   

 } // end else

 free(GraphcutResults);
 GraphcutResults=NULL;

  // the secpnd Pre-Processing method, corresponding to the old version MDL 
  /*
  double threshold; 
  // by xiao liang, using 3 sigma theory to estimate threshold;
  double meanValue =0.0, VarianceValue =  0.0;

  // threshold first
  for (k=0; k<sizeZ; k++)
    {
    for (j=0; j<sizeY; j++) 
      {
      for (i=0; i<sizeX; i++)
        {
        idx = k *sizeX*sizeY + j *sizeX + i;
        meanValue += volin[idx];
        }
      }
    }

  meanValue = meanValue/(double)(sizeX*sizeY*sizeZ);
  // threshold first
  for (k=0; k<sizeZ; k++)
    {
    for (j=0; j<sizeY; j++) 
      {
      for (i=0; i<sizeX; i++)
        {
        idx = k *sizeX*sizeY + j *sizeX + i;
        VarianceValue += (volin[idx]-meanValue)*(volin[idx]-meanValue);
        }
      }
    }

  VarianceValue =  VarianceValue/(double)(sizeX*sizeY*sizeZ);
  VarianceValue = sqrt(VarianceValue);

  double m_threshold=OtsuThreshold (sizeX,sizeY,sizeZ);
  if (m_threshold > 7 || m_threshold < 0)
    {
    threshold =(meanValue-VarianceValue/30); 
    }
  else
    {
    threshold = m_threshold;
    }

  //threshold =7;
  cout << "OTSU optimal threshold " << threshold << endl;

     for (k=0; k<(sizeZ+sizeExpand*2); k++)
      for (j=0; j<sizeY; j++)
        for (i=0; i<sizeX; i++) {

          volout[k *sizeX*sizeY + j *sizeX + i] = 0; 
        }  //initial to zeros

  for (k=0; k<sizeZ; k++)
    {
    // threshold first
    for (j=0; j<sizeY; j++)
      {
      for (i=0; i<sizeX; i++)
        {
        idx = k *sizeX*sizeY + j *sizeX + i;
        if (volin[idx] < threshold) 
          {
          volin[idx] = 0;
          }
        }
      }
    }   
  */
  // Method 2: Dilation of the object
  timesDilate = 1;
  border = 3;
  while (timesDilate >0 )
    {
    for (k=border; k<sizeZ-border; k++)
      {
      for (j=border; j<sizeY-border; j++)
        {
        for (i=border; i<sizeX-border; i++)
          {
          blockMax = volin[k *sizeX*sizeY + j *sizeX + i];
          for (kk=-1; kk<=1; kk++)
            {
            for (jj=-1; jj<=1; jj++)
              {
              for (ii=-1; ii<=1; ii++)
                {
                if(volin[(k+kk)*sizeX*sizeY + (j+jj)*sizeX + (i+ii)] > blockMax) 
                  {
                  blockMax = volin[(k+kk)*sizeX*sizeY + (j+jj)*sizeX + (i+ii)];
                  }
                }
              }
            }
          // Keep the peak of the original intensity
          if (blockMax == volin[k *sizeX*sizeY + j *sizeX + i] && blockMax != 0)
            {
            blockMax = blockMax + 1;
            //if (blockMax > 255)   blockMax = 255;
            }
          volout[k *sizeX*sizeY + j *sizeX + i] = blockMax;
          }
        }
      }

    // copy volout back to volin for the next dilation
    for (k=0; k<sizeZ; k++) 
      {
      for (j=0; j<sizeY; j++) 
        {
        for (i=0; i<sizeX; i++)
          {
          volin[k *sizeX*sizeY + j *sizeX + i] = volout[k *sizeX*sizeY + j *sizeX + i];
          }
        }
      }
    timesDilate--;
    }

  //-----  Image write 
   /*
    typedef itk::ImageRegionIteratorWithIndex< ImageType > IteratorType;
	IteratorType iterator1(inputImage,inputImage->GetRequestedRegion());
	int lng = sizeX*sizeY*sizeZ;
	
	for(int i=0; i<lng; i++)
	{
	 iterator1.Set((float)volin[i]);
	 ++iterator1;	
	}
   */
  //write the output image and free memory
  fwrite(volout, sizeX*sizeY*sizeZ, sizeof(DATATYPEOUT), outfile);
  FILE *mhdfile;
  
  if((mhdfile=fopen("volume_Processed.mhd","w"))==NULL)
    {
    cerr << "output file open error!" << endl;
    return -1;
    }
  fprintf (mhdfile,"ObjectType = Image\n");
  fprintf (mhdfile,"NDims = 3\n");
  fprintf (mhdfile,"BinaryData = True\n");
  fprintf (mhdfile,"BinaryDataByteOrderMSB = False\n");
  fprintf (mhdfile,"CompressedData = False\n");
  fprintf (mhdfile,"TransformMatrix = 1 0 0 0 1 0 0 0 1\n");
  fprintf (mhdfile,"Offset = 0 0 0\n");
  fprintf (mhdfile,"CenterOfRotation = 0 0 0\n");
  fprintf (mhdfile,"AnatomicalOrientation = RAI\n");
  fprintf (mhdfile,"ElementSpacing = 1 1 1\n");
  fprintf (mhdfile,"DimSize = %d %d %d\n",sizeX,sizeY,sizeZ);
  fprintf (mhdfile,"ElementType = MET_UCHAR\n");
  fprintf (mhdfile,"ElementDataFile = volume_Processed.raw\n");
  fclose(mhdfile);

  if (rawInput)
	  fclose(infile);
  fclose(outfile);

  free(volin);  // by xiao
  free(volout); // by xiao
  volin=NULL;
  volout=NULL;

  //cout << "Done" << endl;
  return 0;
}
void LabelsVolumeGenerator::postProcessTargetITK()
{
    typedef unsigned char       PixelType;
    typedef Image<PixelType, 3> ImageType;

    // create a new image from the target data

    ImageType::Pointer input = ImageType::New();

    ImageType::IndexType start;
    start.Fill(0);

    ImageType::SizeType size;
    for (int i = 0; i < 3; ++i) size[i] = m_targetVolume->dimensions[i];

    ImageType::RegionType region;
    region.SetSize(size);
    region.SetIndex(start);

    input->SetRegions(region);
    input->SetSpacing(m_targetVolume->spacing.data());
    input->Allocate();

    memcpy(input->GetBufferPointer(), m_targetVolume->data, m_bufferSize);

    // create a grayscale dilation filter and a structuring element

    typedef BinaryBallStructuringElement<PixelType, 3> StructureType;
    typedef GrayscaleDilateImageFilter<ImageType, ImageType, StructureType> DilateFilterType;

    DilateFilterType::Pointer filter = DilateFilterType::New();

    StructureType structure;
    structure.SetRadius(1);

    filter->SetKernel(structure);

    // set up progress reporting
    if (m_progressReporter)
    {
        CStyleCommand::Pointer command = CStyleCommand::New();
        command->SetClientData(m_progressReporter);
        command->SetCallback(ProgressCallback);
        filter->AddObserver(ProgressEvent(), command);
        m_progressReporter->start("Post-Processing Label volume",
                                  "Dilating label field...");
    }

    // hook up the filters and run

    filter->SetInput(input);
    filter->Update();

    if (m_progressReporter)
        m_progressReporter->finish();

    // copy back into the target volume data
    memcpy(m_targetVolume->data, filter->GetOutput()->GetBufferPointer(), m_bufferSize);

    // threshold and gaussian blur to put a smooth version into the alpha channel

    typedef BinaryThresholdImageFilter<ImageType, ImageType> ThresholderType;
//    typedef DiscreteGaussianImageFilter<ImageType, ImageType> SmoothFilterType;
    typedef SmoothingRecursiveGaussianImageFilter<ImageType, ImageType> SmoothFilterType;

    ThresholderType::Pointer thresholder = ThresholderType::New();
    thresholder->SetLowerThreshold(1);
    thresholder->SetUpperThreshold(255);
    thresholder->SetInsideValue(255);
    thresholder->SetOutsideValue(0);

    SmoothFilterType::Pointer smoother = SmoothFilterType::New();
//    smoother->SetVariance(0.05); // in physical units
//    smoother->SetMaximumKernelWidth(5);
    smoother->SetSigma(0.2);

    // set up progress reporting (again)
    if (m_progressReporter)
    {
        CStyleCommand::Pointer command = CStyleCommand::New();
        command->SetClientData(m_progressReporter);
        command->SetCallback(ProgressCallback);
        smoother->AddObserver(ProgressEvent(), command);
        m_progressReporter->start("Post-Processing Label volume",
                                  "Smoothing alpha mask...");
    }

    // hook up the filters and run

    thresholder->SetInput(input);
    smoother->SetInput(thresholder->GetOutput());
    smoother->Update();

    // copy back into the target volume data
    memcpy(m_targetMask->data, smoother->GetOutput()->GetBufferPointer(), m_bufferSize);

    if (m_progressReporter)
        m_progressReporter->finish();
}
示例#22
0
void reconstruction_func(V3DPluginCallback2 &callback, QWidget *parent, input_PARA &PARA, bool bmenu)
{
    // QMessageBox msgBox;
    // if (bmenu)
    // {
    //     msgBox.setText("Rivulet Running...");
    //     msgBox.setIcon(QMessageBox::Information);
    //     msgBox.setStandardButtons(QMessageBox::Ok);
    //     // msgBox.setAutoClose(true);
    //     // msgBox.setTimeout(3); //Closes after three seconds
    //     msgBox.exec();
    // }

    unsigned char* data1d = 0;
    V3DLONG N,M,P,sc,c;
    V3DLONG in_sz[4];
    if(bmenu)
    {
        v3dhandle curwin = callback.currentImageWindow();
        if (!curwin)
        {
            QMessageBox::information(0, "", "You don't have any image open in the main window.");
            return;
        }

        Image4DSimple* p4DImage = callback.getImage(curwin);

        if (!p4DImage)
        {
            QMessageBox::information(0, "", "The image pointer is invalid. Ensure your data is valid and try again!");
            return;
        }


        data1d = p4DImage->getRawData();
        N = p4DImage->getXDim();
        M = p4DImage->getYDim();
        P = p4DImage->getZDim();
        sc = p4DImage->getCDim();

        bool ok1;

        if(sc==1)
        {
            c=1;
            ok1=true;
        }
        else
        {
            c = QInputDialog::getInteger(parent, "Channel",
                                             "Enter channel NO:",
                                             1, 1, sc, 1, &ok1);
        }

        if(!ok1)
            return;

        in_sz[0] = N;
        in_sz[1] = M;
        in_sz[2] = P;
        in_sz[3] = sc;


        PARA.inimg_file = p4DImage->getFileName();
    }
    else
    {
        int datatype = 0;
        if (!simple_loadimage_wrapper(callback,PARA.inimg_file.toStdString().c_str(), data1d, in_sz, datatype))
        {
            fprintf (stderr, "Error happens in reading the subject file [%s]. Exit. \n",PARA.inimg_file.toStdString().c_str());
            return;
        }
        if(PARA.channel < 1 || PARA.channel > in_sz[3])
        {
            fprintf (stderr, "Invalid channel number. \n");
            return;
        }
        N = in_sz[0];
        M = in_sz[1];
        P = in_sz[2];
        sc = in_sz[3];
        c = PARA.channel;
    }

    //main neuron reconstruction code
    cout<<"Start Rivulet"<<endl;
    printf("Image Size: %d, %d, %d\n", in_sz[0], in_sz[1], in_sz[2]);

    // Binarize Image with theshold
    const unsigned char threshold = PARA.threshold;
    const unsigned char stepsize = PARA.stepsize;
    const unsigned char gap = PARA.gap; 
    const unsigned char dumpbranch = PARA.dumpbranch; 
    const unsigned char connectrate = PARA.connectrate; 
    const double percentage = PARA.percentage;
    cout<<"Tracing Parameters:"<<endl;
    printf("threshold:\t%d", threshold);
    printf("stepsize:\t%d", stepsize);
    printf("gap:\t%d", gap);
    printf("dumpbranch:\t%d", dumpbranch);
    printf("connectrate:\t%d", connectrate);
    printf("percentage:\t%f", percentage);

    int NVOX = M * N * P;
    
    // Distance Transform
    float * bdist1d = 0;
    cout<<"DT..."<<endl;
    unsigned char* binary_data1d;

    try
    {
        binary_data1d = new unsigned char[NVOX]; // Make a copy of the original data for radius estimation
    }
    catch(...)  {v3d_msg("Cannot allocate memory for B."); return;}

    std::copy(data1d, data1d + NVOX, binary_data1d);

    // Fast marching distance transform proposed in APP2 
    fastmarching_dt(data1d, bdist1d, N, M, P, 2, threshold);

    // Using the Image Operation found in vaa3d_tools/hackathon/zhi/snake_tracing/TracingCore/ in for some simple Image Processing
    IM = new ImageOperation;


    int in_sz_int[4];

    for(int i = 0; i < 4; i++)
    {
        in_sz_int[i] = (int)in_sz[i];
    }

    IM->Imcreate(data1d, in_sz_int);
    // std::cout<<"image operation work or not?"<<std::endl;
    IM->computeHessian(PARA.sigma, PARA.alpha_one, PARA.alpha_two);
    std::cout<<"=== Hessian computation Finished..."<<std::endl;
    //----------------------------vesselness begin
    V3DLONG l_npixels_vessel;
    l_npixels_vessel = in_sz_int[0] * in_sz_int[1] * in_sz_int[2];
    cout<<"l_npixels_vessel"<<l_npixels_vessel<<endl;
    GradientImageType::IndexType index;
    unsigned char *p_vessel = new unsigned char[l_npixels_vessel]();
    unsigned char *vp_tmp = p_vessel;
    ImageType::RegionType rg = (IM->finalim->GetLargestPossibleRegion());
    ImageType::SizeType sz = rg.GetSize();
    for(V3DLONG Z = 0;Z < in_sz[2]; Z++)
        for(V3DLONG Y = 0;Y < in_sz[1]; Y++)
            for(V3DLONG X = 0;X < in_sz[0]; X++)
            {
                index[0] = X; index[1] = Y; index[2] = Z;

                *vp_tmp = (unsigned char)(IM->finalim->GetPixel(index) * 100);
                vp_tmp++;
            }
    // cout<<"Before the vesselness image is saved."<<endl;
    // QString str_outimg_filename = PARA.inimg_file + "_vesselness.v3draw";
    // saveImage(qPrintable(str_outimg_filename), p_vessel, in_sz, V3D_UINT8);
    // cout<<"After the vesselness image is saved."<<endl;
    cout<<"the vesselness image is binaried with threshold."<<endl;

    // binarize data
    for (int i=0; i<NVOX; i++)
    {
        // binary_data1d[i] = binary_data1d[i] > threshold? 1 : 0;
        binary_data1d[i] = p_vessel[i] > threshold? 1 : 0;
    }

    // Find the source point
    float maxd;
    V3DLONG maxidx = findmax(bdist1d, NVOX, &maxd);
    Point sourcepoint = ind2sub(maxidx, in_sz);

    // Make Speed Image
    for (int i = 0; i < NVOX - 1; i++)
    {   
        float s = pow(bdist1d[i] / maxd, 4);
        bdist1d[i] = s == 0 ? 1e-10 : s;
    }

    // Marching on the Speed Image
    int sp[3];
    sp[0] = (int)sourcepoint.x; sp[1] = (int)sourcepoint.y; sp[2] = (int)sourcepoint.z;
    double* bdist1d_double = float2double(bdist1d, NVOX);
    // printf("Source Point -- x: %d, y: %d, z: %d\n", (int)sourcepoint.x, (int)sourcepoint.y, (int)sourcepoint.z);
    double* oT = msfm(bdist1d_double, in_sz, sp, false, false, false); // Original Timemap

    if (bdist1d_double) {delete [] bdist1d_double; bdist1d_double = 0;}

    double* T = new double[NVOX]; // Timemap for tracing which is going to be erased
    copy(oT, oT + NVOX, T);
    vector<swcnode> tree;
    bool prune = true;

    // Calculate the gradient of the Distance map
    cout<<"Calculating Gradient"<<endl;
    double* grad = distgradient(T, in_sz);
    // cout<<"Gradient Calculated"<<endl;
    bool * B;
    try {B = new bool[NVOX];}
    catch(...)  {v3d_msg("Cannot allocate memory for B."); return;}
    for (int i=0; i<NVOX; i++)
    {
        B[i] = false;
    }

    bool * tB;
    try {tB = new bool[NVOX];}
    catch(...)  {v3d_msg("Cannot allocate memory for tB."); return;}
    for (int i=0; i<NVOX; i++)
    {
        tB[i] = false;
    }
    vector<float> lconfidence;

    // Mask T with 0 where 0 in original image
    for (int i=0; i<NVOX; i++)
    {
        T[i] = binary_data1d[i] ==0 ? 0 : T[i];
    }
    // Start Tracing
    cout<<"Start Tracing"<<endl;
    cout<<"        '.,\n          'b      *\n           '$    #.\n            $:   #:\n            *#  @):\n            :@,@):   ,.**:'\n  ,         :@@*: ..**'\n   '#o.    .:(@'.@*\"'\n      'bq,..:,@@*'   ,*\n      ,p$q8,:@)'  .p*'\n     '    '@@Pp@@*'\n           Y7'.'\n          :@):.\n         .:@:'.\n       .::(@:.  \n"<<endl;
    MyMarker marker; // Only for radius estimation
    std::clock_t start = std::clock();
    while(true)
    {
        cout<<".";
        // cout<<"N Branches:"<<tree.size()<<endl;
        double maxt;
        int maxidx = findmax(T, NVOX, &maxt);
        Point startpoint = ind2sub((V3DLONG)maxidx, in_sz);
        // Trace the shortest path from the farthest point to the source point
        Path l = shortestpath2(T, grad, binary_data1d, in_sz, startpoint, sourcepoint, stepsize, gap);
        // cout<<"after shortestpath2"<<endl;
        int pathlen = l.l.size();
        
        //Get radius of each point from distance transform
        vector<float> radius(pathlen);
        for (int i=0; i< pathlen; i++)
        {
            V3DLONG idx = sub2ind(l.l[i].x, l.l[i].y, l.l[i].z, in_sz);
            // radius[i] = bdist1d[idx] < 1.0 ? 1.0 : bdist1d[idx];
            marker.x = l.l[i].x; marker.y = l.l[i].y; marker.z = l.l[i].z;
            radius[i] = markerRadius(data1d, in_sz, marker, threshold, 2); 
        }

        // Remove traced from the time map
        binarysphere3d(tB, in_sz, l.l, radius);
        tB[maxidx] = 1;
        V3DLONG bsum = 0;
        V3DLONG vsum = 0;

        for (int i=0; i<NVOX; i++)
        {
            T[i] = tB[i] == true ? -1 : T[i];
            B[i] = tB[i] || B[i];
            bsum += B[i] && binary_data1d[i] != 0? 1 : 0;
            vsum += binary_data1d[i];
        }

        // Add l to tree
        if ( !(l.dump && dumpbranch) )
        {
            float conf = addbranch2tree(&tree, l, connectrate, radius, binary_data1d, in_sz);
            lconfidence.push_back(conf);
        }
        else
        {
            // cout<<"Branch dumped"<<endl;
        }

        // Compute the coverage percent
        double percent = (double)bsum / (double)vsum;
        // cout<<"Percent:"<<percent* 100<<endl;
        if (percent >= percentage)
        {
            break;
        }
        
    }

    double duration = (std::clock() - start) / (double) CLOCKS_PER_SEC;
    cout<<"Tracing took "<<duration<<" seconds"<<endl;

    // Free up memory
    if (bdist1d) {delete [] bdist1d; bdist1d = 0;}
    if (oT) {delete [] oT; oT = 0;}
    if (T) {delete [] T; T = 0;}
    if (grad) {delete [] grad; grad = 0;}
    if (B) {delete [] B; B = 0;}
    if (binary_data1d) {delete [] binary_data1d; binary_data1d = 0;}

    //Output
    NeuronTree nt;
    QList <NeuronSWC> listNeuron;
    QHash <int, int> hashNeuron;
    listNeuron.clear();
    hashNeuron.clear();
    NeuronSWC S;
    for (int i = 0; i < tree.size(); i++)
    {
        S.n = tree[i].id;
        S.type = tree[i].type;
        S.x = tree[i].p.x;
        S.y = tree[i].p.y;
        S.z = tree[i].p.z;
        S.r = tree[i].radius;
        S.pn = tree[i].parent;
        listNeuron.append(S);
        hashNeuron.insert(S.n, listNeuron.size() - 1);       
    }
    nt.n = -1;
    nt.on = true;
    nt.listNeuron = listNeuron;
    nt.hashNeuron = hashNeuron;
	QString swc_name = PARA.inimg_file + "_Rivulet.swc";
	nt.name = "Rivulet";
    writeSWC_file(swc_name.toStdString().c_str(),nt);
    celebrate();
    cout<<"δὶς ἐς τὸν αὐτὸν ποταμὸν οὐκ ἂν ἐμβαίης. -- Ἡράκλειτος"<<endl;
    // if (bmenu)
    // {
    //     msgBox.done(0);
    // }

    v3d_msg(QString("Now you can drag and drop the generated swc fle [%1] into Vaa3D.").arg(swc_name.toStdString().c_str()),bmenu);

    if(!bmenu)
    {
        if(data1d) {delete []data1d; data1d = 0;}
    }

    // v3d_msg(QString("Now you can drag and drop the generated swc fle [%1] into Vaa3D.").arg(swc_name.toStdString().c_str()),bmenu);

    return;
}
示例#23
0
void MakeDices(const char * montagefileName, const char * seedfileName, int diceWidth, 
			   double alfa, double beta, int timethreshold, double curvatureScaling, double rmsThres, int holeSize, int minObjSize)
{
	typedef SomaExtractor::ProbImageType ImageType;
	typedef SomaExtractor::OutputImageType OutputImageType;
	typedef itk::RegionOfInterestImageFilter< ImageType, ImageType> RegionOfInterestFilter;
	SomaExtractor *Somas = new SomaExtractor();

	std::cout<< "ReadMontage..."<<std::endl;
	ImageType::Pointer image = Somas->SetInputImage(montagefileName);
	int SZ = image->GetLargestPossibleRegion().GetSize()[2];

	std::vector< itk::Index<3> > seedVector;
	Somas->ReadSeedpoints( seedfileName, seedVector, 0);
	std::cout<< "Seed points size:"<< seedVector.size()<<std::endl;	

	#pragma omp parallel for
	for(int i = 0; i < seedVector.size(); i++)
	{
		SomaExtractor *somaExtractor = new SomaExtractor();
		ImageType::IndexType start;
		start[0] = seedVector[i][0] - diceWidth / 2;
		start[1] = seedVector[i][1] - diceWidth / 2;
		start[2] = 0;
		ImageType::SizeType size;
		size[0] = diceWidth;
		size[1] = diceWidth;
		size[2] = SZ;

		ImageType::RegionType desiredRegion;
		desiredRegion.SetSize(size);
		desiredRegion.SetIndex(start);

		RegionOfInterestFilter::Pointer regionFilter = RegionOfInterestFilter::New();
		regionFilter->SetInput(image);
		regionFilter->SetRegionOfInterest(desiredRegion);
		regionFilter->Update();
		ImageType::Pointer diceImage = regionFilter->GetOutput();
		std::ostringstream oss1;
		oss1<< "Dice_"<< i<<".tif";
		std::string str1 = oss1.str();
		somaExtractor->writeImage(str1.c_str(), diceImage);
		
		std::vector< itk::Index<3> > seedsForDice;
		itk::Index<3> seedIndex = seedVector[i];
		seedIndex[0] = diceWidth / 2;
		seedIndex[1] = diceWidth / 2;
		seedsForDice.push_back(seedIndex);

		float Origion[3] = {0,0,0};
		diceImage->SetOrigin(Origion);

		//SomaExtractor::SegmentedImageType::Pointer segImage= somaExtractor->SegmentSoma(diceImage, seedsForDice, alfa, 
		//					beta, timethreshold, curvatureScaling, rmsThres, holeSize, minObjSize);
		//double threshold = 0;
//		//ImageType::Pointer segImage = Somas->EnhanceContrast(diceImage, seedIndex[2], alfa, beta, threshold);
//
//#pragma omp critical
//		std::cout<< "segment "<< i<<"\t"<<seedsForDice.size()<<std::endl;
//		std::ostringstream oss;
//		oss<< "Dice_Segment_"<< i<<".tif";
//		std::string str = oss.str();
//		somaExtractor->writeImage(str.c_str(), segImage);
		delete somaExtractor;
	}
	delete Somas;
}
//calculate segmentation values
bool CTImageTreeItem::internalGetSegmentationValues( SegmentationValues &values) const {
	
	//get ITK image
	ImageType::Pointer image = getITKImage();
	if (image.IsNull()) 
		return false;

	//get buffered region of the image
	ImageType::RegionType ctregion = image->GetBufferedRegion();
	//define an iterator for the binary segment
	typedef itk::ImageRegionConstIteratorWithIndex< BinaryImageType > BinaryIteratorType;
	//get binary segment
	BinaryImageTreeItem::ImageType::Pointer segment = values.m_segment->getITKImage();
	if (segment.IsNull()) 
		return false;

/*	typedef itk::ImageFileWriter< ImageType >  WriterType;
	WriterType::Pointer writer = WriterType::New();
	writer->SetFileName( "test.dcm" );

	writer->SetInput( image );
		try 
		{
			writer->Update();
		}
		catch( itk::ExceptionObject & excep )
		{
			std::cerr << "Exception catched !" << std::endl;
			std::cerr << excep << std::endl;
		}
*/
	//create a binary iterator for the segment and its buffered region
	BinaryIteratorType binIter( segment, segment->GetBufferedRegion() );
	ImageType::PointType point;
  
	//The Accumulators Framework is framework for performing incremental calculations
	using namespace boost::accumulators;
	//http://boost-sandbox.sourceforge.net/libs/accumulators/doc/html/accumulators/user_s_guide.html#accumulators.user_s_guide.the_accumulators_framework
	accumulator_set<double,features<tag::count, tag::min, tag::mean, tag::max, tag::variance> > acc;  
  
	//check selected accuracy
	if (values.m_accuracy == SegmentationValues::SimpleAccuracy) {
		ImageType::IndexType index;
		//iterate over the pixel of the binary segment
		for(binIter.GoToBegin(); !binIter.IsAtEnd(); ++binIter) {
			//if actual value = 255
			if (binIter.Value() == BinaryPixelOn) {
				//transforms the index to a physical point in the binary segment
				segment->TransformIndexToPhysicalPoint(binIter.GetIndex(),point);
				//transform that point to an index of the CT image
				image->TransformPhysicalPointToIndex(point, index);
				//check if that index is inside the CT region
				if (ctregion.IsInside(index)) {
					//get the pixel value at the index
					int t = image->GetPixel(index);
					//check if pixel value != -2048
					if (isRealHUvalue(t)) {
						//accumulate pixel value
						acc( t );
					}
				}
			}
		}
	//check selected accuracy
	} else if (values.m_accuracy == SegmentationValues::PreventDoubleSamplingAccuracy) {
		ImageType::IndexType index;
		//definition for a set of indices, which can be compared
		typedef std::set< ImageType::IndexType, IndexCompareFunctor > IndexSetType;
		IndexSetType indexSet;
		//iterate over the pixel of the binary segment
		for(binIter.GoToBegin(); !binIter.IsAtEnd(); ++binIter) {
			//if actual value = 255
			if (binIter.Value() == BinaryPixelOn) {
				//transforms the index to a physical point in the binary segment
				segment->TransformIndexToPhysicalPoint(binIter.GetIndex(),point);
				//transform that point to an index of the CT image
				image->TransformPhysicalPointToIndex(point, index);
				//check if that index is inside the CT region
				if (ctregion.IsInside(index)) {

					std::pair<IndexSetType::iterator,IndexSetType::iterator> ret;
					//
					ret = indexSet.equal_range(index);
					//If x does not match any key in the container, the range returned has a length of zero, 
					//with both iterators pointing to the nearest value greater than x, if any, 
					//or to set::end if x is greater than all the elements in the container.
					if (ret.first == ret.second) {
						indexSet.insert(ret.first, index);
						//get the pixel value at the index
						int t = image->GetPixel(index);
						//check if pixel value != -2048
						if (isRealHUvalue(t)) {
							//accumulate pixel value
							acc( t );
						}
					}
				}
			}
		}
	//check selected accuracy
	} else if (values.m_accuracy == SegmentationValues::InterpolatedAccuracy) {
		//define an interpolate function
		typedef  itk::LinearInterpolateImageFunction< CTImageType > InterpolatorType;
		InterpolatorType::Pointer interpolator = InterpolatorType::New();
		//set input to the interpolator
		interpolator->SetInputImage( image );
		InterpolatorType::ContinuousIndexType index;
		//iterate over the pixel of the binary segment
		for(binIter.GoToBegin(); !binIter.IsAtEnd(); ++binIter) {
			//if actual value = 255
			if (binIter.Value() == BinaryPixelOn) {
				//transforms the index to a physical point in the binary segment
				segment->TransformIndexToPhysicalPoint(binIter.GetIndex(),point);
				//transform that point to an index of the CT image
				image->TransformPhysicalPointToContinuousIndex(point, index);
				//check if the index is inside the buffer of the interpolator
				if (interpolator->IsInsideBuffer(index)) {
					//Returns the linearly interpolated image intensity
					int t = interpolator->EvaluateAtContinuousIndex(index);
					//check if pixel value != -2048
					if (isRealHUvalue(t)) {
						//accumulate pixel value
						acc( t );
					}
				}
			}
		}  
	}
	//set sample count, min, mean, max and standard deviation
	//from the accumulated intensities
	values.m_sampleCount = count( acc );
	values.m_min = min( acc );
	values.m_mean = mean( acc );
	values.m_max = max( acc );
	values.m_stddev = std::sqrt( variance( acc ) );
	//set the image modification time
	values.m_mtime = segment->GetMTime();
	const_cast<CTImageTreeItem*>(this)->m_segmentationValueCache[ values.m_segment ] = values;
	return values.m_sampleCount > 0;
}    
示例#25
0
ITKImplicit::ITKImplicit(void)
{
	new SurfParamString(this,&dirFile,"","fileDir", "Input file or dicom directory");
	new SurfParamButton(this,new LoadButtonCallback(this),"load","","load a dicom or imagetype file (extension .vtk suggested)");
	new SurfParamButton(this,new SaveButtonCallback(this),"save","","save a dicom or imagetype file (extension .vtk suggested)");
	new SurfParamDouble(this,&threshold,0,"Threshold", "CT Number");
	new SurfParamDouble(this,&scale,1.0,"Scale", "Volume Scaling Factor");
	new SurfParamgmVector3(this,&tr,gmVector3(0,0,0),"Translation","Volume Translation");
	new SurfParamButton(this, new ApplyParameterChangesCallback(this),"Apply","Apply parameter changes",  "apply parameter changes: Namely translation, scaling,"
																											"and spline order");

	new SurfSurfRefParam(this, &surface,"<invalid/optional>","Surf(opt.)","SurfaceReference(optional)",	
																			"The ITK Volume can also be initialized using a" 
																			"surface. In the case of an implicit the bounding box should be meaningful."
																			"If no bounding box is provided a unit cube centered at the origin is assumed."
																			"The implicit is sampled inside of this bounding box."
																			"In the case of a surface mesh, the behavior is special:"
																			"a distance field is calculated inside of ITS bounding box");


	new SurfParamInt(this,&(voxelRes[0]),64,"sizeX", "NbX", "Nb of gridcells along x-Axis");
	new SurfParamInt(this,&(voxelRes[1]),64,"sizeY","nbY", "Nb of gridcells along y-Axis");
	new SurfParamInt(this,&(voxelRes[2]),64,"sizeZ","nbZ", "Nb of gridcells along z-Axis");
	new SurfParamDouble(this, &boundingBoxScaling, 1.3,"scale","scalebb", "Scaling of the bounding box to make it slightly bigger");

	new SurfAttrRefParam(this,(ParticleAttribute **)&bbox,"invalid:ParticleBoundingBox","bbox","box",
		"Particle bounding box attribute (it is advised to provide one for implicit surfaces).");

	new SurfParamButton(this, new SetITKImplicit(this),"initImp","Initialize ITK implicit","set ITK imp");
	new SurfParamInt(this,&order,3,"Order","Spline Order");


	//DICOM reader
	dicomIO = ImageIOType::New();
	reader = ReaderType::New();
	reader->SetImageIO( dicomIO );
	nameGenerator = NamesGeneratorType::New();


	//now we initialize a simple default image
	//and all the rest of this constructor is just to do this...
	//...I love the ITK interface ... lol
	//init default image, this can still be overwritten
	myImage = ImageType::New();

	ImageType::SpacingType spacing;
	spacing[0]=0.1;
	spacing[1]=0.1;;
	spacing[2]=0.1;;
	myImage->SetSpacing(spacing);
	
	//we set the origin such that center lies at (0,0,0)
	ImageType::PointType origin;
	origin[0]=-0.05;
	origin[1]=-0.05;
	origin[2]=-0.05;
	myImage->SetOrigin(origin);
	
	//we want an image with voxelRes voxels
	ImageType::IndexType start;
	start[0]=0;
	start[1]=0;
	start[2]=0;
	ImageType::SizeType size;
	size[0]=1;
	size[1]=1;
	size[2]=1;
	ImageType::RegionType region;
	region.SetIndex(start);
	region.SetSize(size);
	myImage->SetRegions(region);
	
	//allocate memory
	myImage->Allocate();


	//interpolating function
	myInterpFunc = InterpFunc::New();	
	myInterpFunc->SetSplineOrder((unsigned int) 0);
	myInterpFunc->SetInputImage(myImage);

	
}
示例#26
0
/**
 * draws the tree from the TreeDrawer into a volumetric 3D
 * image as a series of 2D png slices
 */
void drawImage(TreeDrawer * td, const char* rootName){
	typedef unsigned char PixelType;
	const unsigned int Dimension = 3;
	typedef itk::Image< PixelType, Dimension > ImageType;

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

	ImageType::SizeType size;
	size[0] = td->dim[0]; // size along X
	size[1] = td->dim[1]; // size along Y
	size[2] = td->dim[2]; // size along Z

	ImageType::IndexType start;
	start[0] = 0; // first index on X
	start[1] = 0; // first index on Y
	start[2] = 0; // first index on Z

	ImageType::RegionType region;
	region.SetSize( size );
	region.SetIndex( start );

	image->SetRegions( region );
	image->Allocate();
	
	ImageType::IndexType pixelIndex;
	pixelIndex[0] = 0; // x position
	pixelIndex[1] = 0; // y position
	pixelIndex[2] = 0; // z position

	for(int i = 0; i < td->dim[0]; i++){
		for(int j = 0; j < td->dim[1]; j++){
			for(int k = 0 ; k < td->dim[2]; k++){
				pixelIndex[0] = i;
				pixelIndex[1] = j;
				pixelIndex[2] = k;
				
				image->SetPixel(pixelIndex, td->imageAt(i, j, k));
			}
		}
	}


	typedef itk::Image< unsigned char, 2 > Image2DType;
	typedef itk::ImageSeriesWriter< ImageType, Image2DType > WriterType;
	WriterType::Pointer writer = WriterType::New();
	writer->SetInput( image);

	typedef itk::NumericSeriesFileNames NameGeneratorType;
	NameGeneratorType::Pointer nameGenerator = NameGeneratorType::New();

	std::string format = rootName;
	format += "%03d";
	format += ".jpg";
	nameGenerator->SetSeriesFormat( format.c_str() );

	const unsigned int firstSlice = start[2];
	const unsigned int lastSlice = start[2] + size[2] - 1;
	nameGenerator->SetStartIndex( firstSlice );
	nameGenerator->SetEndIndex( lastSlice );
	nameGenerator->SetIncrementIndex( 1 );

	writer->SetFileNames( nameGenerator->GetFileNames() );

	try{
		writer->Update();
	}catch( itk::ExceptionObject & excp ){
        
        throw "Exception thrown while reading the image";
        
	}

	return;
}
示例#27
0
int main(int argc, char**argv)
{
	int nx, ny, nz, nbytes, direction, nx8, ny8, nz8, k;
//	int n, x, y, z, dx, dy;
	long long width, height, depth, xysize;
	char *dataFile, *tiffFile;
	bool use_compression = true, data2tiff, compressdata = true;
	FILE *fpdata;

	if (argc != 4) {
		printf("Usage: maketiff dataFile tiffFile direction\n");
		printf("       direction = 0 (tiff to data) = 1 (data to tiff)\n");
		return 1;
	}

	dataFile = argv[1];
	tiffFile = argv[2];
	sscanf(argv[3],"%d",&direction);
	if (direction == 0) {
		data2tiff = false;
		printf("Output data file: %s\n",dataFile);
	} else {
		data2tiff = true;
		printf("Output image file: %s\n",tiffFile);
	}

	if (data2tiff) {		// create tiff file
		fpdata = fopen(dataFile,"rb");
		if (fpdata == NULL) {
			return 2;
		}
		fread(&nx,4,1,fpdata);
		fread(&ny,4,1,fpdata);
		fread(&nz,4,1,fpdata);
//		fread(&nbytes,4,1,fpdata);

		//if (nbytes != nx*ny*nz) {
		//	printf("Error: this is a compressed data file\n");
		//	return 10;
		//}
		width = nx;
		height = ny;
		depth = nz;
		xysize = width*height;
		printf("Desired image dimensions: width, height, depth: %d %d %d\n",width,height,depth);

		ImageType::Pointer im = ImageType::New();
		ImageType::SizeType imsize; 
		imsize[0] = width;
		imsize[1] = height;
		imsize[2] = depth;
		ImageType::IndexType imstart; 
		imstart[0] = 0;
		imstart[1] = 0;
		imstart[2] = 0;
		ImageType::RegionType imregion; 
		imregion.SetSize(imsize);
		imregion.SetIndex(imstart);
		im->SetRegions(imregion);
		im->Allocate();
		p = (unsigned char *)(im->GetBufferPointer());

		nbytes = nx*ny*nz;
		fread(p,nbytes,1,fpdata);

		typedef itk::ImageFileWriter<ImageType> FileWriterType;
		FileWriterType::Pointer writer = FileWriterType::New();
		writer->SetFileName(tiffFile);
		writer->SetInput(im);
		if (use_compression) {
			writer->UseCompressionOn();
		}
		try
		{
			writer->Update();
		}
		catch (itk::ExceptionObject &e)
		{
			std::cout << e << std::endl;
			return 3;
		}
		if (use_compression) {
			printf("Created compressed image file: %s\n",tiffFile);
		} else {
			printf("Created uncompressed image file: %s\n",tiffFile);
		}
	} else {		// create data file
		typedef itk::ImageFileReader<ImageType> FileReaderType;
		FileReaderType::Pointer reader = FileReaderType::New();

		reader->SetFileName(tiffFile);
		try
		{
			reader->Update();
		}
		catch (itk::ExceptionObject &e)
		{
			std::cout << e << std::endl;
			printf("Read error on input file\n");
			return 2;	// Read error on input tiff file
		}

		im = reader->GetOutput();
		width = im->GetLargestPossibleRegion().GetSize()[0];
		height = im->GetLargestPossibleRegion().GetSize()[1];
		depth = im->GetLargestPossibleRegion().GetSize()[2];
		printf("Image dimensions: width, height, depth: %d %d %d\n",width,height,depth);

		p = (unsigned char *)(im->GetBufferPointer());

		fpdata = fopen(dataFile,"wb");
		if (fpdata == NULL) {
			return 2;
		}
		nx = width;
		ny = height;
		nz = depth;

		if (compressdata) {
			// create compressed buffer pc from p using (0,1)
			// First round up nx, ny, nz to a multiple of 8
			k = nx%8;
			if (k == 0)
				nx8 = nx;
			else
				nx8 = nx + 8-k;
			k = ny%8;
			if (k == 0)
				ny8 = ny;
			else
				ny8 = ny + 8-k;
			k = nx%8;
			if (k == 0)
				nz8 = nz;
			else
				nz8 = nz + 8-k;
			nbytes = nx8*ny8*nz8/8;

			pc = (unsigned char *)malloc(nbytes*sizeof(unsigned char));
			int kbit = 0;
			int kbyte = 0;
			k = 0;
			unsigned char pcbyte = 0;
			for (int iz=0; iz<nz8; iz++) {
				bool zok = (iz<nz);
				for (int iy=0; iy<ny8; iy++) {
					bool yok = (iy<ny);
					for (int ix=0; ix<nx8; ix++) {
						bool xok = (ix<nx);
						if (xok && yok && zok) {
							// set bit kbit of pcbyte to (0,1) based on p[k]
							if (p[k] == 1 || p[k] == 255) {
								pcbyte |= 1 << kbit;
							}
							if (kbyte < 4) printf("ix,iy,iz k p[k] pcbyte: %d %d %d  %d  %d  %d\n", ix,iy,iz,k,p[k],pcbyte);
							k++;
						}
						kbit++;
						if (kbit == 8) {
							pc[kbyte] = pcbyte;
							if (kbyte == 0) {
								printf("byte:%d  %d\n",kbyte,pc[kbyte]);
							}
							kbyte++;
							pcbyte = 0;
							kbit = 0;
						}
					}
				}
			}
		}
		fwrite(&nx,4,1,fpdata);
		fwrite(&ny,4,1,fpdata);
		fwrite(&nz,4,1,fpdata);
		fwrite(&nx8,4,1,fpdata);
		fwrite(&ny8,4,1,fpdata);
		fwrite(&nz8,4,1,fpdata);
		fwrite(&nbytes,4,1,fpdata);
		printf("nx,ny,nz  nx8,ny8,nz8: %d %d %d  %d %d %d\n",nx,ny,nz,nx8,ny8,nz8);

		width = nx;
		height = ny;
		depth = nz;
		xysize = width*height;
// write(nfdata) nx,ny,nz,(((imagedata(ix,iy,iz),ix=1,nx),iy=1,ny),iz=1,nz)
		// try this...
		if (compressdata) {
			fwrite(pc,1,nbytes,fpdata);
		} else {
			fwrite(p,1,nx*ny*nz,fpdata);
		}
		fclose(fpdata);
	}

	return 0;
}
示例#28
0
void CCropDialog::DoCrop(int nStartX, int nStartY, int nWidth, int nLength, 
		QString strInputFileName, QString strOutputFileName)
{
	if(QFile::exists(strOutputFileName))
	{
		return; // 
	}

	ImageType::IndexType start;
	start[0] = nStartX;
	start[1] = nStartY;

	ImageType::SizeType size;
	size[0] = nWidth;
	size[1] = nLength;
	
	ImageType::RegionType desiredRegion;
	desiredRegion.SetSize(  size  );
	desiredRegion.SetIndex( start );
	FilterType::Pointer filter = FilterType::New();
	filter->SetRegionOfInterest( desiredRegion );

	ReaderType::Pointer reader = ReaderType::New();
	const char * inputFilename  = strInputFileName.toStdString().c_str();

	reader->SetFileName( inputFilename  );
	filter->SetInput( reader->GetOutput() );
	
	//bool bbErrorInSourceImage = false;
	try 
	{ 
		filter->Update(); 
	} 
	catch( itk::ExceptionObject & err ) 
	{ 
		std::cerr << "ExceptionObject caught !" << std::endl; 
		std::cerr << err << std::endl; 
		return; // EXIT_FAILURE;
	} 
	
	////////////////////////////////////
	// prepare the output
	ImageType::Pointer pOutputImage = ImageType::New();
	pOutputImage->SetRegions( filter->GetOutput()->GetRequestedRegion() );
	//pOutputImage->CopyInformation(pReader->GetOutput());
	pOutputImage->Allocate();
	
	///////////////////////////////////
	// fill buffer with initial value
	ImageType::PixelType  InitialValue = 255;
	pOutputImage->FillBuffer( InitialValue );

	//if(bErrorInSourceImage != true)
	{
		ConstIteratorType InputItX(filter->GetOutput(), filter->GetOutput()->GetRequestedRegion());
		IteratorType      OutputItX(pOutputImage, filter->GetOutput()->GetRequestedRegion());
		DoRelight(0, InputItX, OutputItX);

		ConstIteratorType InputItY(pOutputImage, filter->GetOutput()->GetRequestedRegion());
		IteratorType      OutputItY(pOutputImage, filter->GetOutput()->GetRequestedRegion());
		DoRelight(1, InputItY, OutputItY);
	}
	
	WriterType::Pointer pWriter = WriterType::New();
	const char * outputFilename  = strOutputFileName.toStdString().c_str();
	pWriter->SetFileName(outputFilename);
	pWriter->SetInput( pOutputImage );

	try
	{
		pWriter->Update();
	}
	catch ( itk::ExceptionObject &err)
	{
	    std::cerr << "ExceptionObject caught !" << std::endl; 
	    std::cerr << err << std::endl; 
	    return; // -1;   
	}
}
示例#29
0
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;
  }
}
示例#30
0
void Cell::GetMask(const std::string & soma_filename)
{
	typedef itk::ImageFileReader< SomaImageType > ReaderType;
	ReaderType::Pointer reader = ReaderType::New();
	reader->SetFileName(soma_filename);

	//**WARNING** PURPOSELY COMMENTED OUT SO YOU DO NOT TRY TO WRITE THIS CODE, THIS KILLS PERFORMANCE BECAUSE IT ATTEMPTS TO READ THE ENTIRE IMAGE FOR EACH CELL INSTEAD OF JUST THE ROI
	//try
	//{
	//	reader->Update();
	//}
	//catch (itk::ExceptionObject &err)
	//{
	//	std::cerr << "reader Exception: " << err << std::endl;
	//}

	typedef itk::RegionOfInterestImageFilter< SomaImageType, MaskImageType > ROIFilterType;
	ROIFilterType::Pointer roi_filter = ROIFilterType::New();

	ImageType::IndexType start;
	start[0] = this->roi_origin[0];
	start[1] = this->roi_origin[1];
	start[2] = this->roi_origin[2];

	ImageType::SizeType size = this->roi_size;

	ImageType::RegionType desiredRegion;
	desiredRegion.SetSize(size);
	desiredRegion.SetIndex(start);

	roi_filter->SetRegionOfInterest(desiredRegion);
	roi_filter->SetInput(reader->GetOutput());

	try
	{
		//roi_filter->Update();
		ftk::TimeStampOverflowSafeUpdate(roi_filter.GetPointer());
	}
	catch (itk::ExceptionObject &err)
	{
		std::cout << "roi_filter Exception: " << err << std::endl;
	}

	this->mask = roi_filter->GetOutput();
	this->mask->DisconnectPipeline();	//Disconnect pipeline so we don't propagate...

	ImageType::PointType origin;
	origin[0] = 0;
	origin[1] = 0;
	origin[2] = 0;
	this->mask->SetOrigin(origin);

	//Make the file name of the mask image
	std::stringstream mask_filename_stream;
	mask_filename_stream << cell_x << "_" << cell_y << "_" << cell_z << "_mask.TIF";	//X_Y_Z_masked.TIF

	//Write the masked cell image
	//WriteImage(mask_filename_stream.str(), this->mask);

	//Get the label image from the binary image
	typedef itk::BinaryImageToLabelMapFilter< MaskImageType > BinaryToLabelFilterType;
	BinaryToLabelFilterType::Pointer labelMapFilter = BinaryToLabelFilterType::New();
	labelMapFilter->SetInput(this->mask);

	try
	{
		ftk::TimeStampOverflowSafeUpdate( labelMapFilter.GetPointer() );
		//labelMapFilter->Update();
	}
	catch (itk::ExceptionObject &err)
	{
		std::cerr << "labelMapFilter exception: " << err << std::endl;
		std::cerr << "Mask image: " << this->mask << std::endl;
		std::cerr << this->mask << std::endl;
		std::cerr << labelMapFilter << std::endl;
	}

	BinaryToLabelFilterType::OutputImageType::Pointer label_map_image = labelMapFilter->GetOutput();
	label_map_image->DisconnectPipeline();

	typedef itk::LabelMapToLabelImageFilter< BinaryToLabelFilterType::OutputImageType, LabelImageType > LabelMapToLabelImageFilterType;
	LabelMapToLabelImageFilterType::Pointer labelImageFilter = LabelMapToLabelImageFilterType::New();
	labelImageFilter->SetInput(label_map_image);
	try
	{
		ftk::TimeStampOverflowSafeUpdate( labelImageFilter.GetPointer() );
		//labelImageFilter->Update();
	}
	catch (itk::ExceptionObject &err)
	{
		std::cerr << "labelImageFilter exception: " << err << std::endl;
	}

	this->soma_label_image = labelImageFilter->GetOutput();
	this->soma_label_image->DisconnectPipeline();	//Disconnect pipeline so we don't propagate...
}