BinaryImageType::Pointer readBinaryImage(const std::string& filename) { ImageReaderType::Pointer reader = ImageReaderType::New(); reader->SetFileName(filename.c_str()); reader->Update(); // we make sure that the image really has value 0 and 1 typedef itk::BinaryThresholdImageFilter<BinaryImageType, BinaryImageType> ThresholdFilterType; ThresholdFilterType::Pointer thresholdFilter = ThresholdFilterType::New(); thresholdFilter->SetInsideValue(1); thresholdFilter->SetOutsideValue(0); thresholdFilter->SetLowerThreshold(1); thresholdFilter->SetUpperThreshold(255); thresholdFilter->SetInput(reader->GetOutput()); thresholdFilter->Update(); BinaryImageType::Pointer img = thresholdFilter->GetOutput(); img->DisconnectPipeline(); return img; }
void mitk::SurfaceStampImageFilter::SurfaceStampBinaryOutputProcessing(MeshType *mesh) { auto *inputImage = this->GetInput(); mitk::Image::Pointer outputImage = this->GetOutput(); typedef itk::Image<unsigned char, 3> BinaryImageType; BinaryImageType::Pointer itkInputImage; mitk::CastToItkImage(inputImage, itkInputImage); typedef itk::TriangleMeshToBinaryImageFilter<MeshType, BinaryImageType> FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput(mesh); filter->SetInfoImage(itkInputImage); filter->SetInsideValue(1); filter->SetOutsideValue(0); filter->Update(); BinaryImageType::Pointer resultImage = filter->GetOutput(); resultImage->DisconnectPipeline(); mitk::CastToMitkImage(resultImage, outputImage); }
void Image3D::TransformMeshToBinaryImage(Mesh* m, string filename, OrientationType orient, bool sub_segmentation, bool cropUpDown, CVector3* upperSlicePoint, CVector3* upperSliceNormal, CVector3* downSlicePoint, CVector3* downSliceNormal) { //m->subdivision(2); MeshTypeB::Pointer mesh; MeshFilterType::Pointer meshFilter = MeshFilterType::New(); if (cropUpDown) { mesh = MeshTypeB::New(); vtkSmartPointer<vtkPolyData> polyData; try { polyData = m->reduceMeshUpAndDown(*upperSlicePoint, *upperSliceNormal, *downSlicePoint, *downSliceNormal); } catch (const exception& e) { cout << e.what() << endl; } vtkSmartPointer<vtkFillHolesFilter> fillHolesFilter = vtkSmartPointer<vtkFillHolesFilter>::New(); fillHolesFilter->SetInputData(polyData); fillHolesFilter->SetHoleSize(1000.0); fillHolesFilter->Update(); // Make the triangle windong order consistent vtkSmartPointer<vtkPolyDataNormals> normals = vtkSmartPointer<vtkPolyDataNormals>::New(); normals->SetInputData(fillHolesFilter->GetOutput()); normals->ConsistencyOn(); normals->SplittingOff(); normals->Update(); // Restore the original normals normals->GetOutput()->GetPointData()->SetNormals(polyData->GetPointData()->GetNormals()); polyData = normals->GetOutput(); // // Transfer the points from the vtkPolyData into the itk::Mesh // const unsigned int numberOfPoints = polyData->GetNumberOfPoints(); vtkPoints * vtkpoints = polyData->GetPoints(); mesh->GetPoints()->Reserve( numberOfPoints ); for(unsigned int p =0; p < numberOfPoints; p++) { double * apoint = vtkpoints->GetPoint( p ); mesh->SetPoint( p, MeshTypeB::PointType( apoint )); } // // Transfer the cells from the vtkPolyData into the itk::Mesh // vtkCellArray * triangleStrips = polyData->GetStrips(); vtkIdType * cellPoints; vtkIdType numberOfCellPoints; // // First count the total number of triangles from all the triangle strips. // unsigned int numberOfTriangles = 0; triangleStrips->InitTraversal(); while( triangleStrips->GetNextCell( numberOfCellPoints, cellPoints ) ) { numberOfTriangles += numberOfCellPoints-2; } vtkCellArray * polygons = polyData->GetPolys(); polygons->InitTraversal(); while( polygons->GetNextCell( numberOfCellPoints, cellPoints ) ) { if( numberOfCellPoints == 3 ) { numberOfTriangles ++; } } // // Reserve memory in the itk::Mesh for all those triangles // mesh->GetCells()->Reserve( numberOfTriangles ); // // Copy the triangles from vtkPolyData into the itk::Mesh // // typedef MeshTypeB::CellType CellType; typedef itk::TriangleCell< CellType > TriangleCellType; int cellId = 0; // first copy the triangle strips triangleStrips->InitTraversal(); while( triangleStrips->GetNextCell( numberOfCellPoints, cellPoints ) ) { unsigned int numberOfTrianglesInStrip = numberOfCellPoints - 2; unsigned long pointIds[3]; pointIds[0] = cellPoints[0]; pointIds[1] = cellPoints[1]; pointIds[2] = cellPoints[2]; for( unsigned int t=0; t < numberOfTrianglesInStrip; t++ ) { MeshTypeB::CellAutoPointer c; TriangleCellType * tcell = new TriangleCellType; tcell->SetPointIds( pointIds ); c.TakeOwnership( tcell ); mesh->SetCell( cellId, c ); cellId++; pointIds[0] = pointIds[1]; pointIds[1] = pointIds[2]; pointIds[2] = cellPoints[t+3]; } } // then copy the normal triangles polygons->InitTraversal(); while( polygons->GetNextCell( numberOfCellPoints, cellPoints ) ) { if( numberOfCellPoints !=3 ) // skip any non-triangle. { continue; } MeshTypeB::CellAutoPointer c; TriangleCellType * t = new TriangleCellType; t->SetPointIds( (unsigned long*)cellPoints ); c.TakeOwnership( t ); mesh->SetCell( cellId, c ); cellId++; } meshFilter->SetInput(mesh); } else { mesh = MeshTypeB::New(); vector<Vertex*> points = m->getListPoints(); PointType pnt; CVector3 p, n; for (unsigned int i=0; i<points.size(); i++) { p = points[i]->getPosition(); n = points[i]->getNormal(); pnt[0] = p[0]; pnt[1] = p[1]; pnt[2] = p[2]; mesh->SetPoint(i,pnt); } vector<int> triangles = m->getListTriangles(); for (unsigned int i=0; i<triangles.size(); i+=3) { CellTypeB::CellAutoPointer triangle; triangle.TakeOwnership(new CellTypeB); triangle->SetPointId(0,triangles[i]); triangle->SetPointId(1,triangles[i+1]); triangle->SetPointId(2,triangles[i+2]); mesh->SetCell((int)(i+1)/3,triangle); } meshFilter->SetInput(mesh); } meshFilter->SetOrigin(imageOriginale_->GetOrigin()); meshFilter->SetSpacing(imageOriginale_->GetSpacing()); meshFilter->SetSize(imageOriginale_->GetLargestPossibleRegion().GetSize()); meshFilter->SetDirection(imageOriginale_->GetDirection()); meshFilter->SetIndex(imageOriginale_->GetLargestPossibleRegion().GetIndex()); //meshFilter->SetTolerance(1.0); meshFilter->SetInsideValue(1.0); meshFilter->SetOutsideValue(0.0); try { meshFilter->Update(); } catch( itk::ExceptionObject & e ) { cout << "Exception thrown ! " << endl; cout << "An error ocurred during creating binary image" << endl; cout << "Location = " << e.GetLocation() << endl; cout << "Description = " << e.GetDescription() << endl; } BinaryImageType::Pointer im = meshFilter->GetOutput(); if (!sub_segmentation) { imageSegmentation_ = im; } else { BinaryImageType::RegionType region = im->GetLargestPossibleRegion(); itk::ImageRegionConstIterator<BinaryImageType> imageIterator(im,region); unsigned char pixel, pixel_seg; BinaryIndexType index; while(!imageIterator.IsAtEnd()) { index = imageIterator.GetIndex(); pixel = imageIterator.Get(); pixel_seg = imageSegmentation_->GetPixel(index); im->SetPixel(index,pixel && !pixel_seg); ++imageIterator; } } OrientImage<BinaryImageType> orientationFilter; orientationFilter.setInputImage(im); orientationFilter.orientation(orient); im = orientationFilter.getOutputImage(); // Write the image typedef itk::ImageFileWriter< BinaryImageType > WriterType; WriterType::Pointer writer = WriterType::New(); itk::NiftiImageIO::Pointer io = itk::NiftiImageIO::New(); writer->SetImageIO(io); writer->SetFileName(filename); writer->SetInput(im); try { writer->Update(); } catch( itk::ExceptionObject & e ) { cout << "Exception thrown ! " << endl; cout << "An error ocurred during Writing" << endl; cout << "Location = " << e.GetLocation() << endl; cout << "Description = " << e.GetDescription() << endl; } }
static mitk::Image::Pointer ResampleBySpacing(mitk::Image *input, float *spacing, bool useLinInt = true, bool useNN = false) { if (!useNN) { InputImageType::Pointer itkImage = InputImageType::New(); CastToItkImage(input,itkImage); /** * 1) Resampling * */ // Identity transform. // We don't want any transform on our image except rescaling which is not // specified by a transform but by the input/output spacing as we will see // later. // So no transform will be specified. typedef itk::IdentityTransform<double, 3> T_Transform; // The resampler type itself. typedef itk::ResampleImageFilter<InputImageType, InputImageType> T_ResampleFilter; // Prepare the resampler. // Instantiate the transform and specify it should be the id transform. T_Transform::Pointer _pTransform = T_Transform::New(); _pTransform->SetIdentity(); // Instantiate the resampler. Wire in the transform and the interpolator. T_ResampleFilter::Pointer _pResizeFilter = T_ResampleFilter::New(); // Specify the input. _pResizeFilter->SetInput(itkImage); _pResizeFilter->SetTransform(_pTransform); // Set the output origin. _pResizeFilter->SetOutputOrigin(itkImage->GetOrigin()); // Compute the size of the output. // The size (# of pixels) in the output is recomputed using // the ratio of the input and output sizes. InputImageType::SpacingType inputSpacing = itkImage->GetSpacing(); InputImageType::SpacingType outputSpacing; const InputImageType::RegionType& inputSize = itkImage->GetLargestPossibleRegion(); InputImageType::SizeType outputSize; typedef InputImageType::SizeType::SizeValueType SizeValueType; // Set the output spacing. outputSpacing[0] = spacing[0]; outputSpacing[1] = spacing[1]; outputSpacing[2] = spacing[2]; outputSize[0] = static_cast<SizeValueType>(inputSize.GetSize()[0] * inputSpacing[0] / outputSpacing[0] + .5); outputSize[1] = static_cast<SizeValueType>(inputSize.GetSize()[1] * inputSpacing[1] / outputSpacing[1] + .5); outputSize[2] = static_cast<SizeValueType>(inputSize.GetSize()[2] * inputSpacing[2] / outputSpacing[2] + .5); _pResizeFilter->SetOutputSpacing(outputSpacing); _pResizeFilter->SetSize(outputSize); typedef itk::LinearInterpolateImageFunction< InputImageType > LinearInterpolatorType; LinearInterpolatorType::Pointer lin_interpolator = LinearInterpolatorType::New(); typedef itk::WindowedSincInterpolateImageFunction< InputImageType, 4> WindowedSincInterpolatorType; WindowedSincInterpolatorType::Pointer sinc_interpolator = WindowedSincInterpolatorType::New(); if (useLinInt) _pResizeFilter->SetInterpolator(lin_interpolator); else _pResizeFilter->SetInterpolator(sinc_interpolator); _pResizeFilter->Update(); mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk(_pResizeFilter->GetOutput()); mitk::GrabItkImageMemory( _pResizeFilter->GetOutput(), image); return image; } BinaryImageType::Pointer itkImage = BinaryImageType::New(); CastToItkImage(input,itkImage); /** * 1) Resampling * */ // Identity transform. // We don't want any transform on our image except rescaling which is not // specified by a transform but by the input/output spacing as we will see // later. // So no transform will be specified. typedef itk::IdentityTransform<double, 3> T_Transform; // The resampler type itself. typedef itk::ResampleImageFilter<BinaryImageType, BinaryImageType> T_ResampleFilter; // Prepare the resampler. // Instantiate the transform and specify it should be the id transform. T_Transform::Pointer _pTransform = T_Transform::New(); _pTransform->SetIdentity(); // Instantiate the resampler. Wire in the transform and the interpolator. T_ResampleFilter::Pointer _pResizeFilter = T_ResampleFilter::New(); // Specify the input. _pResizeFilter->SetInput(itkImage); _pResizeFilter->SetTransform(_pTransform); // Set the output origin. _pResizeFilter->SetOutputOrigin(itkImage->GetOrigin()); // Compute the size of the output. // The size (# of pixels) in the output is recomputed using // the ratio of the input and output sizes. BinaryImageType::SpacingType inputSpacing = itkImage->GetSpacing(); BinaryImageType::SpacingType outputSpacing; const BinaryImageType::RegionType& inputSize = itkImage->GetLargestPossibleRegion(); BinaryImageType::SizeType outputSize; typedef BinaryImageType::SizeType::SizeValueType SizeValueType; // Set the output spacing. outputSpacing[0] = spacing[0]; outputSpacing[1] = spacing[1]; outputSpacing[2] = spacing[2]; outputSize[0] = static_cast<SizeValueType>(inputSize.GetSize()[0] * inputSpacing[0] / outputSpacing[0] + .5); outputSize[1] = static_cast<SizeValueType>(inputSize.GetSize()[1] * inputSpacing[1] / outputSpacing[1] + .5); outputSize[2] = static_cast<SizeValueType>(inputSize.GetSize()[2] * inputSpacing[2] / outputSpacing[2] + .5); _pResizeFilter->SetOutputSpacing(outputSpacing); _pResizeFilter->SetSize(outputSize); typedef itk::NearestNeighborInterpolateImageFunction< BinaryImageType> NearestNeighborInterpolateImageType; NearestNeighborInterpolateImageType::Pointer nn_interpolator = NearestNeighborInterpolateImageType::New(); _pResizeFilter->SetInterpolator(nn_interpolator); _pResizeFilter->Update(); mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk(_pResizeFilter->GetOutput()); mitk::GrabItkImageMemory( _pResizeFilter->GetOutput(), image); return image; }
double Mesh::computeStandardDeviationFromPixelsInside(ImageType::Pointer image) { MeshTypeB::Pointer mesh = MeshTypeB::New(); typedef itk::Point< double, 3 > PointType; PointType pnt; ImageType::IndexType index; CVector3 p, n, min(10000,10000,10000), max; for (unsigned int i=0; i<points_.size(); i++) { p = points_[i]->getPosition(); pnt[0] = p[0]; pnt[1] = p[1]; pnt[2] = p[2]; mesh->SetPoint(i,pnt); image->TransformPhysicalPointToIndex(pnt, index); if (index[0]<min[0]) min[0]=index[0]; if (index[1]<min[1]) min[1]=index[1]; if (index[2]<min[2]) min[2]=index[2]; if (index[0]>max[0]) max[0]=index[0]; if (index[1]>max[1]) max[1]=index[1]; if (index[2]>max[2]) max[2]=index[2]; } for (unsigned int i=0; i<triangles_.size(); i+=3) { CellTypeB::CellAutoPointer triangle; triangle.TakeOwnership(new CellTypeB); triangle->SetPointId(0,triangles_[i]); triangle->SetPointId(1,triangles_[i+1]); triangle->SetPointId(2,triangles_[i+2]); mesh->SetCell((int)(i+1)/3,triangle); } CastFilterType::Pointer castFilter = CastFilterType::New(); castFilter->SetInput(image); BinaryImageType::Pointer im = castFilter->GetOutput(); BinaryImageType::IndexType indexRegion; BinaryImageType::SizeType sizeRegion; sizeRegion[0] = max[0]-min[0]+5; // adding two pixels at each side to be sure sizeRegion[1] = max[1]-min[1]+5; sizeRegion[2] = max[2]-min[2]+5; indexRegion[0] = min[0]-2; indexRegion[1] = min[1]-2; indexRegion[2] = min[2]-2; BinaryImageType::RegionType region(indexRegion,sizeRegion); im->SetRegions(region); MeshFilterType::Pointer meshFilter = MeshFilterType::New(); meshFilter->SetInput(mesh); meshFilter->SetInfoImage(im); /*meshFilter->SetDirection(image->GetDirection()); meshFilter->SetSpacing(image->GetSpacing()); meshFilter->SetOrigin(image->GetOrigin()); meshFilter->SetSize(sizeRegion); meshFilter->SetIndex(indexRegion);*/ meshFilter->SetTolerance(1.0); meshFilter->SetInsideValue(1.0); meshFilter->SetOutsideValue(0.0); try { meshFilter->Update(); } catch( itk::ExceptionObject & e ) { cout << "Exception thrown ! " << endl; cout << "An error ocurred during creating binary image" << endl; cout << "Location = " << e.GetLocation() << endl; cout << "Description = " << e.GetDescription() << endl; } MeshFilterType::OutputImageType::Pointer binary = meshFilter->GetOutput(); vector<double> valueVoxels; typedef ImageType::IndexType IndexType; IndexType ind; ImageIterator it( binary, binary->GetRequestedRegion() ); it.GoToBegin(); while(!it.IsAtEnd()) { if (it.Get()==true) { ind = it.GetIndex(); valueVoxels.push_back(image->GetPixel(ind)); } ++it; } double mean = 0.0, sum = 0.0, std = 0.0, nbVoxels = valueVoxels.size(); for (int i=0; i<nbVoxels; i++) mean += valueVoxels[i]; mean /= nbVoxels; for (int i=0; i<nbVoxels; i++) { sum += valueVoxels[i]*valueVoxels[i]; } std = sqrt(sum/nbVoxels-mean*mean); /*ofstream myfile; myfile.open("StandardDeviation.txt", ios_base::app); myfile << ind[1] << " " << mean << " " << std << endl; myfile.close();*/ return mean; }
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 mitk::SurfaceStampImageFilter::SurfaceStampProcessing(itk::Image<TPixel, 3> *input, MeshType *mesh) { typedef itk::Image<TPixel, 3> ImageType; typedef itk::Image<unsigned char, 3> BinaryImageType; typedef itk::TriangleMeshToBinaryImageFilter<mitk::SurfaceStampImageFilter::MeshType, BinaryImageType> FilterType; BinaryImageType::Pointer binaryInput = BinaryImageType::New(); binaryInput->SetSpacing(input->GetSpacing()); binaryInput->SetOrigin(input->GetOrigin()); binaryInput->SetDirection(input->GetDirection()); binaryInput->SetRegions(input->GetLargestPossibleRegion()); binaryInput->Allocate(); binaryInput->FillBuffer(0); FilterType::Pointer filter = FilterType::New(); filter->SetInput(mesh); filter->SetInfoImage(binaryInput); filter->SetInsideValue(1); filter->SetOutsideValue(0); filter->Update(); BinaryImageType::Pointer resultImage = filter->GetOutput(); resultImage->DisconnectPipeline(); mitk::Image::Pointer outputImage = this->GetOutput(); typename ImageType::Pointer itkOutputImage; mitk::CastToItkImage(outputImage, itkOutputImage); typedef itk::ImageRegionConstIterator<BinaryImageType> BinaryIteratorType; typedef itk::ImageRegionConstIterator<ImageType> InputIteratorType; typedef itk::ImageRegionIterator<ImageType> OutputIteratorType; BinaryIteratorType sourceIter(resultImage, resultImage->GetLargestPossibleRegion()); sourceIter.GoToBegin(); InputIteratorType inputIter(input, input->GetLargestPossibleRegion()); inputIter.GoToBegin(); OutputIteratorType outputIter(itkOutputImage, itkOutputImage->GetLargestPossibleRegion()); outputIter.GoToBegin(); typename ImageType::PixelType inputValue; unsigned char sourceValue; auto fgValue = static_cast<typename ImageType::PixelType>(m_ForegroundValue); auto bgValue = static_cast<typename ImageType::PixelType>(m_BackgroundValue); while (!sourceIter.IsAtEnd()) { sourceValue = static_cast<unsigned char>(sourceIter.Get()); inputValue = static_cast<typename ImageType::PixelType>(inputIter.Get()); if (sourceValue != 0) outputIter.Set(fgValue); else if (m_OverwriteBackground) outputIter.Set(bgValue); else outputIter.Set(inputValue); ++sourceIter; ++inputIter; ++outputIter; } }