Пример #1
0
bool TestIsClosedLoop()
{
  std::cout << "TestIsClosedLoop()" << std::endl;

  // Open loop
  {
  typedef itk::Image<unsigned char, 2> ImageType;
  ImageType::Pointer image = ImageType::New();

  itk::Index<2> corner = {{0,0}};
  itk::Size<2> size = {{100,100}};
  itk::ImageRegion<2> region(corner, size);

  image->SetRegions(region);
  image->Allocate();
  image->FillBuffer(0);

  for(itk::Index<2>::IndexValueType i = 20; i < 30; ++i)
  {
    itk::Index<2> pixel = {{i, 50}};
    image->SetPixel(pixel, 255);
  }

  itk::Index<2> start = {{25, 50}};

  bool isClosedLoop = ITKHelpers::IsClosedLoop(image.GetPointer(), start);

  std::cout << "Is closed loop? " << isClosedLoop << std::endl;
  }

  // Closed loop
  {
  typedef itk::Image<unsigned char, 2> ImageType;
  ImageType::Pointer image = ImageType::New();

  itk::Index<2> corner = {{0,0}};
  itk::Size<2> size = {{100,100}};
  itk::ImageRegion<2> region(corner, size);

  image->SetRegions(region);
  image->Allocate();
  image->FillBuffer(0);

  itk::Index<2> corner0 = {{10,10}};
  itk::Index<2> corner1 = {{30,30}};
  ITKHelpers::DrawRectangle(image.GetPointer(), 255,
                            corner0, corner1);

  itk::Index<2> start = {{10, 10}};

  bool isClosedLoop = ITKHelpers::IsClosedLoop(image.GetPointer(), start);

  std::cout << "Is closed loop? " << isClosedLoop << std::endl;
  }

  return true;
}
Пример #2
0
bool TestBreadthFirstOrderingNonZeroPixels()
{
  std::cout << "TestBreadthFirstOrderingNonZeroPixels()" << std::endl;

  typedef itk::Image<unsigned char, 2> ImageType;
  ImageType::Pointer image = ImageType::New();

  itk::Index<2> corner = {{0,0}};
  itk::Size<2> size = {{100,100}};
  itk::ImageRegion<2> region(corner, size);

  image->SetRegions(region);
  image->Allocate();
  image->FillBuffer(0);

  for(itk::Index<2>::IndexValueType i = 20; i < 30; ++i)
  {
    itk::Index<2> pixel = {{i, 50}};
    image->SetPixel(pixel, 255);
  }

  itk::Index<2> start = {{25, 50}};
  std::vector<itk::Index<2> > breadthFirstOrdering =
      ITKHelpers::BreadthFirstOrderingNonZeroPixels(image.GetPointer(), start);

  for(unsigned int i = 0; i < breadthFirstOrdering.size(); ++i)
  {
    //std::cout << breadthFirstOrdering[i] << " ";
    std::cout << breadthFirstOrdering[i] << std::endl;
  }

  std::cout << std::endl;

  return true;
}
Пример #3
0
void TestGetOpenContourOrdering()
{
  typedef itk::Image<unsigned char, 2> ImageType;
  ImageType::Pointer image = ImageType::New();

  itk::Index<2> corner = {{0,0}};
  itk::Size<2> size = {{100,100}};
  itk::ImageRegion<2> region(corner, size);

  image->SetRegions(region);
  image->Allocate();
  image->FillBuffer(0);

  for(unsigned int i = 20; i < 30; ++i)
  {
    itk::Index<2> pixel = {{i, 50}};
    image->SetPixel(pixel, 255);
  }

  itk::Index<2> start = {{25, 50}};

  std::vector<itk::Index<2> > contourOrdering = ITKHelpers::GetOpenContourOrdering(image.GetPointer(), start);

  for(unsigned int i = 0; i < contourOrdering.size(); ++i)
  {
    //std::cout << breadthFirstOrdering[i] << " ";
    std::cout << contourOrdering[i] << std::endl;
  }

  std::cout << std::endl;
}
Пример #4
0
void TestGetClosedContourOrdering()
{
  typedef itk::Image<unsigned char, 2> ImageType;
  ImageType::Pointer image = ImageType::New();

  itk::Index<2> corner = {{0,0}};
  itk::Size<2> size = {{100,100}};
  itk::ImageRegion<2> region(corner, size);

  image->SetRegions(region);
  image->Allocate();
  image->FillBuffer(0);

  itk::Index<2> corner0 = {{10,10}};
  itk::Index<2> corner1 = {{30,30}};
  ITKHelpers::DrawRectangle(image.GetPointer(), 255,
                            corner0, corner1);

  itk::Index<2> start = {{10, 10}};

  std::vector<itk::Index<2> > ordering = ITKHelpers::GetClosedContourOrdering(image.GetPointer(), start);

  for(unsigned int i = 0; i < ordering.size(); ++i)
  {
    std::cout << ordering[i] << std::endl;
  }

  std::cout << std::endl;
}
int main(int, char* [] )
{
  typedef itk::Image<unsigned char, 2> ImageType;
  ImageType::Pointer image = ImageType::New();

  itk::Index<2> corner={{0,0}};
  itk::Size<2> size = {{10,10}};
  itk::ImageRegion<2> region(corner,size);
  image->SetRegions(region);
  image->Allocate();
  image->FillBuffer(0);

  unsigned char searchValue = 255; // This value does not appear in the image, so both functions
  // will have to search the entire image.

  int counter = 0;
  for(unsigned int i = 0; i < 1e7; ++i)
  {
//    counter += HasValue(image.GetPointer(), searchValue); // About 3 seconds
    counter += HasValueConditional(image.GetPointer(), searchValue); // About 3.3 seconds
  }

  std::cout << "counter " << counter << std::endl;
  return 0;
}
Пример #6
0
void NRRDTools::saveNRRDFile(const cleaver::FloatField *field, const std::string &name) {
  auto dims = field->dataBounds().size;
  ImageType::Pointer img = ImageType::New();
  itk::Index<3> start; start.Fill(0);
  ImageType::SizeType size;
  size[0] = static_cast<size_t>(dims[0]);
  size[1] = static_cast<size_t>(dims[1]);
  size[2] = static_cast<size_t>(dims[2]);
  ImageType::RegionType region(start, size);
  img->SetRegions(region);
  img->Allocate();
  img->FillBuffer(0);
  for (size_t i = 0; i < dims[0]; i++) {
    for (size_t j = 0; j < dims[1]; j++) {
      for (size_t k = 0; k < dims[2]; k++) {
        ImageType::IndexType pixelIndex;
        pixelIndex[0] = i;
        pixelIndex[1] = j;
        pixelIndex[2] = k;
        auto data = ((cleaver::FloatField*)field)->data();
        img->SetPixel(pixelIndex, data[i + size[0] * j + size[0] * size[1] * k]);
      }
    }
  }
  WriterType::Pointer write = WriterType::New();
  write->SetFileName(name + ((name.find_first_of(".nrrd") == std::string::npos) ? ".nrrd" : ""));
  write->SetInput(img);
  write->Update();
}
Пример #7
0
// ------------------------------------------------------------------------
void createOutput(const ImageType::Pointer &input, ImageType::Pointer &output)
{
	output->SetDirection(input->GetDirection());
	output->SetSpacing(input->GetSpacing());
	output->SetRegions(input->GetLargestPossibleRegion());
	output->SetOrigin(input->GetOrigin());
	output->Allocate();
	output->FillBuffer(0);
}
Пример #8
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);
	
}
ComposeImageFilter::ImageType::Pointer ComposeImageFilter::ComposeIt()
{
	ImageType::Pointer outputImage = ImageType::New();

	outputImage->SetRegions(m_imageLR->GetLargestPossibleRegion());
	outputImage->SetOrigin(m_imageLR->GetOrigin());
	outputImage->SetSpacing(m_imageLR->GetSpacing());
	outputImage->SetDirection(m_imageLR->GetDirection());
	outputImage->Allocate();
	outputImage->FillBuffer(0.0);

	std::cout << "outputImage" << std::endl;

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

	std::cout << m_matrix.rows() << " " << m_matrix.cols() << std::endl;

	for (int i=0; i< m_matrix.rows() ; i++ )
	{
		vcl_vector<int> rowIndices;
		vcl_vector<float> rowValues;
	    vcl_vector<pair_t> rowM = m_matrix.get_row(i);

		float sum_vox =0;

		ImageType::IndexType outputIndex;
		outputIndex = ComputeImageIndex(i, m_imageLR);
		
//		std::cout << "ImageLR " << " " << i << " " <<  outputIndex << std::endl;

		for (vcl_vector<pair_t>::const_iterator it = rowM.begin(); it != rowM.end(); ++it)
		{
			ImageType::IndexType HRIndex;
			HRIndex = ComputeImageIndex(it->first, m_imageHR);
			sum_vox += (it->second)* (m_imageHR->GetPixel(HRIndex));
//			std::cout << HRIndex <<  " " << it->second <<  std::endl;

		}
//		std::cout << sum_vox << std::endl;
		outputImage->SetPixel(outputIndex, sum_vox);
//


	}

	return outputImage;
}
Пример #10
0
bool TestRandomImage()
{
  typedef itk::Image<unsigned char, 2> ImageType;
  ImageType::Pointer image = ImageType::New();

  itk::Index<2> corner = {{0,0}};
  itk::Size<2> size = {{100,100}};
  itk::ImageRegion<2> region(corner, size);

  image->SetRegions(region);
  image->Allocate();
  image->FillBuffer(0);

  ITKHelpers::RandomImage(image.GetPointer());
  ITKHelpers::WriteImage(image.GetPointer(), "random.png");

  return true;
}
Пример #11
0
void snapshot_beta_points(Nodes const& nodes)
{
   // clear it
   g_snapshot_image->FillBuffer(0);

   for (Nodes::const_iterator it = nodes.begin(), end = nodes.end();
        it != end; ++it) {

      // &&& Hmm, maybe we can do better than this; make it truly sparse.
      ImageType::IndexType index;
      g_snapshot_image->TransformPhysicalPointToIndex((*it)->pos(), index);

      PixelType density = g_snapshot_image->GetPixel(index);
      // There is no natural beta intensity (except maybe beta-like-ness,
      // which we don't keep)
      density += constants::BetaPointDisplayFakeDensity;
      g_snapshot_image->SetPixel(index, density);
   }
}
Пример #12
0
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 TestDrawRectangle()
{
  typedef itk::Image<unsigned char, 2> ImageType;
  ImageType::Pointer image = ImageType::New();

  itk::Index<2> corner = {{0,0}};
  itk::Size<2> size = {{100,100}};
  itk::ImageRegion<2> region(corner, size);

  image->SetRegions(region);
  image->Allocate();
  image->FillBuffer(0);

  itk::Index<2> corner0 = {{10,10}};
  itk::Index<2> corner1 = {{30,30}};
  ITKHelpers::DrawRectangle(image.GetPointer(), 255,
                            corner0, corner1);

  ITKHelpers::WriteImage(image.GetPointer(), "rectangle.png");
}
int main(int, char* [] )
{
  typedef itk::Image<unsigned char, 2> ImageType;
  ImageType::Pointer image = ImageType::New();

  itk::Index<2> corner = {{0, 0}};
  itk::Size<2> size = {{31, 31}}; // Both dimensions of the size must be odd for the logic in this code to work
  itk::ImageRegion<2> region(corner, size);
  image->SetRegions(region);
  image->Allocate();
  image->FillBuffer(1);

  // This is the pixel we will repeatedly query
  itk::Index<2> queryIndex = {{size[0]/2, size[0]/2}};

  // Create a list of all of the offsets relative to the queryIndex
  std::vector<itk::Offset<2> > offsets;

  itk::ImageRegionConstIteratorWithIndex<ImageType> imageIterator(image, region);

  while(!imageIterator.IsAtEnd())
  {
    offsets.push_back(imageIterator.GetIndex() - queryIndex);

    ++imageIterator;
  }

  // Call these functions many times for timing stability

  int totalSum = 0; // This variable is used so the compiler doesn't optimize away the loop
  for(unsigned int i = 0; i < 1e4; ++i)
  {
//    ImageType::PixelType pixelSum = SumPixelsManual(image.GetPointer(), queryIndex, offsets); // about 2 seconds
    ImageType::PixelType pixelSum = SumPixelsIterator(image.GetPointer(), queryIndex, offsets);

    totalSum += pixelSum;
  }

  std::cout << "totalSum " << totalSum << std::endl;
  return 0;
}
Пример #15
0
void TestGetAllPatchesContainingPixel()
{
  typedef itk::Image<float, 2> ImageType;
  ImageType::Pointer image = ImageType::New();

  itk::Index<2> corner = {{0,0}};
  itk::Size<2> size = {{10,10}};
  itk::ImageRegion<2> imageRegion(corner,size);

  image->SetRegions(imageRegion);
  image->Allocate();
  image->FillBuffer(0.0f);

  itk::Index<2> queryPixel = {{5,5}};

  std::vector<itk::ImageRegion<2> > allPatches =
        ITKHelpers::GetAllPatchesContainingPixel(queryPixel, 1, imageRegion);

  std::cout << "Number of patches " << allPatches.size() << std::endl;

}
Пример #16
0
int main(int argc, char ** argv){

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

	typedef itk::ImageFileReader<ImageType> ReaderType;

	typedef itk::ImageFileWriter<ImageType> WriterType;

	ReaderType::Pointer reader = ReaderType::New();

	reader->SetFileName(argv[1]);

	typedef itk::HessianRecursiveGaussianImageFilter<ImageType> HessianFilterType;
	typedef HessianFilterType::OutputImageType HessianImageType;
	typedef HessianImageType::PixelType HessianType;

	HessianFilterType::Pointer hessianFilter = HessianFilterType::New();

	hessianFilter->SetSigma(0.05);
	hessianFilter->SetInput(reader->GetOutput());

	hessianFilter->Update();

	HessianImageType::Pointer hessianImage = hessianFilter->GetOutput();
	hessianImage->DisconnectPipeline();

	typedef itk::ImageRegionConstIteratorWithIndex<HessianImageType> IteratorType;

	IteratorType hessianIterator(hessianImage,hessianImage->GetLargestPossibleRegion());

	typedef HessianType::EigenValuesArrayType EigenvalueArrayType;
	EigenvalueArrayType expectation;
	expectation.Fill(0.0);
	unsigned count=0;

	ImageType::Pointer small = ImageType::New();
	small->CopyInformation(reader->GetOutput());

	small->SetRegions(reader->GetOutput()->GetLargestPossibleRegion());
	small->Allocate();
	small->FillBuffer(0.0);
	ImageType::Pointer medium = ImageType::New();
	medium->CopyInformation(reader->GetOutput());
	medium->SetRegions(reader->GetOutput()->GetLargestPossibleRegion());

	medium->Allocate();
	medium->FillBuffer(0.0);
	ImageType::Pointer large = ImageType::New();
	large->CopyInformation(reader->GetOutput());
	large->SetRegions(reader->GetOutput()->GetLargestPossibleRegion());
	large->Allocate();
	large->FillBuffer(0.0);

	while(!hessianIterator.IsAtEnd()){

		auto hessian = hessianIterator.Get();
		EigenvalueArrayType eigenValues;
		hessian.ComputeEigenValues(eigenValues);

		std::sort(eigenValues.Begin(),eigenValues.End(),[](double & a, double &b){
			return std::abs(a) > std::abs(b);
		});

		//std::cout << eigenValues[0] << "\t"<< eigenValues[1] << "\t" << eigenValues[2] <<std::endl;

		if(eigenValues[0]<0){
			expectation[0]+=eigenValues[0];
			expectation[1]+=eigenValues[1];
			expectation[2]+=eigenValues[2];

			count++;

			large->SetPixel(hessianIterator.GetIndex(),std::abs(eigenValues[0]));
			medium->SetPixel(hessianIterator.GetIndex(),std::abs(eigenValues[1]));
			small->SetPixel(hessianIterator.GetIndex(),std::abs(eigenValues[2]));
		}
		++hessianIterator;
	}
	expectation[0]=expectation[0]/count;
	expectation[1]=expectation[1]/count;
	expectation[2]=expectation[2]/count;

	WriterType::Pointer smallWriter = WriterType::New();
	smallWriter->SetInput(small);
	smallWriter->SetFileName("small.mha");
	smallWriter->Update();

	WriterType::Pointer mediumWriter = WriterType::New();
	mediumWriter->SetInput(medium);
	mediumWriter->SetFileName("medium.mha");
	mediumWriter->Update();

	WriterType::Pointer largeWriter = WriterType::New();
	largeWriter->SetInput(large);
	largeWriter->SetFileName("large.mha");
	largeWriter->Update();

	std::cout << "Expectation: \t" << expectation<< std::endl;

}
Пример #17
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;   
	}
}
Пример #18
0
void
DistanceMapFilter::applyDistanceMapFilter(QString flnm,
					  QList<Vec> clipPos,
					  QList<Vec> clipNormal,
					  QList<CropObject> crops,
					  QList<PathObject> paths,
					  uchar *lut,
					  int chan)
{
  int bpv = 1;
  if (m_voxelType > 0) bpv = 2;
  int nbytes = bpv*m_nY*m_nZ;

  bool trim = (qRound(m_dataSize.x) < m_height ||
	       qRound(m_dataSize.y) < m_width ||
	       qRound(m_dataSize.z) < m_depth);
  bool clipPresent = (clipPos.count() > 0);

  m_cropPresent = false;
  m_tearPresent = false;
  m_blendPresent = false;
  for(int ci=0; ci<m_crops.count(); ci++)
    {
      if (crops[ci].cropType() < CropObject::Tear_Tear)
	m_cropPresent = true;
      else if (crops[ci].cropType() < CropObject::View_Tear)
	m_tearPresent = true;
      else if (m_crops[ci].cropType() > CropObject::Displace_Displace &&
	       m_crops[ci].cropType() < CropObject::Glow_Ball)
	m_blendPresent = true;
    }

  m_pathCropPresent = false;
  m_pathBlendPresent = false;
  for (int i=0; i<m_paths.count(); i++)
    {
      if (m_paths[i].blend()) m_pathBlendPresent = true;
      if (m_paths[i].crop()) m_pathCropPresent = true;
    }

  m_meshLog->moveCursor(QTextCursor::End);
  int d0 = 0;
  int d1 = m_nX-1;
  int d0z = d0 + qRound(m_dataMin.z);
  int d1z = d1 + qRound(m_dataMin.z);

  uchar *opacityVol = new uchar[m_nX*m_nY*m_nZ];
  
  uchar *cropped = new uchar[nbytes];
  uchar *tmp = new uchar[nbytes];

  int i0 = 0;
  for(int i=d0z; i<=d1z; i++)
    {
      m_meshProgress->setValue((int)(100.0*(float)i0/(float)m_nX));
      qApp->processEvents();

      int iv = qBound(0, i, m_depth-1);
      uchar *vslice = m_vfm->getSlice(iv);

      memset(cropped, 0, nbytes);

      if (!trim)
	memcpy(tmp, vslice, nbytes);
      else
	{
	  int wmin = qRound(m_dataMin.y);
	  int hmin = qRound(m_dataMin.x);
	  if (m_voxelType == 0)
	    {
	      for(int w=0; w<m_nY; w++)
		for(int h=0; h<m_nZ; h++)
		  tmp[w*m_nZ + h] = vslice[(wmin+w)*m_height + (hmin+h)];
	    }
	  else
	    {
	      for(int w=0; w<m_nY; w++)
		for(int h=0; h<m_nZ; h++)
		  ((ushort*)tmp)[w*m_nZ + h] = ((ushort*)vslice)[(wmin+w)*m_height + (hmin+h)];
	    }
	}

      int jk = 0;
      for(int j=0; j<m_nY; j++)
	for(int k=0; k<m_nZ; k++)
	  {
	    Vec po = Vec(m_dataMin.x+k, m_dataMin.y+j, iv);
	    bool ok = true;
	    
	    // we don't want to scale before pruning
	    int mop = 0;
	    {
	      Vec pp = po - m_dataMin;
	      int ppi = pp.x/m_pruneLod;
	      int ppj = pp.y/m_pruneLod;
	      int ppk = pp.z/m_pruneLod;
	      ppi = qBound(0, ppi, m_pruneX-1);
	      ppj = qBound(0, ppj, m_pruneY-1);
	      ppk = qBound(0, ppk, m_pruneZ-1);
	      int mopidx = ppk*m_pruneY*m_pruneX + ppj*m_pruneX + ppi;
	      mop = m_pruneData[3*mopidx + chan];
	      ok = (mop > 0);
	    }
	    
	    po *= m_samplingLevel;
	    
	    if (ok && clipPresent)
	      ok = StaticFunctions::getClip(po, clipPos, clipNormal);
	    
	    if (ok && m_cropPresent)
	      ok = checkCrop(po);
	    
	    if (ok && m_pathCropPresent)
	      ok = checkPathCrop(po);
	    
	    if (ok && m_blendPresent)
	      {
		ushort v;
		if (m_voxelType == 0)
		  v = tmp[j*m_nZ + k];
		else
		  v = ((ushort*)tmp)[j*m_nZ + k];
		ok = checkBlend(po, v, lut);
	      }
	    
	    if (ok && m_pathBlendPresent)
	      {
		ushort v;
		if (m_voxelType == 0)
		  v = tmp[j*m_nZ + k];
		else
		  v = ((ushort*)tmp)[j*m_nZ + k];
		ok = checkPathBlend(po, v, lut);
	      }
	    
	    if (ok)
	      cropped[jk] = mop;
	    else
	      cropped[jk] = 0;
	    
	    jk ++;
	  }
      
      if (m_voxelType == 0)
	{
	  for(int j=0; j<m_nY*m_nZ; j++)
	    {
	      if (cropped[j] == 0)
		tmp[j] = 0;
	    }
	}
      else
	{
	  for(int j=0; j<m_nY*m_nZ; j++)
	    {
	      if (cropped[j] == 0)
		((ushort*)tmp)[j] = 0;
	    }
	}
      
      applyOpacity(iv, cropped, lut, tmp);
      memcpy(opacityVol + i0*m_nY*m_nZ, tmp, m_nY*m_nZ);
      
      i0++;
    }
  delete [] tmp;
  delete [] cropped;
  m_meshProgress->setValue(100);
  qApp->processEvents();

  //------------
  if (m_tearPresent)
    {
      uchar *data0 = new uchar[m_nX*m_nY*m_nZ];
      memcpy(data0, opacityVol, m_nX*m_nY*m_nZ);
      applyTear(d0, d1, 0,
		data0, opacityVol, false);
      
      delete [] data0;
    }


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

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

  ImageType::SizeType size;
  size[0] = m_nZ;
  size[1] = m_nY;
  size[2] = m_nX;

  ImageType::RegionType region(start, size);

  ImageType::Pointer image = ImageType::New();
  image->SetRegions(region);
  image->Allocate();
  image->FillBuffer(0);
  uchar *iptr = (uchar*)image->GetBufferPointer();
  memcpy(iptr, opacityVol, m_nX*m_nY*m_nZ);

  typedef itk::Image< float, 3 > OutputImageType;
  typedef itk::SignedMaurerDistanceMapImageFilter<ImageType, OutputImageType> DistanceMapFilter;
  DistanceMapFilter::Pointer filter = DistanceMapFilter::New();
  filter->SetInput( image );
  filter->SetSquaredDistance(0);
  filter->SetUseImageSpacing(0);
  filter->SetInsideIsPositive(1);
  filter->Update();

  QFile fp;
  fp.setFileName(flnm);
  fp.open(QFile::WriteOnly);
  uchar vt = 8;
  fp.write((char*)&vt, 1);
  fp.write((char*)&m_nX, 4);
  fp.write((char*)&m_nY, 4);
  fp.write((char*)&m_nZ, 4);
  OutputImageType *dimg = filter->GetOutput();
  char *tdata = (char*)(dimg->GetBufferPointer());
  fp.write(tdata, 4*m_nX*m_nY*m_nZ);
  fp.close();

  m_meshLog->moveCursor(QTextCursor::End);
  m_meshLog->insertPlainText("Signed Distance Map data saved in "+flnm);

  QMessageBox::information(0, "", QString("Signed Distance Map saved in "+flnm));
}
Пример #19
0
void CUnitVolumeMakerDlg::GetImage(int iWidth, int iLength, int iHeight, int iZ,
								 EZoomOut eZoomOutLevel)
{
	int nCol;
	int nX, nY, nZ;
	int nRibbonWidth;
	int nImageWidth;
	int nRightWidth;
	int nTotalWidth;
	QString strPathName, strImageFileName, strImageVolPathName, strImage4VolFileName;
	
	nRibbonWidth = qRound(float(m_TissueBlock.m_Ribbon.m_nWidth)/eZoomOutLevel);
	nCol = (int)((m_TissueBlock.m_UnitCube.m_nWidth*iWidth)/nRibbonWidth);
	nX = nRibbonWidth - (nRibbonWidth*(nCol+1)-(iWidth*m_TissueBlock.m_UnitCube.m_nWidth));
	nY = iLength*m_TissueBlock.m_UnitCube.m_nLength;
	nZ = iHeight*m_TissueBlock.m_UnitCube.m_nHeight;
	strPathName = QString(tr("%1%2%3/%4/")
			.arg(sINIT_DATA_DIR).arg(sZOOM_OUT_DIR_PREFIX).arg(eZoomOutLevel).arg(nCol));
	strImageFileName.sprintf("%05d%s", nZ+eZoomOutLevel*iZ, sDATA_FILE_FORMAT);
		
	nRightWidth = nRibbonWidth - nX;
	
	if(nRightWidth > m_TissueBlock.m_UnitCube.m_nWidth)
	{
		nImageWidth = qMin(m_TissueBlock.m_UnitCube.m_nWidth, nRibbonWidth);
	}
	else
	{
		nImageWidth = nRightWidth;
	}
	
	// extract nX, nY, nImageWidth, m_TissueBlock.m_UnitCube.m_nLength
	//...
	qDebug() << "nX: " << nX << ", nY: " << nY << ", nImageWidth: " << nImageWidth << "\n";
	ui.listWidgetResult->addItem(tr("nCol: %1, nX: %2, nY: %3, nImageWidth: %4").arg(nCol).arg(nX).arg(nY).arg(nImageWidth));
	ui.listWidgetResult->addItem(strPathName);
	ui.listWidgetResult->addItem(strImageFileName);
	
	// source image filename (full path)
	QString strFileName = strPathName + strImageFileName;
	
	/////////////////////////
	// read an image
	// typedef
	
	typedef unsigned char PixelType;
	const unsigned int nDimension = 2;
	typedef itk::Image<PixelType, nDimension> ImageType;
	typedef itk::ImageFileReader<ImageType> ReaderType;
	typedef itk::ImageFileWriter<ImageType> WriterType;
	//typedef itk::RegionOfInterestImageFilter<ImageType, ImageType> ROIFilterType;
	typedef itk::ImageRegionConstIterator< ImageType > ConstIteratorType;
	typedef itk::ImageRegionIterator< ImageType>       IteratorType;

	/////////////////////////////////////
	// input: a region of a source image 
	ImageType::RegionType InputRegion;
	ImageType::RegionType::IndexType InputStart;
	ImageType::RegionType::SizeType  InputSize;
	
	InputStart[0] = nX;
	InputStart[1] = nY;
	
	InputSize[0]  = nImageWidth;
	InputSize[1]  = m_TissueBlock.m_UnitCube.m_nLength;
	
	InputRegion.SetSize( InputSize );
	InputRegion.SetIndex( InputStart );
	
	/////////////////////////////////////
	// output: a region of a output image 
	ImageType::RegionType OutputRegion, OutputSubRegion;
	ImageType::RegionType::IndexType OutputStart;
	ImageType::RegionType::SizeType  OutputSize;

	OutputStart[0] = 0;
	OutputStart[1] = 0;
	OutputSize[0]  = m_TissueBlock.m_UnitCube.m_nWidth; //InputSize[0];
	OutputSize[1]  = m_TissueBlock.m_UnitCube.m_nLength; //InputSize[1];

	OutputRegion.SetSize( OutputSize );
	OutputRegion.SetIndex( OutputStart );

	OutputSize[0]  = InputSize[0];
	OutputSize[1]  = InputSize[1];

	OutputSubRegion.SetSize( OutputSize );
	OutputSubRegion.SetIndex( OutputStart );

	bool bErrorInSourceImage = false;

	/////////////////////////////////////
	// read the source image
	ReaderType::Pointer pReader = ReaderType::New();
	pReader->SetFileName(strFileName.toStdString());
	try
	{
	    pReader->Update();
	}
	catch ( itk::ExceptionObject &err)
	{
	    std::cerr << "ExceptionObject caught !" << std::endl; 
	    std::cerr << err << std::endl; 
	    bErrorInSourceImage = true;
	    //return; // -1;
	}

	// Check that the region is contained within the input image.
	if(!pReader->GetOutput()->GetRequestedRegion().IsInside( InputRegion ) )
	{
	    std::cerr << "Error" << std::endl;
	    std::cerr << "The region " << InputRegion << "is not contained within the input image region "
	              << pReader->GetOutput()->GetRequestedRegion() << std::endl;
	    bErrorInSourceImage = true;
	    //return; // -1;
	}
	
	////////////////////////////////////
	// prepare the output
	ImageType::Pointer pOutputImage = ImageType::New();
	pOutputImage->SetRegions( OutputRegion );
	pOutputImage->Allocate();

	///////////////////////////////////
	// fill buffer with initial value
	ImageType::PixelType  InitialValue = nDEF_BG_COLOR;
	pOutputImage->FillBuffer( InitialValue );
	
	/////////////////////////////////////////////////////////////////////////
	// get pixels from the source image file and put them into the output image file
	if(bErrorInSourceImage != true)
	{
		ConstIteratorType InputIt(   pReader->GetOutput(), InputRegion  );
		IteratorType      OutputIt(  pOutputImage,         OutputSubRegion );
	
		for(InputIt.GoToBegin(), OutputIt.GoToBegin(); !InputIt.IsAtEnd(); ++InputIt, ++OutputIt)
		{
		    OutputIt.Set(InputIt.Get());
		}
	}

	nTotalWidth = nImageWidth;

	while(nTotalWidth < m_TissueBlock.m_UnitCube.m_nWidth)
	{
		nCol++;
		if(nCol == m_TissueBlock.m_nNumCol)
			break;
		nX = 0;
		nImageWidth = m_TissueBlock.m_UnitCube.m_nWidth - nTotalWidth;
		if(nImageWidth > nRibbonWidth)
		{
			nImageWidth = nRibbonWidth;
		}
	
		strPathName = QString(tr("%1%2%3/%4/")
				.arg(sINIT_DATA_DIR).arg(sZOOM_OUT_DIR_PREFIX).arg(eZoomOutLevel).arg(nCol));
		strImageFileName.sprintf("%05d%s", nZ+eZoomOutLevel*iZ, sDATA_FILE_FORMAT);

		// extract nX, nY, nImageWidth, m_TissueBlock.m_UnitCube.m_nLength
		// for display
		qDebug() << "nX: " << nX << ", nY: " << nY << ", nImageWidth: " << nImageWidth << "\n";
		ui.listWidgetResult->addItem(tr("nCol: %1, nX: %2, nY: %3, nImageWidth: %4").arg(nCol).arg(nX).arg(nY).arg(nImageWidth));
		ui.listWidgetResult->addItem(strPathName);
		ui.listWidgetResult->addItem(strImageFileName);
		// source image filename (full path)
		strFileName = strPathName + strImageFileName;
		
		// set input size
		InputStart[0] = nX;
		InputStart[1] = nY;
		
		InputSize[0]  = nImageWidth;
		InputSize[1]  = m_TissueBlock.m_UnitCube.m_nLength;
		
		InputRegion.SetSize( InputSize );
		InputRegion.SetIndex( InputStart );
		
		OutputSize[0]  = InputSize[0];
		OutputSize[1]  = InputSize[1];

		ImageType::RegionType::IndexType OutputStartSub;
		OutputStartSub[0] = nTotalWidth;
		OutputStartSub[1] = 0;
		OutputSubRegion.SetSize( OutputSize );
		OutputSubRegion.SetIndex( OutputStartSub );

		bErrorInSourceImage = false;
		/////////////////////////////////////
		// read the source image
		//ReaderType::Pointer pReader = ReaderType::New();
		pReader->SetFileName(strFileName.toStdString());
		try
		{
		    pReader->Update();
		}
		catch ( itk::ExceptionObject &err)
		{
		    std::cerr << "ExceptionObject caught !" << std::endl; 
		    std::cerr << err << std::endl; 
		    bErrorInSourceImage = true;
		    //return; // -1;
		}

		// Check that the region is contained within the input image.
		if(!pReader->GetOutput()->GetRequestedRegion().IsInside( InputRegion ) )
		{
		    std::cerr << "Error" << std::endl;
		    std::cerr << "The region " << InputRegion << "is not contained within the input image region "
		              << pReader->GetOutput()->GetRequestedRegion() << std::endl;
		    bErrorInSourceImage = true;
		    //return; // -1;
		}
		
		////////////////////////////////////
		// prepare the output
		//ImageType::Pointer pOutputImage = ImageType::New();
		//pOutputImage->SetRegions( OutputRegion );
		//pOutputImage->Allocate();
		if(bErrorInSourceImage != true)
		{
			ConstIteratorType InputIt(   pReader->GetOutput(), InputRegion  );
			IteratorType      OutputIt(  pOutputImage,         OutputSubRegion );
	
			for(InputIt.GoToBegin(), OutputIt.GoToBegin(); !InputIt.IsAtEnd(); ++InputIt, ++OutputIt)
			{
			    OutputIt.Set(InputIt.Get());
			}
		}
		
		nTotalWidth += nImageWidth;

	}
	
	/////////////////////////////////////////////////////////
	// get an output image file name (full path)
	strImageVolPathName = QString(tr("%1%2%3/%4/")
			.arg(sINIT_DATA_DIR).arg(sZOOM_OUT_DIR_PREFIX).arg(eZoomOutLevel).arg(sVOL_DIR_PREFIX));
	QString strVolDir;
	strVolDir.sprintf("%03d_%03d_%03d", iWidth, iLength, iHeight);
	strVolDir = strImageVolPathName + strVolDir;
	QDir dir;
	dir.mkdir(strImageVolPathName);
	dir.mkdir(strVolDir);
	strImage4VolFileName.sprintf("%03d_%03d_%03d/%05d%s", 
			iWidth, iLength, iHeight, nZ+eZoomOutLevel*iZ, sDATA_FILE_FORMAT);
	strImage4VolFileName = strImageVolPathName + strImage4VolFileName;

	/////////////////////////////////
	// write an output image
	WriterType::Pointer pWriter = WriterType::New();
	pWriter->SetFileName(strImage4VolFileName.toStdString());
	pWriter->SetInput( pOutputImage );

	try
	{
		pWriter->Update();
	}
	catch ( itk::ExceptionObject &err)
	{
	    std::cerr << "ExceptionObject caught !" << std::endl; 
	    std::cerr << err << std::endl; 
	    return; // -1;   
	}

}
Пример #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;
}
Пример #21
0
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;
}