int main(int argc, char* argv[]) { CSimpleOpt::SOption specs[] = { { 0, "-o", SO_REQ_SEP }, SO_END_OF_OPTIONS }; Options argParser; StringVector args = argParser.ParseOptions(argc, argv, specs); if (args.size() < 1) { cout << argv[0] << " [input-vector] [output-rgb]" << endl; return 1; } ImageIO<DeformFieldImageType> io; DeformFieldImageType::Pointer img = io.ReadImage(args[0]); // itk::UnaryFunctorImageFilter<DeformFieldImageType,RGBImageType> CastFilter; typedef itk::UnaryFunctorImageFilter<DeformFieldImageType, RGBImageType, Vector2RGB> CastFilter; CastFilter::Pointer caster = CastFilter::New(); caster->SetInput(img); caster->Update(); RGBImageType::Pointer rgbImg = caster->GetOutput(); rgbImg->Print(cout); io.WriteImageS<RGBImageType>(args[1], rgbImg); return 0; }
void SuperPixelSegmentationGUI::slot_IterationComplete(unsigned int numberOfSegments) { std::stringstream ss; ss << "Computed " << numberOfSegments << " segments." << std::endl; this->statusBar()->showMessage(ss.str().c_str()); typedef itk::Image<itk::RGBPixel<unsigned char>, 2> RGBImageType; RGBImageType::Pointer colorImage = RGBImageType::New(); colorImage->SetRegions(this->LabelImage->GetLargestPossibleRegion()); colorImage->Allocate(); unsigned int maxLabel = Helpers::MaxValue<LabelImageType>(this->LabelImage); std::vector<RGBImageType::PixelType> segmentColors; for(unsigned int labelId = 0; labelId <= maxLabel; ++labelId) { //std::cout << "Coloring label " << labelId << std::endl; float rgb[3] = {0,0,0}; itk::ImageRegionIterator<LabelImageType> labelIterator(this->LabelImage, this->LabelImage->GetLargestPossibleRegion()); unsigned int counter = 0; while(!labelIterator.IsAtEnd()) { if(labelIterator.Get() == labelId) { rgb[0] += this->Image->GetPixel(labelIterator.GetIndex())[0]; rgb[1] += this->Image->GetPixel(labelIterator.GetIndex())[1]; rgb[2] += this->Image->GetPixel(labelIterator.GetIndex())[2]; counter++; }// end if ++labelIterator; } // end while RGBImageType::PixelType colorPixel; colorPixel[0] = rgb[0]/static_cast<float>(counter); colorPixel[1] = rgb[1]/static_cast<float>(counter); colorPixel[2] = rgb[2]/static_cast<float>(counter); segmentColors.push_back(colorPixel); } // end for itk::ImageRegionIterator<LabelImageType> colorIterator(this->LabelImage, this->LabelImage->GetLargestPossibleRegion()); while(!colorIterator.IsAtEnd()) { colorImage->SetPixel(colorIterator.GetIndex(), segmentColors[colorIterator.Get()]); ++colorIterator; } // end while QImage qimage = HelpersQt::GetQImageRGB<RGBImageType>(colorImage); if(this->LabelImagePixmapItem) { this->Scene->removeItem(this->LabelImagePixmapItem); } this->LabelImagePixmapItem = this->Scene->addPixmap(QPixmap::fromImage(qimage)); Refresh(); }
bool TestCreateLuminanceImage() { // From RGB image { itk::Index<2> imageCorner = {{0,0}}; itk::Size<2> imageSize = {{100,100}}; itk::ImageRegion<2> imageRegion(imageCorner, imageSize); typedef itk::Image<itk::RGBPixel<unsigned char>, 2> RGBImageType; RGBImageType::Pointer rgbImage = RGBImageType::New(); rgbImage->SetRegions(imageRegion); rgbImage->Allocate(); typedef itk::Image<float, 2> LuminanceImageType; LuminanceImageType::Pointer luminanceImage = LuminanceImageType::New(); ITKHelpers::CreateLuminanceImage(rgbImage.GetPointer(), luminanceImage.GetPointer()); } // From Vector image { itk::Index<2> imageCorner = {{0,0}}; itk::Size<2> imageSize = {{100,100}}; itk::ImageRegion<2> imageRegion(imageCorner, imageSize); typedef itk::Image<itk::CovariantVector<unsigned char, 3>, 2> VectorImageType; VectorImageType::Pointer vectorImage = VectorImageType::New(); vectorImage->SetRegions(imageRegion); vectorImage->Allocate(); typedef itk::Image<float, 2> LuminanceImageType; LuminanceImageType::Pointer luminanceImage = LuminanceImageType::New(); ITKHelpers::CreateLuminanceImage(vectorImage.GetPointer(), luminanceImage.GetPointer()); } return true; }
void LidarSegmentationWidget::on_action_Selections_SaveAsImage_triggered() { QString filename = QFileDialog::getSaveFileName(this, "Save Image", ".", "PNG Files (*.png)"); if(filename.isEmpty()) { return; } RGBImageType::Pointer selectionsImage = RGBImageType::New(); selectionsImage->SetRegions(this->ImageRegion); selectionsImage->Allocate(); RGBPixelType whitePixel; whitePixel.SetRed(255); whitePixel.SetGreen(255); whitePixel.SetBlue(255); selectionsImage->FillBuffer(whitePixel); RGBPixelType greenPixel; greenPixel.SetRed(0); greenPixel.SetGreen(255); greenPixel.SetBlue(0); ITKHelpers::SetPixels(selectionsImage.GetPointer(), this->Sources, greenPixel); RGBPixelType redPixel; redPixel.SetRed(255); redPixel.SetGreen(0); redPixel.SetBlue(0); ITKHelpers::SetPixels(selectionsImage.GetPointer(), this->Sinks, redPixel); typedef itk::ImageFileWriter< RGBImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName(filename.toStdString()); writer->SetInput(selectionsImage); writer->Update(); }
void LidarSegmentationWidget::on_action_Selections_SaveBackgroundAsImage_triggered() { QString filename = QFileDialog::getSaveFileName(this, "Save Image", "background.png", "PNG Files (*.png)"); if(filename.isEmpty()) { return; } RGBImageType::Pointer selectionsImage = RGBImageType::New(); selectionsImage->SetRegions(this->ImageRegion); selectionsImage->Allocate(); RGBPixelType blackPixel; blackPixel.SetRed(0); blackPixel.SetGreen(0); blackPixel.SetBlue(0); RGBPixelType whitePixel; whitePixel.SetRed(255); whitePixel.SetGreen(255); whitePixel.SetBlue(255); ITKHelpers::SetPixelsInRegionToValue(selectionsImage.GetPointer(), selectionsImage->GetLargestPossibleRegion(), blackPixel); ITKHelpers::SetPixels(selectionsImage.GetPointer(), this->Sinks, whitePixel); typedef itk::ImageFileWriter< RGBImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName(filename.toStdString()); writer->SetInput(selectionsImage); writer->Update(); }
void LidarInpaintingHSVTextureVerification(TImage* const originalImage, Mask* const mask, const unsigned int patchHalfWidth, const unsigned int numberOfKNN, float slightBlurVariance = 1.0f, unsigned int searchRadius = 1000, float localRegionSizeMultiplier = 3.0f, float maxAllowedUsedPixelsRatio = 0.5f) { itk::ImageRegion<2> fullRegion = originalImage->GetLargestPossibleRegion(); // Extract the RGB image typedef itk::Image<itk::CovariantVector<float, 3>, 2> RGBImageType; std::vector<unsigned int> firstThreeChannels = {0,1,2}; RGBImageType::Pointer rgbImage = RGBImageType::New(); ITKHelpers::ExtractChannels(originalImage, firstThreeChannels, rgbImage.GetPointer()); // Create the HSV image typedef itk::Image<itk::CovariantVector<float, 3>, 2> HSVImageType; HSVImageType::Pointer hsvImage = HSVImageType::New(); ITKVTKHelpers::ConvertRGBtoHSV(rgbImage.GetPointer(), hsvImage.GetPointer()); ITKHelpers::WriteImage(hsvImage.GetPointer(), "HSVImage.mha"); // Stack the HSV image with the original rest of the channels typedef itk::Image<itk::CovariantVector<float, 5>, 2> HSVDxDyImageType; HSVDxDyImageType::Pointer hsvDxDyImage = HSVDxDyImageType::New(); ITKHelpers::DeepCopy(originalImage, hsvDxDyImage.GetPointer()); ITKHelpers::ReplaceChannels(hsvDxDyImage.GetPointer(), firstThreeChannels, hsvImage.GetPointer()); // Blur the image for gradient computation stability (Criminisi's data term) RGBImageType::Pointer blurredRGBImage = RGBImageType::New(); float blurVariance = 2.0f; MaskOperations::MaskedBlur(rgbImage.GetPointer(), mask, blurVariance, blurredRGBImage.GetPointer()); ITKHelpers::WriteRGBImage(blurredRGBImage.GetPointer(), "BlurredRGBImage.png"); // Blur the image slightly so that the SSD comparisons are not so noisy typename HSVDxDyImageType::Pointer slightlyBlurredHSVDxDyImage = TImage::New(); MaskOperations::MaskedBlur(hsvDxDyImage.GetPointer(), mask, slightBlurVariance, slightlyBlurredHSVDxDyImage.GetPointer()); ITKHelpers::WriteImage(slightlyBlurredHSVDxDyImage.GetPointer(), "SlightlyBlurredHSVDxDyImage.mha"); // Create the graph typedef ImagePatchPixelDescriptor<TImage> ImagePatchPixelDescriptorType; typedef boost::grid_graph<2> VertexListGraphType; // We can't make this a signed type (size_t versus int) because we allow negative boost::array<std::size_t, 2> graphSideLengths = { { fullRegion.GetSize()[0], fullRegion.GetSize()[1] } }; VertexListGraphType graph(graphSideLengths); typedef boost::graph_traits<VertexListGraphType>::vertex_descriptor VertexDescriptorType; typedef boost::graph_traits<VertexListGraphType>::vertex_iterator VertexIteratorType; // Get the index map typedef boost::property_map<VertexListGraphType, boost::vertex_index_t>::const_type IndexMapType; IndexMapType indexMap(get(boost::vertex_index, graph)); // Create the descriptor map. This is where the data for each pixel is stored. typedef boost::vector_property_map<ImagePatchPixelDescriptorType, IndexMapType> ImagePatchDescriptorMapType; ImagePatchDescriptorMapType imagePatchDescriptorMap(num_vertices(graph), indexMap); // Create the patch inpainter. typedef PatchInpainter<TImage> OriginalImageInpainterType; OriginalImageInpainterType originalImagePatchInpainter(patchHalfWidth, originalImage, mask); originalImagePatchInpainter.SetDebugImages(true); originalImagePatchInpainter.SetImageName("RGB"); // Create an inpainter for the HSV image. typedef PatchInpainter<HSVImageType> HSVImageInpainterType; HSVImageInpainterType hsvImagePatchInpainter(patchHalfWidth, hsvImage, mask); // Create an inpainter for the RGB image. typedef PatchInpainter<RGBImageType> RGBImageInpainterType; RGBImageInpainterType rgbImagePatchInpainter(patchHalfWidth, rgbImage, mask); // Create an inpainter for the blurred image. typedef PatchInpainter<RGBImageType> BlurredImageInpainterType; BlurredImageInpainterType blurredRGBImagePatchInpainter(patchHalfWidth, blurredRGBImage, mask); // Create an inpainter for the slightly blurred image. typedef PatchInpainter<TImage> SlightlyBlurredHSVDxDyImageImageInpainterType; SlightlyBlurredHSVDxDyImageImageInpainterType slightlyBlurredHSVDxDyImageImagePatchInpainter(patchHalfWidth, slightlyBlurredHSVDxDyImage, mask); // Create a composite inpainter. (Note: the mask is inpainted in InpaintingVisitor::FinishVertex) CompositePatchInpainter inpainter; inpainter.AddInpainter(&originalImagePatchInpainter); inpainter.AddInpainter(&hsvImagePatchInpainter); inpainter.AddInpainter(&blurredRGBImagePatchInpainter); inpainter.AddInpainter(&slightlyBlurredHSVDxDyImageImagePatchInpainter); inpainter.AddInpainter(&rgbImagePatchInpainter); // Create the priority function typedef PriorityCriminisi<RGBImageType> PriorityType; PriorityType priorityFunction(blurredRGBImage, mask, patchHalfWidth); // priorityFunction.SetDebugLevel(1); // Queue typedef IndirectPriorityQueue<VertexListGraphType> BoundaryNodeQueueType; BoundaryNodeQueueType boundaryNodeQueue(graph); // Create the descriptor visitor (used for SSD comparisons). typedef ImagePatchDescriptorVisitor<VertexListGraphType, TImage, ImagePatchDescriptorMapType> ImagePatchDescriptorVisitorType; // ImagePatchDescriptorVisitorType imagePatchDescriptorVisitor(originalImage, mask, // imagePatchDescriptorMap, patchHalfWidth); // Use the non-blurred image for the SSD comparisons ImagePatchDescriptorVisitorType imagePatchDescriptorVisitor(slightlyBlurredHSVDxDyImage, mask, imagePatchDescriptorMap, patchHalfWidth); // Use the slightly blurred HSV image for the SSD comparisons. Make sure to use a *HSVSSD difference functor so the H differences are treated appropriately! typedef DefaultAcceptanceVisitor<VertexListGraphType> AcceptanceVisitorType; AcceptanceVisitorType acceptanceVisitor; // Create the inpainting visitor. (The mask is inpainted in FinishVertex) typedef InpaintingVisitor<VertexListGraphType, BoundaryNodeQueueType, ImagePatchDescriptorVisitorType, AcceptanceVisitorType, PriorityType, TImage> InpaintingVisitorType; InpaintingVisitorType inpaintingVisitor(mask, boundaryNodeQueue, imagePatchDescriptorVisitor, acceptanceVisitor, &priorityFunction, patchHalfWidth, "InpaintingVisitor", originalImage); inpaintingVisitor.SetDebugImages(true); // This produces PatchesCopied* images showing where patches were copied from/to at each iteration // inpaintingVisitor.SetAllowNewPatches(false); inpaintingVisitor.SetAllowNewPatches(true); // we can do this as long as we use one of the LinearSearchKNNProperty*Reuse (like LinearSearchKNNPropertyLimitLocalReuse) in the steps below InitializePriority(mask, boundaryNodeQueue, &priorityFunction); // Initialize the boundary node queue from the user provided mask image. InitializeFromMaskImage<InpaintingVisitorType, VertexDescriptorType>(mask, &inpaintingVisitor); std::cout << "PatchBasedInpaintingNonInteractive: There are " << boundaryNodeQueue.CountValidNodes() << " nodes in the boundaryNodeQueue" << std::endl; #define DUseWeightedDifference #ifdef DUseWeightedDifference // The absolute value of the depth derivative range is usually about [0,12], so to make // it comparable to to the color image channel range of [0,255], we multiply by 255/12 ~= 20. // float depthDerivativeWeight = 20.0f; // This should not be computed "by eye" by looking at the Dx and Dy channels of the PTX scan, because there are typically // huge depth discontinuties around the objects that are going to be inpainted. We'd have to look at the masked version of this // image to determine the min/max values of the unmasked pixels. They will be much smaller than the min/max values of the original // image, which will make the depth derivative weights much higher (~100 or so) // std::vector<typename TImage::PixelType> channelMins = ITKHelpers::ComputeMinOfAllChannels(originalImage); // std::vector<typename TImage::PixelType> channelMaxs = ITKHelpers::ComputeMaxOfAllChannels(originalImage); typename TImage::PixelType channelMins; ITKHelpers::ComputeMinOfAllChannels(originalImage, channelMins); typename TImage::PixelType channelMaxs; ITKHelpers::ComputeMaxOfAllChannels(originalImage, channelMaxs); float minX = fabs(channelMins[3]); float maxX = fabs(channelMaxs[3]); float maxValueX = std::max(minX, maxX); std::cout << "maxValueX = " << maxValueX << std::endl; float depthDerivativeWeightX = 255.0f / maxValueX; std::cout << "Computed depthDerivativeWeightX = " << depthDerivativeWeightX << std::endl; float minY = fabs(channelMins[4]); float maxY = fabs(channelMaxs[4]); float maxValueY = std::max(minY, maxY); std::cout << "maxValueY = " << maxValueY << std::endl; float depthDerivativeWeightY = 255.0f / maxValueY; std::cout << "Computed depthDerivativeWeightY = " << depthDerivativeWeightY << std::endl; // Use all channels std::vector<float> weights = {1.0f, 1.0f, 1.0f, depthDerivativeWeightX, depthDerivativeWeightY}; // typedef WeightedSumSquaredPixelDifference<typename TImage::PixelType> PixelDifferenceType; typedef WeightedHSVSSDFull<typename TImage::PixelType> FullPixelDifferenceType; FullPixelDifferenceType fullPixelDifferenceFunctor(weights); typedef ImagePatchDifference<ImagePatchPixelDescriptorType, FullPixelDifferenceType > FullPatchDifferenceType; FullPatchDifferenceType fullPatchDifferenceFunctor(fullPixelDifferenceFunctor); // Use only the first 3 channels typedef HSVSSD<typename TImage::PixelType> First3PixelDifferenceType; First3PixelDifferenceType first3PixelDifferenceFunctor; typedef ImagePatchDifference<ImagePatchPixelDescriptorType, First3PixelDifferenceType > First3PatchDifferenceType; First3PatchDifferenceType first3PatchDifferenceFunctor(first3PixelDifferenceFunctor); #else // Use an unweighted pixel difference typedef ImagePatchDifference<ImagePatchPixelDescriptorType, SumSquaredPixelDifference<typename TImage::PixelType> > PatchDifferenceType; PatchDifferenceType patchDifferenceFunctor; #endif //#define DAllowReuse // comment/uncomment this line to toggle allowing patches to be used as the source patch more than once #ifdef DAllowReuse // Create the first (KNN) neighbor finder typedef LinearSearchKNNProperty<ImagePatchDescriptorMapType, PatchDifferenceType> KNNSearchType; KNNSearchType linearSearchKNN(imagePatchDescriptorMap, numberOfKNN, patchDifferenceFunctor); #else typedef LinearSearchKNNPropertyLimitLocalReuse<ImagePatchDescriptorMapType, FullPatchDifferenceType, RGBImageType> KNNSearchType; KNNSearchType linearSearchKNN(imagePatchDescriptorMap, mask, numberOfKNN, localRegionSizeMultiplier, maxAllowedUsedPixelsRatio, fullPatchDifferenceFunctor, inpaintingVisitor.GetSourcePixelMapImage(), rgbImage.GetPointer()); linearSearchKNN.SetDebugImages(true); linearSearchKNN.SetDebugScreenOutputs(true); #endif //#else // This works the best, but is less useful for demonstrations // typedef LinearSearchKNNPropertyLimitLocalReuse<ImagePatchDescriptorMapType, FullPatchDifferenceType, RGBImageType> FullPixelKNNSearchType; // FullPixelKNNSearchType fullPixelSearchKNN(imagePatchDescriptorMap, mask, numberOfKNN, localRegionSizeMultiplier, maxAllowedUsedPixelsRatio, // fullPatchDifferenceFunctor, inpaintingVisitor.GetSourcePixelMapImage(), // rgbImage.GetPointer()); // fullPixelSearchKNN.SetDebugImages(true); // fullPixelSearchKNN.SetDebugScreenOutputs(true); // typedef LinearSearchKNNPropertyLimitLocalReuse<ImagePatchDescriptorMapType, First3PatchDifferenceType, RGBImageType> First3PixelKNNSearchType; // First3PixelKNNSearchType first3SearchKNN(imagePatchDescriptorMap, mask, numberOfKNN, localRegionSizeMultiplier, maxAllowedUsedPixelsRatio, // first3PatchDifferenceFunctor, inpaintingVisitor.GetSourcePixelMapImage(), // rgbImage.GetPointer()); // first3SearchKNN.SetDebugScreenOutputs(true); //// typedef LinearSearchKNNProperty<ImagePatchDescriptorMapType, First3PatchDifferenceType> First3PixelKNNSearchType; //// First3PixelKNNSearchType first3SearchKNN(imagePatchDescriptorMap, numberOfKNN, //// first3PatchDifferenceFunctor); //// first3SearchKNN.SetDebugImages(true); // typedef LinearSearchKNNPropertyCombine<FullPixelKNNSearchType, First3PixelKNNSearchType> KNNSearchType; // KNNSearchType linearSearchKNN(fullPixelSearchKNN, first3SearchKNN); //#endif // Setup the second (1-NN) neighbor finder typedef std::vector<VertexDescriptorType>::iterator VertexDescriptorVectorIteratorType; // This is templated on TImage because we need it to write out debug patches from this searcher (since we are not using an RGB image to compute the histograms) // typedef LinearSearchBestTexture<ImagePatchDescriptorMapType, HSVImageType, // VertexDescriptorVectorIteratorType, TImage> BestSearchType; // Use the histogram of the gradient magnitudes of a scalar represetnation of the image (e.g. magnitude image) // typedef LinearSearchBestLidarTextureDerivatives<ImagePatchDescriptorMapType, HSVImageType, // VertexDescriptorVectorIteratorType, TImage> BestSearchType; // Use the concatenated histograms of the absolute value of the derivatives of each channel // typedef LinearSearchBestLidarHSVTextureGradient<ImagePatchDescriptorMapType, HSVDxDyImageType, // VertexDescriptorVectorIteratorType, RGBImageType> BestSearchType; // Use the concatenated histograms of the gradient magnitudes of each channel. This HSVDxDyImageType must match the hsvDxDyImage provided below typedef LinearSearchBestLidarHSVTextureGradientWithSort<ImagePatchDescriptorMapType, HSVDxDyImageType, VertexDescriptorVectorIteratorType, RGBImageType> BestSearchType; // Use the concatenated histograms of the gradient magnitudes of each channel. This HSVDxDyImageType must match the hsvDxDyImage provided below. Also sort the patches for demonstrative output purposes. // BestSearchType linearSearchBest(imagePatchDescriptorMap, hsvDxDyImage.GetPointer(), mask); // use non-blurred for texture sorting Debug bestSearchTypeDebug; bestSearchTypeDebug.SetDebugScreenOutputs(true); // bestSearchTypeDebug.SetDebugImages(true); // linearSearchBest.SetDebugOutputs(true); // linearSearchBest.SetDebugImages(true); // use slightly blurred for texture sorting BestSearchType linearSearchBest(imagePatchDescriptorMap, slightlyBlurredHSVDxDyImage.GetPointer(), mask, rgbImage.GetPointer(), bestSearchTypeDebug); // linearSearchBest.SetDebugImages(false); linearSearchBest.SetDebugImages(true); // This produces BestPatch* images showing the list of the top K patches that were passed to the BestSearch functor // Setup the two step neighbor finder TwoStepNearestNeighbor<KNNSearchType, BestSearchType> twoStepNearestNeighbor(linearSearchKNN, linearSearchBest); // #define DFullSearch // comment/uncomment this line to set the search region #ifdef DFullSearch // Perform the inpainting (full search) InpaintingAlgorithm(graph, inpaintingVisitor, &boundaryNodeQueue, twoStepNearestNeighbor, &inpainter); #else NeighborhoodSearch<VertexDescriptorType, ImagePatchDescriptorMapType> neighborhoodSearch(originalImage->GetLargestPossibleRegion(), searchRadius, imagePatchDescriptorMap); // Perform the inpainting (local search) bool algorithmDebug = true; InpaintingAlgorithmWithLocalSearch(graph, inpaintingVisitor, &boundaryNodeQueue, twoStepNearestNeighbor, &inpainter, neighborhoodSearch, algorithmDebug); #endif }
int main(int argc, char *argv[]) { if(argc != 3) { std::cerr << "Required arguments: image mask" << std::endl; return EXIT_FAILURE; } std::string imageFilename = argv[1]; std::string maskFilename = argv[2]; std::cout << "Reading image: " << imageFilename << std::endl; std::cout << "Reading mask: " << maskFilename << std::endl; typedef itk::ImageFileReader<FloatVectorImageType> ImageReaderType; ImageReaderType::Pointer imageReader = ImageReaderType::New(); imageReader->SetFileName(imageFilename.c_str()); imageReader->Update(); std::cout << "Read image " << imageReader->GetOutput()->GetLargestPossibleRegion() << std::endl; typedef itk::ImageFileReader<Mask> MaskReaderType; MaskReaderType::Pointer maskReader = MaskReaderType::New(); maskReader->SetFileName(maskFilename.c_str()); maskReader->Update(); std::cout << "Read mask " << maskReader->GetOutput()->GetLargestPossibleRegion() << std::endl; // Prepare image RGBImageType::Pointer rgbImage = RGBImageType::New(); // TODO: update this to the new API //Helpers::VectorImageToRGBImage(imageReader->GetOutput(), rgbImage); OutputHelpers::WriteImage(rgbImage.GetPointer(), "Test/TestIsophotes.rgb.mha"); typedef itk::RGBToLuminanceImageFilter< RGBImageType, FloatScalarImageType > LuminanceFilterType; LuminanceFilterType::Pointer luminanceFilter = LuminanceFilterType::New(); luminanceFilter->SetInput(rgbImage); luminanceFilter->Update(); FloatScalarImageType::Pointer blurredLuminance = FloatScalarImageType::New(); // Blur with a Gaussian kernel unsigned int kernelRadius = 5; MaskOperations::MaskedBlur<FloatScalarImageType>(luminanceFilter->GetOutput(), maskReader->GetOutput(), kernelRadius, blurredLuminance); OutputHelpers::WriteImage<FloatScalarImageType>(blurredLuminance, "Test/TestIsophotes.blurred.mha"); //inpainting.ComputeMaskedIsophotes(blurredLuminance, maskReader->GetOutput()); //Helpers::WriteImage<FloatVector2ImageType>(inpainting.GetIsophoteImage(), ); //HelpersOutput::Write2DVectorImage(inpainting.GetIsophoteImage(), "Test/TestIsophotes.isophotes.mha"); itk::Size<2> size; size.Fill(21); // Target itk::Index<2> targetIndex; targetIndex[0] = 187; targetIndex[1] = 118; itk::ImageRegion<2> targetRegion(targetIndex, size); // Source itk::Index<2> sourceIndex; sourceIndex[0] = 176; sourceIndex[1] = 118; itk::ImageRegion<2> sourceRegion(sourceIndex, size); //PatchPair patchPair(Patch(sourceRegion), Patch(targetRegion)); //PatchPair patchPair; // Patch sourcePatch(sourceRegion); // Patch targetPatch(targetRegion); // PatchPair patchPair(sourcePatch, targetPatch); //inpainting.FindBoundary(); // std::vector<itk::Index<2> > borderPixels = // ITKHelpers::GetNonZeroPixels(inpainting.GetBoundaryImage(), targetRegion); itk::RGBPixel<unsigned char> black; black.SetRed(0); black.SetGreen(0); black.SetBlue(0); itk::RGBPixel<unsigned char> red; red.SetRed(255); red.SetGreen(0); red.SetBlue(0); itk::RGBPixel<unsigned char> darkRed; darkRed.SetRed(100); darkRed.SetGreen(0); darkRed.SetBlue(0); itk::RGBPixel<unsigned char> yellow; yellow.SetRed(255); yellow.SetGreen(255); yellow.SetBlue(0); itk::RGBPixel<unsigned char> green; green.SetRed(0); green.SetGreen(255); green.SetBlue(0); itk::RGBPixel<unsigned char> darkGreen; darkGreen.SetRed(0); darkGreen.SetGreen(100); darkGreen.SetBlue(0); itk::RGBPixel<unsigned char> blue; blue.SetRed(0); blue.SetGreen(0); blue.SetBlue(255); RGBImageType::Pointer output = RGBImageType::New(); output->SetRegions(imageReader->GetOutput()->GetLargestPossibleRegion()); output->Allocate(); output->FillBuffer(black); ITKHelpers::BlankAndOutlineRegion(output.GetPointer(), targetRegion, black, red); ITKHelpers::BlankAndOutlineRegion(output.GetPointer(), sourceRegion, black, green); RGBImageType::Pointer target = RGBImageType::New(); target->SetRegions(imageReader->GetOutput()->GetLargestPossibleRegion()); target->Allocate(); ITKHelpers::BlankAndOutlineRegion(target.GetPointer(), targetRegion, black, red); RGBImageType::Pointer source = RGBImageType::New(); source->SetRegions(imageReader->GetOutput()->GetLargestPossibleRegion()); source->Allocate(); ITKHelpers::BlankAndOutlineRegion(source.GetPointer(), sourceRegion, black, green); // itk::Offset<2> offset = targetIndex - sourceIndex; /* for(unsigned int pixelId = 0; pixelId < borderPixels.size(); ++pixelId) { itk::Index<2> targetPatchSourceSideBoundaryPixel = borderPixels[pixelId]; itk::Index<2> sourcePatchTargetSideBoundaryPixel; //bool valid = GetAdjacentBoundaryPixel(currentPixel, candidatePairs[sourcePatchId], adjacentBoundaryPixel); bool valid = inpainting.GetAdjacentBoundaryPixel(targetPatchSourceSideBoundaryPixel, patchPair, sourcePatchTargetSideBoundaryPixel); target->SetPixel(targetPatchSourceSideBoundaryPixel, darkRed); source->SetPixel(sourcePatchTargetSideBoundaryPixel, darkGreen); if(!valid) { continue; } // Bring the adjacent pixel back to the target region. itk::Index<2> targetPatchTargetSideBoundaryPixel = sourcePatchTargetSideBoundaryPixel + offset; output->SetPixel(targetPatchSourceSideBoundaryPixel, darkRed); output->SetPixel(targetPatchTargetSideBoundaryPixel, blue); output->SetPixel(sourcePatchTargetSideBoundaryPixel, darkGreen); } */ // OutputHelpers::WriteImage(output.GetPointer(), "Test/FollowIsophotes.Output.mha"); // OutputHelpers::WriteImage(target.GetPointer(), "Test/FollowIsophotes.Target.mha"); // OutputHelpers::WriteImage(source.GetPointer(), "Test/FollowIsophotes.Source.mha"); return EXIT_SUCCESS; }
void Initialisation::savePointAsAxialImage(ImageType::Pointer initialImage, string filename) { if (points_.size() > 0) { double radius = 2.0; //if (initialRadius_/stretchingFactor_ > radius_) radius = radius_*stretchingFactor_; // initialRadius_ majored by radius_ //else radius = initialRadius_; typedef itk::ImageDuplicator< ImageType > DuplicatorType3D; DuplicatorType3D::Pointer duplicator = DuplicatorType3D::New(); duplicator->SetInputImage(initialImage); duplicator->Update(); ImageType::Pointer clonedImage = duplicator->GetOutput(); // Intensity normalization RescaleFilterType::Pointer rescaleFilter = RescaleFilterType::New(); rescaleFilter->SetInput(clonedImage); rescaleFilter->SetOutputMinimum(0); rescaleFilter->SetOutputMaximum(255); try { rescaleFilter->Update(); } catch( itk::ExceptionObject & e ) { cerr << "Exception caught while normalizing input image " << endl; cerr << e << endl; } clonedImage = rescaleFilter->GetOutput(); typedef itk::RGBPixel<unsigned char> RGBPixelType; typedef itk::Image<RGBPixelType, 2> RGBImageType; typedef itk::ExtractImageFilter< ImageType, RGBImageType > ExtractorTypeRGB; PointType pt; pt[0] = initialPoint_[0]; pt[1] = initialPoint_[1]; pt[2] = initialPoint_[2]; ImageType::IndexType ind; clonedImage->TransformPhysicalPointToIndex(pt,ind); ImageType::SizeType desiredSize = clonedImage->GetLargestPossibleRegion().GetSize(); ImageType::IndexType desiredStart; desiredStart[0] = 0; desiredStart[1] = ind[1]; desiredStart[2] = 0; desiredSize[1] = 0; ImageType::RegionType desiredRegion(desiredStart, desiredSize); ExtractorTypeRGB::Pointer filter = ExtractorTypeRGB::New(); filter->SetExtractionRegion(desiredRegion); filter->SetInput(clonedImage); #if ITK_VERSION_MAJOR >= 4 filter->SetDirectionCollapseToIdentity(); // This is required. #endif try { filter->Update(); } catch( itk::ExceptionObject & e ) { std::cerr << "Exception caught while updating ExtractorTypeRGB " << std::endl; std::cerr << e << std::endl; } RGBImageType::Pointer image = filter->GetOutput(); // draw cross RGBPixelType pixel; pixel[0] = 255; pixel[1] = 255; pixel[2] = 255; for (int x=-radius; x<=radius; x++) { RGBImageType::IndexType ind_x, ind_y; ind_x[0] = ind[0]+x; ind_x[1] = ind[2]; ind_y[0] = ind[0]; ind_y[1] = ind[2]+x; image->SetPixel(ind_x, pixel); image->SetPixel(ind_y, pixel); } typedef itk::ImageFileWriter< RGBImageType > WriterRGBType; itk::PNGImageIO::Pointer ioPNG = itk::PNGImageIO::New(); WriterRGBType::Pointer writerPNG = WriterRGBType::New(); writerPNG->SetInput(image); writerPNG->SetImageIO(ioPNG); writerPNG->SetFileName(filename); try { writerPNG->Update(); } catch( itk::ExceptionObject & e ) { cout << "Exception thrown ! " << endl; cout << "An error ocurred during Writing PNG" << endl; cout << "Location = " << e.GetLocation() << endl; cout << "Description = " << e.GetDescription() << endl; } } else cout << "Error: Spinal cord center not detected" << endl; }
int main(int argc, char *argv[]) { if(argc != 3) { std::cerr << "Required arguments: image mask" << std::endl; return EXIT_FAILURE; } std::string imageFilename = argv[1]; std::string maskFilename = argv[2]; std::cout << "Reading image: " << imageFilename << std::endl; std::cout << "Reading mask: " << maskFilename << std::endl; typedef itk::ImageFileReader<FloatVectorImageType> ImageReaderType; ImageReaderType::Pointer imageReader = ImageReaderType::New(); imageReader->SetFileName(imageFilename.c_str()); imageReader->Update(); std::cout << "Read image " << imageReader->GetOutput()->GetLargestPossibleRegion() << std::endl; typedef itk::ImageFileReader<Mask> MaskReaderType; MaskReaderType::Pointer maskReader = MaskReaderType::New(); maskReader->SetFileName(maskFilename.c_str()); maskReader->Update(); std::cout << "Read mask " << maskReader->GetOutput()->GetLargestPossibleRegion() << std::endl; // Prepare image RGBImageType::Pointer rgbImage = RGBImageType::New(); // Helpers::VectorImageToRGBImage(imageReader->GetOutput(), rgbImage); // TODO: Update this call to new API //maskReader->GetOutput()->ApplyToImage(rgbImage.GetPointer(), Qt::black); ITKHelpers::WriteImage(rgbImage.GetPointer(), "Test/TestIsophotes.rgb.mha"); typedef itk::RGBToLuminanceImageFilter< RGBImageType, FloatScalarImageType > LuminanceFilterType; LuminanceFilterType::Pointer luminanceFilter = LuminanceFilterType::New(); luminanceFilter->SetInput(rgbImage); luminanceFilter->Update(); ITKHelpers::WriteImage(luminanceFilter->GetOutput(), "Test/Luminance.mha"); // PatchBasedInpainting inpainting; // inpainting.SetDebugImages(true); // inpainting.SetMask(maskReader->GetOutput()); // inpainting.SetImage(imageReader->GetOutput()); //Helpers::Write2DVectorImage(inpainting.GetIsophoteImage(), "Test/TestIsophotes.isophotes.mha"); //inpainting.FindBoundary(); // After blurVariance == 4, you cannot tell the difference in the output. for(unsigned int blurVariance = 0; blurVariance < 5; ++blurVariance) { std::string fileNumber = Helpers::ZeroPad(blurVariance, 2); FloatScalarImageType::Pointer blurredLuminance = FloatScalarImageType::New(); // Blur with a Gaussian kernel MaskOperations::MaskedBlur(luminanceFilter->GetOutput(), maskReader->GetOutput(), blurVariance, blurredLuminance.GetPointer()); std::stringstream ssBlurredLuminance; ssBlurredLuminance << "Test/BlurredLuminance_" << fileNumber << ".mha"; ITKHelpers::WriteImage(blurredLuminance.GetPointer(), ssBlurredLuminance.str()); //Helpers::WriteImage<FloatScalarImageType>(blurredLuminance, "Test/TestIsophotes.blurred.mha"); FloatVector2ImageType::Pointer gradient = FloatVector2ImageType::New(); Derivatives::MaskedGradient(blurredLuminance.GetPointer(), maskReader->GetOutput(), gradient.GetPointer()); // Boundary gradient typedef itk::MaskImageFilter< FloatVector2ImageType, UnsignedCharScalarImageType, FloatVector2ImageType > MaskFilterType; MaskFilterType::Pointer maskFilter = MaskFilterType::New(); maskFilter->SetInput(gradient); //maskFilter->SetMaskImage(inpainting.GetBoundaryImage()); maskFilter->Update(); vtkSmartPointer<vtkPolyData> boundaryGradient = vtkSmartPointer<vtkPolyData>::New(); // TODO: Convert this call to new API //Helpers::ConvertNonZeroPixelsToVectors(maskFilter->GetOutput(), boundaryGradient); std::stringstream ssPolyData; ssPolyData << "Test/BoundaryGradient_" << fileNumber << ".vtp"; VTKHelpers::WritePolyData(boundaryGradient, ssPolyData.str()); } return EXIT_SUCCESS; }