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; } }
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; }
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; }
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; }
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); }
// ------------------------------------------------------------------------ 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; } } }
/* * 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); }
// ------------------------------------------------------------------------ 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(); }
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(); }
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); }
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(); }
void Initialisation::savePointAsBinaryImage(ImageType::Pointer initialImage, string filename, OrientationType orientation) { if (points_.size() > 0) { typedef itk::Image< unsigned char, 3 > BinaryImageType; BinaryImageType::Pointer binary = BinaryImageType::New(); ImageType::RegionType region; ImageType::IndexType start; start[0] = 0; start[1] = 0; start[2] = 0; ImageType::SizeType size, imSize = initialImage->GetLargestPossibleRegion().GetSize(); size[0] = imSize[0]; size[1] = imSize[1]; size[2] = imSize[2]; region.SetSize(size); region.SetIndex(start); binary->CopyInformation(initialImage); binary->SetRegions(region); binary->Allocate(); binary->FillBuffer(false); typedef ImageType::IndexType IndexType; ContinuousIndex ind; IndexType ind2; unsigned int pSize = points_.size(); unsigned int indexMiddle = 0; for (unsigned int i=0; i<pSize; i++) { if (points_[i][1] == startSlice_) indexMiddle = i; } ind[0] = points_[indexMiddle][0]; ind[1] = points_[indexMiddle][1]; ind[2] = points_[indexMiddle][2]; PointType pt; inputImage_->TransformContinuousIndexToPhysicalPoint(ind, pt); initialImage->TransformPhysicalPointToIndex(pt, ind2); binary->SetPixel(ind2,true); OrientImage<BinaryImageType> orientationFilter; orientationFilter.setInputImage(binary); orientationFilter.orientation(orientation); binary = orientationFilter.getOutputImage(); ImageIterator it( binary, binary->GetRequestedRegion() ); it.GoToBegin(); while(!it.IsAtEnd()) { if (it.Get()==true) { ind2 = it.GetIndex(); break; } ++it; } if (verbose_) cout << "Center of spinal cord saved on pixel : " << ind2 << endl; WriterBinaryType::Pointer writer = WriterBinaryType::New(); itk::NiftiImageIO::Pointer io = itk::NiftiImageIO::New(); writer->SetImageIO(io); writer->SetFileName(filename); writer->SetInput(binary); try { writer->Write(); } catch( itk::ExceptionObject & e ) { std::cerr << "Exception caught while writing image " << std::endl; std::cerr << e << std::endl; } } else cout << "Error: Spinal cord center not detected" << endl; }
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; }
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); }
void gradient_calc(int S_i, float* S, int i, int j, int k, float* data, int r, int s, int t, unsigned short* output_label){ //cout<<"Starting Definitions..."<<endl; //define the pixel and image types typedef float PixelType; typedef itk::Image<PixelType, 3> ImageType; typedef itk::CovariantVector< double, 3 > GradientPixelType; typedef itk::Image< GradientPixelType, 3 > GradientImageType; typedef itk::GradientRecursiveGaussianImageFilter<ImageType, GradientImageType> GradientFilterType; //Initialize a new image which will read the input label ImageType::Pointer image = ImageType::New(); ImageType::IndexType start; start[0] = 0; start[1] = 0; start[2] = 0; ImageType::SizeType size; size[0] = k; size[1] = j; size[2] = i; ImageType::SpacingType spacing; spacing[0] = S[0]; spacing[1] = S[1]; spacing[2] = S[2]; //cout<<"X_space="<<spacing[0]<<", Y_space="<<spacing[1]<<", Z_space="<<spacing[2]<<endl; image->SetSpacing( spacing ); ImageType::RegionType region; region.SetSize( size ); region.SetIndex( start ); image->SetRegions( region ); image->Allocate(); //Create an image iterator to copy the input label into the image file typedef itk::ImageRegionIterator< ImageType > IteratorType; IteratorType it( image, image->GetRequestedRegion() ); int count = 0; while(!it.IsAtEnd()){ it.Set( data[ count ] ); ++it; count++; } //Calculate the vector gradient of the image GradientFilterType::Pointer gradientMapFilter = GradientFilterType::New(); gradientMapFilter->SetInput( image ); gradientMapFilter->SetSigma( 1.0 ); gradientMapFilter->Update(); //Creates a new image and iterator of the gradient GradientImageType::Pointer image2 = gradientMapFilter->GetOutput(); typedef itk::ImageRegionConstIterator< GradientImageType > IteratorType2; IteratorType2 it2( image2, image2->GetRequestedRegion() ); //ImageType::IndexType idx = it2.GetIndex(); //Outputs the input image to test if the input worked correctly ImageType::RegionType region2 = image2->GetLargestPossibleRegion(); long int count2 = 0; while(!it2.IsAtEnd()){ //while(count2 < (r * s * t - 1)){ float magnitude = sqrt(it2.Get()[0] * it2.Get()[0] + it2.Get()[1] * it2.Get()[1] + it2.Get()[2] * it2.Get()[2]); output_label[ count2 ] = magnitude ; count2++; ++it2; } }
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; } }
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; }
void CAxialFor3DView::cropImage(ImagePointer source , ImagePointer target,int nStartSlice, int nEndSlice) { const unsigned int Dimension = 3; typedef itk::ImageRegionConstIterator< ImageType > ConstIteratorType; typedef itk::ImageRegionIterator< ImageType> IteratorType; ImageType::RegionType inputRegion; ImageType::RegionType::IndexType inputStart; ImageType::RegionType::SizeType size; inputStart[0] = 0;//174 m_nCropStart[0] inputStart[1] = 0;//160 m_nCropStart[1] inputStart[2] = nStartSlice; size[0] = m_nWidth;//193 m_nCropSize[0] size[1] = m_nHeight;//193 m_nCropSize[1] size[2] = nEndSlice-nStartSlice+1;//350 746 inputRegion.SetSize( size ); inputRegion.SetIndex( inputStart ); ImageType::RegionType outputRegion; ImageType::RegionType::IndexType outputStart; outputStart[0] = 0; outputStart[1] = 0; outputStart[2] = 0; outputRegion.SetSize( size ); outputRegion.SetIndex( outputStart ); target->SetRegions( outputRegion ); const ImageType::SpacingType& spacing = source->GetSpacing(); const ImageType::PointType& inputOrigin = source->GetOrigin(); double outputOrigin[ Dimension ]; for(unsigned int i=0; i< Dimension; i++) { outputOrigin[i] = inputOrigin[i] + spacing[i] * inputStart[i]; } target->SetSpacing( spacing ); target->SetOrigin( outputOrigin ); target->Allocate(); ConstIteratorType inputIt( source, inputRegion ); IteratorType outputIt( target, outputRegion ); for ( inputIt.GoToBegin(), outputIt.GoToBegin(); !inputIt.IsAtEnd(); ++inputIt, ++outputIt) { outputIt.Set( inputIt.Get() ); } itkVTKResampleExporter->SetInput(target); VTKResampleImporter->SetDataOrigin(0,0,0); itkVTKResampleExporter->Update(); greyPadder->SetInput(VTKResampleImporter->GetOutput()); greyPadder->SetOutputWholeExtent(0,m_nWidth,0,m_nHeight,0,0); greyPadder->SetConstant(0); m_nSliceSum=nEndSlice-nStartSlice; m_bCropImage=true; VTKImporter->Delete(); source->ReleaseData(); //seriesReader->Delete(); //itkVTKExporter->RemoveInput(); //itkVTKExporter->RemoveOutput(); }
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; }
Matrix<int> getCCLabeling(Matrix<int> p, bool recip){ Matrix<int> m = Matrix<int>(p.getXdim(), p.getYdim(), 1); if(recip){ for(int i=0; i<p.getXdim(); i++) for(int j=0; j<p.getYdim(); j++) if(p(i,j) == 1) m(i,j) = 0; }else{ for(int i=0; i<p.getXdim(); i++) for(int j=0; j<p.getYdim(); j++) m(i,j) = p(i,j); } const unsigned int Dimension = 2; typedef unsigned char PixelType; typedef itk::RGBPixel<unsigned char> RGBPixelType; typedef itk::Image<PixelType, 2> ImageType; typedef itk::Image<RGBPixelType, 2> RGBImageType; //fill ITK image type ImageType::Pointer image = ImageType::New(); typename ImageType::IndexType start;// = {{0,0}};//TImage::IndexType start = {{0,0}}; start[0] = 0; start[1] = 0; typename ImageType::SizeType size; unsigned int NumRows = m.getXdim(); unsigned int NumCols = m.getYdim(); size[0] = NumRows; size[1] = NumCols; ImageType::RegionType region;// region(start, size); region.SetSize(size); region.SetIndex(start); //region.SetSize(size); image->SetRegions(region); image->Allocate(); //cout << "here" << endl; for(typename ImageType::IndexValueType r = 0; r < m.getXdim(); r++) { for(typename ImageType::IndexValueType c = 0; c < m.getYdim(); c++) { typename ImageType::IndexType pixelIndex = {{r,c}}; if(m(r,c) == 1) image->SetPixel(pixelIndex, 255); else image->SetPixel(pixelIndex, 0); //image->SetPixel(pixelIndex, 255); } } //cout << "got here" << endl; typedef itk::Image< unsigned short, Dimension > OutputImageType; typedef itk::ConnectedComponentImageFilter <ImageType, OutputImageType > ConnectedComponentImageFilterType; ConnectedComponentImageFilterType::Pointer connected = ConnectedComponentImageFilterType::New (); connected->SetInput(image); connected->Update(); //cout << "got CC" << endl; //std::cout << "Number of objects: " << connected->GetObjectCount() << std::endl; Matrix<int> out = Matrix<int>(m.getXdim(), m.getYdim(), 0); //connected->SetMaskImage(image); //connected->GetOutput(); for(typename ImageType::IndexValueType r = 0; r < m.getXdim(); r++) { for(typename ImageType::IndexValueType c = 0; c < m.getYdim(); c++) { typename ImageType::IndexType pixelIndex = {{r,c}}; out(r,c) = connected->GetOutput()->GetPixel(pixelIndex); //out(r,c) = image->GetPixel(pixelIndex); } } return out; }
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; } }
static void testGeneratedImage() { // create itk rgb image typedef unsigned char PixelType; typedef itk::Image< itk::RGBPixel<PixelType>, 2 > ImageType; ImageType::Pointer itkImage = ImageType::New(); ImageType::IndexType start; start[0] = 0; // first index on X start[1] = 0; // first index on Y ImageType::SizeType size; size[0] = 50; // size along X size[1] = 40; // size along Y ImageType::RegionType region; region.SetSize( size ); region.SetIndex( start ); itkImage->SetRegions( region ); itkImage->Allocate(); typedef itk::ImageRegionIterator<ImageType> IteratorType; IteratorType it(itkImage, region); float twoThirdsTheWidth = size[0] / 4; unsigned int x=0, y=0; // create rgb pic for ( it.GoToBegin(); !it.IsAtEnd(); ++it ) { ImageType::PixelType newPixel; newPixel.SetRed(0); newPixel.SetGreen(0); // create asymmetric pic if( x > twoThirdsTheWidth ) newPixel.SetBlue(0); else newPixel.SetBlue(255); it.Set(newPixel); ++x; // next line found if( x == size[0] ) x = 0; } // debugging // itk::ImageFileWriter< ImageType >::Pointer writer = itk::ImageFileWriter< ImageType >::New(); // writer->SetFileName( "c:\\image.png" ); // writer->SetInput ( itkImage ); // writer->Update(); // import rgb image as MITK image mitk::Image::Pointer mitkImage = mitk::ImportItkImage(itkImage)->Clone(); mitk::ImageToOpenCVImageFilter::Pointer _ImageToOpenCVImageFilter = mitk::ImageToOpenCVImageFilter::New(); _ImageToOpenCVImageFilter->SetImage( mitkImage ); IplImage* openCVImage = _ImageToOpenCVImageFilter->GetOpenCVImage(); MITK_TEST_CONDITION_REQUIRED( openCVImage != NULL, "Image returned by filter is not null."); // check byte size const unsigned int expectedSize = size[0] * size[1] * 3 * sizeof( unsigned char);// sizeof( PixelType ); const unsigned int realSize = openCVImage->width * openCVImage->height * openCVImage->nChannels * sizeof( unsigned char);//* sizeof ( PixelType ); MITK_TEST_CONDITION_REQUIRED( expectedSize == realSize, "Test expectedSize == realSize"); // check pixel values PixelType expectedBlueValue; CvScalar s; for (y = 0; (int)y < openCVImage->height; ++y) { for (x = 0; (int)x < openCVImage->width; ++x) { expectedBlueValue = 255; if(x > twoThirdsTheWidth) expectedBlueValue = 0; s = cvGet2D(openCVImage,y,x); if( s.val[0] != expectedBlueValue || s.val[1] != 0 || s.val[2] != 0 ) { std::cout << "Wrong RGB values in created OpenCV image" << std::endl; throw mitk::TestFailedException(); } } } // cvNamedWindow( "test" ); // cvShowImage( "test" , openCVImage ); // cvWaitKey(); }
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 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... }
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; }
/** * 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; }
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; }
int main(int, char ** argv) { std::string inputFolder = argv[1]; std::string outputFolder = argv[2]; std::string lookupFilename = argv[3]; // load the lookup file and read the image filenames LookupMap lookup; FilenamesType imageFilenames; readFilenames(inputFolder, imageFilenames); loadLookupFile(lookupFilename, lookup); // looop through the list of images for(unsigned int i = 0; i < imageFilenames.size(); i++) { std::string fname = imageFilenames[i]; QFileInfo finfo(QString::fromStdString(fname)); std::string basename = finfo.completeBaseName().toStdString() + ".nrrd"; FilenamesType dicomFilenames = lookup[basename]; // slice up the input image to recreate the output typedef utils::ImageVolume ImageType; ImageType::Pointer input = utils::ImageVolumeIO::Read(fname); const unsigned int slices = input->GetLargestPossibleRegion().GetSize()[2]; for(unsigned int slice = 0; slice < slices; slice++) { typedef itk::RegionOfInterestImageFilter<ImageType, ImageType> ROIFilter; ROIFilter::Pointer roiFilter = ROIFilter::New(); roiFilter->SetInput(input); ImageType::RegionType roi = input->GetLargestPossibleRegion(); ImageType::IndexType roiIndex = roi.GetIndex(); ImageType::SizeType roiSize = roi.GetSize(); roiIndex[2] = slice; roiSize[2] = 1; roi.SetSize(roiSize); roi.SetIndex(roiIndex); roiFilter->SetRegionOfInterest(roi); roiFilter->Update(); ImageType::Pointer imSlice = roiFilter->GetOutput(); // load the dicom file std::string dicomFilename = dicomFilenames[slice]; DcmFileFormat fileFormat; fileFormat.loadFile(dicomFilename.c_str()); unsigned int numberOfPixels = imSlice->GetLargestPossibleRegion().GetNumberOfPixels(); unsigned short * buffer = new unsigned short[numberOfPixels]; fileFormat.getDataset()->putAndInsertUint16Array(DCM_PixelData, buffer, imSlice->GetLargestPossibleRegion().GetNumberOfPixels()); // reset the pixel values itk::ImageRegionConstIterator<ImageType> it(imSlice, imSlice->GetLargestPossibleRegion()); unsigned int count = 0; while(!it.IsAtEnd()) { buffer[count] = it.Get(); ++it; ++count; } fileFormat.getDataset()->putAndInsertUint16Array(DCM_PixelData, buffer, imSlice->GetLargestPossibleRegion().GetNumberOfPixels()); // create the output filename std::stringstream ss; ss << outputFolder << "/dicom_" << i << "_" << slice << ".dcm"; fileFormat.saveFile(ss.str().c_str()); } } return 0; }