Beispiel #1
0
void runVector2Mat(StringVector& args) {
    ImageIO<VectorImage2> io;
    VectorImage2::Pointer inputImage = io.ReadImage(args[0]);

    typedef itk::ImageRegionConstIteratorWithIndex<VectorImage2> VectorImageIteratorType;
    VectorImageIteratorType iter(inputImage, inputImage->GetBufferedRegion());

    ofstream ofs[2];
    ofs[0].open(args[1].c_str());
    ofs[1].open(args[2].c_str());

    VectorImage2::SizeType inputSize = inputImage->GetBufferedRegion().GetSize();

    VectorType* buffer = inputImage->GetBufferPointer();
    for (int j = 0; j < inputSize[1]; j++) {
        for (int i = 0; i < inputSize[0]; i++) {
            VectorType& vv = *buffer;
            for (int k = 0; k < 2; k++) {
                ofs[k] << vv[k] << " ";
            }
            ++buffer;
        }
        for (int k = 0; k < 2; k++) {
            ofs[k] << endl;
        }
    }

    for (int k = 0; k < 2; k++) {
        ofs[k].close();
    }
}
Beispiel #2
0
static void doSeparate(Options& opts, StringVector& args) {
    if (!opts.GetBool("--separate")) {
        return;
    }

    ImageIO<DisplacementFieldType> io;
    DisplacementFieldType::Pointer input = io.ReadImage(args[0]);

    for (int i = 0; i < DisplacementFieldType::PixelType::Length; i++) {
        ImageIO<RealImage> realIO;
        RealImage::Pointer output = realIO.NewImageS<DisplacementFieldType>(input);

        RealImage::PixelType* oBuf = output->GetBufferPointer();
        itk::ImageRegionConstIteratorWithIndex<DisplacementFieldType> iter(input, input->GetBufferedRegion());

        int j = 0;
        for (iter.GoToBegin(); !iter.IsAtEnd(); ++iter, j++) {
            DisplacementFieldType::PixelType p = iter.Get();
            oBuf[j] = p[i];
        }

        realIO.WriteImage(args[i+1], output);
    }
    end();
}
Beispiel #3
0
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;
}
Beispiel #4
0
void computeHistogram(Options& parser, StringVector& args) {
    ImageProcessing proc;
    int nbin = 16;
    int rmin = 0;
    int rmax = 10000;
    parser.GetIntTo("--nbin", nbin);
    parser.GetIntTo("--rmin", rmin);
    parser.GetIntTo("--rmax", rmax);
    cout << proc.ComputeHistogramToString(realIO.ReadImage(args[0].c_str()), nbin, rmin, rmax) << endl;
    return;
}
Beispiel #5
0
/// utility function
void zeroCrossing(Options& parser, StringVector& args) {
    if (args.size() < 2) {
        cout << "--zercorssing requires [srcimg] [dstimg]" << endl;
        return;
    }
    string srcImg = args[0];
    string dstImg = args[1];


    ImageProcessing proc;
    LabelImage::Pointer label = labelIO.ReadImage(args[0].c_str());
    LabelImage::Pointer zeroCross = proc.ZeroCrossing(label);
    labelIO.WriteImage(args[1].c_str(), zeroCross);

    return;
}
Beispiel #6
0
/// create a new image which has the same attributes with the reference image
///
int runPointMarks(pi::Options& opts, pi::StringVector& args) {
    vtkPolyDataReader* reader = vtkPolyDataReader::New();
    reader->SetFileName(args[0].c_str());
    reader->Update();

    vtkPolyData*pd = reader->GetOutput();

    // load an image
    ImageIO<RealImage> imageIO;
    RealImage::Pointer refImage = imageIO.ReadImage(args[1].c_str());


    // create an empty image
    ImageIO<LabelImage> labelIO;
    LabelImage::Pointer markImage = labelIO.NewImageS<RealImage>(refImage);
    markImage->FillBuffer(0);

    // point flipping
    for (int i = 0; i < pd->GetNumberOfPoints(); i++) {
        RealImage::PointType p;
        pd->GetPoint(i, p.GetDataPointer());
        p[0] = -p[0];
        p[1] = -p[1];
        pd->GetPoints()->SetPoint(i, p.GetDataPointer());

        // point to index
        RealImage::IndexType idx;
        refImage->TransformPhysicalPointToIndex(p, idx);

        // mark image
        markImage->SetPixel(idx, 255);
    }

    labelIO.WriteImage(args[2], markImage);
    return EXIT_SUCCESS;
}
Beispiel #7
0
int main(int argc, char* argv[]) {
    CSimpleOpt::SOption specs[] = {
        { 9, "--seeConfig", SO_NONE },
        { 1000, "--json", SO_REQ_SEP },
        { 1001, "--config", SO_REQ_SEP },
        { 1002, "--run", SO_NONE },
        { 1, "-w", SO_NONE },
        { 8, "-d", SO_NONE },
        { 2, "-o", SO_REQ_SEP },
        { 3, "--mean", SO_NONE },
        { 4, "--srcidx", SO_REQ_SEP },
        { 7, "--dstidx", SO_REQ_SEP },
        { 6, "--noTrace", SO_NONE },
        { 10, "--markTrace", SO_NONE },
        { 23, "--markOutput", SO_NONE },
        { 11, "--srcsubj", SO_REQ_SEP },
        { 12, "--inputimage", SO_REQ_SEP },
        { 13, "--inputlabel", SO_REQ_SEP },
        { 14, "--normalize", SO_NONE },
        { 15, "--magnitude", SO_NONE },
        { 16, "--distancemap", SO_NONE },
        { 17, "--createmask", SO_NONE },
        { 18, "--rescaletoshort", SO_NONE },
        { 19, "--mask", SO_REQ_SEP },
        { 20, "--align", SO_NONE },
        { 21, "--warp", SO_NONE },
        { 22, "--norigidalign", SO_NONE },
        { 24, "--onlyrigidalign", SO_NONE },
        { 25, "--showpoints", SO_NONE },
        { 26, "--eval", SO_NONE },
        { 27, "--histo", SO_NONE },
        { 28, "--nbin", SO_NONE },
        { 29, "--rmin", SO_NONE },
        { 30, "--rmax", SO_NONE },
        { 31, "--removeborder", SO_NONE },
        { 32, "--size", SO_REQ_SEP },
        { 33, "--traceWarp", SO_NONE },
        { 34, "--interval", SO_REQ_SEP },
        { 35, "--zerocrossing", SO_NONE },
        { 36, "--meanwarp", SO_NONE },
        { 41, "--magnitude2", SO_NONE },
        { 42, "--vector2mat", SO_NONE },

        // Experiment #1
        { 37, "--expr1", SO_NONE },
        { 39, "--expr2", SO_NONE },
        { 40, "--bspline2d", SO_NONE },
        { 43, "--particleExpr", SO_NONE },

        // Image Processing
        { 100, "--doGaussian", SO_REQ_SEP },
        { 101, "--doBlur2", SO_NONE },
        { 102, "--ellipse", SO_NONE },
        { 103, "--affineReg", SO_NONE },
        { 104, "--gradhist", SO_NONE },
        { 105, "--testgradreg", SO_NONE },
        { 106, "--gradmag", SO_NONE },
        { 107, "--transform2", SO_NONE },
        { 108, "--boundingbox", SO_NONE },
        { 109, "--crop", SO_REQ_SEP },
        { 110, "--slice", SO_NONE },
        { 111, "--padding", SO_REQ_SEP },
        { 112, "--deform", SO_NONE },
        { 113, "--testdisplacementfield", SO_NONE },
        { 114, "--distmap2contour", SO_NONE },

        // Test Main
        { 200, "--newuoa", SO_NONE },
        { 201, "--boost", SO_NONE },
        { 202, "--testconfig", SO_NONE },

        // Particle Tools
        { 300, "--coverlabel", SO_NONE },
        { 301, "--p2mat", SO_NONE },

        // Options Test
        { 400, "--testjson", SO_NONE },

        // PatchCompare
        { 500, "--demons", SO_NONE },
        { 501, "--makeGradientPatch", SO_NONE },
        { 502, "--opticalFlow", SO_NONE },
        { 503, "--patchtest", SO_NONE },

        SO_END_OF_OPTIONS
    };

    cout << argv[0] << " version compiled at " << __TIMESTAMP__ << endl;
    Options parser;
    parser.ParseOptions(argc, argv, specs);
    StringVector& args = parser.GetStringVector("args");
    string output = parser.GetString("-o", "");

    ParticleSystemSolver solver;
    ParticleSystem& system = solver.m_System;
    Options& options = solver.m_Options;


    srcIdx = atoi(parser.GetString("--srcidx", "1").c_str());
    dstIdx = atoi(parser.GetString("--dstidx", "0").c_str());

    if (parser.GetBool("--run")) {
        executeParticleRunner(parser, args);
        return 0;
    } else if (parser.GetBool("--demons")) {
        executeDemonsRunner(parser, args);
    } else if (parser.GetBool("--expr1")) {
        runExpr1(args);
    } else if (parser.GetBool("--expr2")) {
        runExpr2(args);
    } else if (parser.GetBool("--bspline2d")) {
        runBspline2D(args);
    } else if (parser.GetBool("--vector2mat")) {
        runVector2Mat(args);
    } else if (parser.GetBool("--particleExpr")) {
        runParticleExperiments(args);
    } else if (parser.GetBool("--seeConfig")) {
        solver.LoadConfig(args[0].c_str());
        cout << "Option Contents:\n\n" << options << endl;
        if (args.size() > 1) {
            solver.SaveConfig(args[1].c_str());
        }
    } else if (parser.GetBool("-w", false)) {
        if (args.size() < 1 || output == "") {
            cout << "warping requires [config.txt] -o [outputimage]" << endl;
            return 0;
        }

        // load data
        solver.LoadConfig(args[0].c_str());

        // bspline resampling
        ParticleBSpline particleTransform;
        particleTransform.SetReferenceImage(solver.m_System[0].GetLabel());

        int srcIdx = atoi(parser.GetString("--srcidx", "1").c_str());
        int dstIdx = atoi(parser.GetString("--dstidx", "0").c_str());

        if (parser.GetBool("--mean")) {
            system.ComputeXMeanSubject();
            particleTransform.EstimateTransform(system.GetMeanSubject(), system[srcIdx]);
        } else {
            cout << "warping from " << srcIdx << " to " << dstIdx << endl;
            particleTransform.EstimateTransform(system[dstIdx], system[srcIdx]);
        }


        string input = parser.GetString("--inputimage", "");
        string label = parser.GetString("--inputlabel", "");

        cout << parser << endl;

        bool doingSomething = false;
        if (label != "") {
            // write image
            ImageIO<LabelImage> io;
            LabelImage::Pointer outputImage = particleTransform.WarpLabel(io.ReadImage(label.c_str()));
            io.WriteImage(output.c_str(), outputImage);
            doingSomething = true;
        }
        if (input != "") {
            ImageIO<RealImage> io;
            RealImage::Pointer outputImage = particleTransform.WarpImage(io.ReadImage(input.c_str()));
            io.WriteImage(output.c_str(), outputImage);
            doingSomething = true;
        }
        if (!doingSomething) {
            cout << "-w requires --inputimage or --inputlabel to warp" << endl;
        }
    } else if (parser.GetBool("--warp")) {
        if (args.size() < 2) {
            cout << "--warp requires [output.txt] --inputimage|inputlabel [source-image] --reference [reference] [warped-output-image]" << endl;
            return 0;
        }

        PRINT_IDX();
        string outputName = args[1];
        string inputImage, inputLabel, refImageName;
        parser.GetStringTo("--inputimage", inputImage);
        parser.GetStringTo("--inputlabel", inputLabel);
        parser.GetStringTo("--reference", refImageName);

        solver.LoadConfig(args[0].c_str());


        if (system.size() < 2) {
            cout << "system is not loaded successfully" << endl;
            return 0;
        }
        if (inputImage != "") {
            RealImage::Pointer refImage;
            // warp from srcidx to dstidx
            if (refImageName != "") {
                refImage = realIO.ReadImage(refImageName.c_str());
            }
            RealImage::Pointer output = warp_image<RealImage>(system[dstIdx], system[srcIdx], realIO.ReadImage(inputImage.c_str()), refImage, false, parser.GetBool("--norigidalign"), parser.GetBool("--onlyrigidalign"));
            realIO.WriteImage(outputName.c_str(), output);
        }
        if (inputLabel != "") {
            LabelImage::Pointer refImage;
            // warp from srcidx to dstidx
            if (refImageName != "") {
                refImage = labelIO.ReadImage(refImageName.c_str());
            }
            LabelImage::Pointer output = warp_image<LabelImage>(system[dstIdx], system[srcIdx], labelIO.ReadImage(inputLabel.c_str()), refImage, true, parser.GetBool("--norigidalign"), parser.GetBool("--onlyrigidalign"));
            labelIO.WriteImage(outputName.c_str(), output);
        }
    } else if (parser.GetBool("--meanwarp")) {
        if (args.size() < 2) {
            cout << "--meanwarp requires [output.txt] --inputimage|--inputlabel [source-image] [warped-output-image]" << endl;
            return 0;
        }

        PRINT_IDX();
        string outputName = args[1];
        string inputImage, inputLabel, refImageName;
        parser.GetStringTo("--inputimage", inputImage);
        parser.GetStringTo("--inputlabel", inputLabel);
        parser.GetStringTo("--reference", refImageName);

        solver.LoadConfig(args[0].c_str());


        ParticleSubject meanSubj = system.ComputeXMeanSubject();

        if (system.size() < 2) {
            cout << "system is not loaded successfully" << endl;
            return 0;
        }
        if (inputImage != "") {
            RealImage::Pointer refImage;
            // warp from srcidx to dstidx
            if (refImageName != "") {
                refImage = realIO.ReadImage(refImageName.c_str());
            }
            RealImage::Pointer output = warp_image<RealImage>(meanSubj, system[srcIdx], realIO.ReadImage(inputImage.c_str()), refImage, false, parser.GetBool("--norigidalign"), parser.GetBool("--onlyrigidalign"));
            realIO.WriteImage(outputName.c_str(), output);
        }
        if (inputLabel != "") {
            LabelImage::Pointer refImage;
            // warp from srcidx to dstidx
            if (refImageName != "") {
                refImage = labelIO.ReadImage(refImageName.c_str());
            }
            LabelImage::Pointer output = warp_image<LabelImage>(meanSubj, system[srcIdx], labelIO.ReadImage(inputLabel.c_str()), refImage, true, parser.GetBool("--norigidalign"), parser.GetBool("--onlyrigidalign"));
            labelIO.WriteImage(outputName.c_str(), output);
        }

    } else if (parser.GetBool("--markTrace")) {
        if (args.size() < 2) {
            cout << "--meanwarp requires [output.txt] [reference-image] [output-image] --srcidx [point-index] --srcsubj [subject-index]" << endl;
            return 0;
        }
        ifstream in(args[0].c_str());
        ParticleTrace trace;
        trace.Read(in);
        in.close();
        cout << trace << endl;

        int srcIdx = atoi(parser.GetString("--srcidx", "-1").c_str());
        int srcSubj = atoi(parser.GetString("--srcsubj", "-1").c_str());

        ImageIO<LabelImage> io;
        LabelImage::Pointer ref = io.ReadImage(args[1].c_str());
        LabelImage::Pointer canvas = io.NewImage(ref);
        for (int i = 0; i < trace.system.size(); i++) {
            if (srcSubj == -1 || srcSubj == i) {
                for (int j = 0; j < trace.system[i].timeSeries.size(); j++) {
                    for (int k = 0; k <= trace.system[i].maxIdx; k++) {
                        if (srcIdx == -1 || srcIdx == k) {
                            Particle& p = trace.system[i].timeSeries[j][k];
                            IntIndex idx;
                            fordim (l) {
                                idx[l] = p.x[l] + 0.5;
                            }
                            (*canvas)[idx] = j;
                        }
                    }
                }
            }
        }
    } else if (parser.GetBool("--markOutput")) {
Beispiel #8
0
// perform B-spline registration for 2D image
void runBspline2D(StringVector& args) {
    typedef itk::BSplineTransform<double, 2, 3> TransformType;
    typedef itk::LBFGSOptimizer OptimizerType;
    typedef itk::MeanSquaresImageToImageMetric<RealImage2, RealImage2> MetricType;
    typedef itk:: LinearInterpolateImageFunction<RealImage2, double> InterpolatorType;
    typedef itk::ImageRegistrationMethod<RealImage2, RealImage2> RegistrationType;

    MetricType::Pointer         metric        = MetricType::New();
    OptimizerType::Pointer      optimizer     = OptimizerType::New();
    InterpolatorType::Pointer   interpolator  = InterpolatorType::New();
    RegistrationType::Pointer   registration  = RegistrationType::New();

    // The old registration framework has problems with multi-threading
    // For now, we set the number of threads to 1
    registration->SetNumberOfThreads(1);

    registration->SetMetric(        metric        );
    registration->SetOptimizer(     optimizer     );
    registration->SetInterpolator(  interpolator  );

    TransformType::Pointer  transform = TransformType::New();
    registration->SetTransform( transform );


    ImageIO<RealImage2> io;

    // Create the synthetic images
    RealImage2::Pointer  fixedImage  = io.ReadImage(args[0]);
    RealImage2::Pointer  movingImage  = io.ReadImage(args[1]);

    // Setup the registration
    registration->SetFixedImage(  fixedImage   );
    registration->SetMovingImage(   movingImage);

    RealImage2::RegionType fixedRegion = fixedImage->GetBufferedRegion();
    registration->SetFixedImageRegion( fixedRegion );

    TransformType::PhysicalDimensionsType   fixedPhysicalDimensions;
    TransformType::MeshSizeType             meshSize;
    for( unsigned int i=0; i < 2; i++ )
    {
        fixedPhysicalDimensions[i] = fixedImage->GetSpacing()[i] *
        static_cast<double>(
                            fixedImage->GetLargestPossibleRegion().GetSize()[i] - 1 );
    }
    unsigned int numberOfGridNodesInOneDimension = 18;
    meshSize.Fill( numberOfGridNodesInOneDimension - 3 );
    transform->SetTransformDomainOrigin( fixedImage->GetOrigin() );
    transform->SetTransformDomainPhysicalDimensions( fixedPhysicalDimensions );
    transform->SetTransformDomainMeshSize( meshSize );
    transform->SetTransformDomainDirection( fixedImage->GetDirection() );

    typedef TransformType::ParametersType     ParametersType;

    const unsigned int numberOfParameters =
    transform->GetNumberOfParameters();

    ParametersType parameters( numberOfParameters );

    parameters.Fill( 0.0 );

    transform->SetParameters( parameters );

    //  We now pass the parameters of the current transform as the initial
    //  parameters to be used when the registration process starts.

    registration->SetInitialTransformParameters( transform->GetParameters() );

    std::cout << "Intial Parameters = " << std::endl;
    std::cout << transform->GetParameters() << std::endl;

    //  Next we set the parameters of the LBFGS Optimizer.

    optimizer->SetGradientConvergenceTolerance( 0.005 );
    optimizer->SetLineSearchAccuracy( 0.9 );
    optimizer->SetDefaultStepLength( .1 );
    optimizer->TraceOn();
    optimizer->SetMaximumNumberOfFunctionEvaluations( 1000 );

    std::cout << std::endl << "Starting Registration" << std::endl;

    try
    {
        registration->Update();
        std::cout << "Optimizer stop condition = "
        << registration->GetOptimizer()->GetStopConditionDescription()
        << std::endl;
    }
    catch( itk::ExceptionObject & err )
    {
        std::cerr << "ExceptionObject caught !" << std::endl;
        std::cerr << err << std::endl;
        return;
    }

    OptimizerType::ParametersType finalParameters =
    registration->GetLastTransformParameters();

    std::cout << "Last Transform Parameters" << std::endl;
    std::cout << finalParameters << std::endl;

    transform->SetParameters( finalParameters );

    typedef itk::ResampleImageFilter<RealImage2, RealImage2> ResampleFilterType;

    ResampleFilterType::Pointer resample = ResampleFilterType::New();

    resample->SetTransform( transform );
    resample->SetInput( movingImage );

    resample->SetSize(    fixedImage->GetLargestPossibleRegion().GetSize() );
    resample->SetOutputOrigin(  fixedImage->GetOrigin() );
    resample->SetOutputSpacing( fixedImage->GetSpacing() );
    resample->SetOutputDirection( fixedImage->GetDirection() );
    resample->SetDefaultPixelValue( 100 );
    resample->Update();

    io.WriteImage(args[2], resample->GetOutput());
}
Beispiel #9
0
/// perform scan conversion
/// [input-vtk] [reference-image] [output-image]
///
int runScanConversion(pi::Options& opts, pi::StringVector& args) {
    vtkPolyDataReader* reader = vtkPolyDataReader::New();
    reader->SetFileName(args[0].c_str());
    reader->Update();

    vtkPolyData*pd = reader->GetOutput();

    // point flipping
    for (int i = 0; i < pd->GetNumberOfPoints(); i++) {
        double p[3];
        pd->GetPoint(i, p);
        p[0] = -p[0];
        p[1] = -p[1];
        pd->GetPoints()->SetPoint(i, p);
    }

    vtkSmartPointer<vtkImageData> whiteImage = vtkSmartPointer<vtkImageData>::New();

    ImageIO<RealImage> imageIO;
    RealImage::Pointer refImage = imageIO.ReadImage(args[1].c_str());


    // compute bounding box
    RealImage::RegionType region = refImage->GetBufferedRegion();
    RealImage::IndexType lowerIndex = region.GetIndex();
    RealImage::IndexType upperIndex = region.GetUpperIndex();

    RealImage::PointType lowerPoint, upperPoint;
    refImage->TransformIndexToPhysicalPoint(lowerIndex, lowerPoint);
    refImage->TransformIndexToPhysicalPoint(upperIndex, upperPoint);

    // mesh bounds
    double bounds[6];

    // image bounds
    bounds[0] = lowerPoint[0];
    bounds[1] = upperPoint[0];
    bounds[2] = lowerPoint[1];
    bounds[3] = upperPoint[1];
    bounds[4] = lowerPoint[2];
    bounds[5] = upperPoint[2];


    // print bounds
    for (int i = 0; i < 6; i++) {
        cout << bounds[i] << ", ";
    }
    cout << endl;


    // make the same spacing as refImage
    double spacing[3]; // desired volume spacing
    for (int i = 0; i < 3; i++) {
        spacing[i] = refImage->GetSpacing()[i];
    }
    whiteImage->SetSpacing(spacing);

    // compute dimensions
    int dim[3];
    for (int i = 0; i < 3; i++)
    {
        dim[i] = static_cast<int>(ceil((bounds[i * 2 + 1] - bounds[i * 2]) / spacing[i])) + 1;
    }
    whiteImage->SetDimensions(dim);
    whiteImage->SetExtent(0, dim[0] - 1, 0, dim[1] - 1, 0, dim[2] - 1);

    double origin[3];
    origin[0] = bounds[0] + spacing[0] / 2;
    origin[1] = bounds[2] + spacing[1] / 2;
    origin[2] = bounds[4] + spacing[2] / 2;
    whiteImage->SetOrigin(origin);

#if VTK_MAJOR_VERSION <= 5
    whiteImage->SetScalarTypeToUnsignedChar();
    whiteImage->AllocateScalars();
#else
    whiteImage->AllocateScalars(VTK_UNSIGNED_CHAR,1);
#endif
    // fill the image with foreground voxels:
    unsigned char inval = 255;
    unsigned char outval = 0;
    vtkIdType count = whiteImage->GetNumberOfPoints();
    for (vtkIdType i = 0; i < count; ++i)
    {
        whiteImage->GetPointData()->GetScalars()->SetTuple1(i, inval);
    }

    // polygonal data --> image stencil:
    vtkSmartPointer<vtkPolyDataToImageStencil> pol2stenc =
    vtkSmartPointer<vtkPolyDataToImageStencil>::New();
#if VTK_MAJOR_VERSION <= 5
    pol2stenc->SetInput(pd);
#else
    pol2stenc->SetInputData(pd);
#endif
    pol2stenc->SetOutputOrigin(origin);
    pol2stenc->SetOutputSpacing(spacing);
    pol2stenc->SetOutputWholeExtent(whiteImage->GetExtent());
    pol2stenc->Update();

    // cut the corresponding white image and set the background:
    vtkSmartPointer<vtkImageStencil> imgstenc =
    vtkSmartPointer<vtkImageStencil>::New();
#if VTK_MAJOR_VERSION <= 5
    imgstenc->SetInput(whiteImage);
    imgstenc->SetStencil(pol2stenc->GetOutput());
#else
    imgstenc->SetInputData(whiteImage);
    imgstenc->SetStencilConnection(pol2stenc->GetOutputPort());
#endif
    imgstenc->ReverseStencilOff();
    imgstenc->SetBackgroundValue(outval);
    imgstenc->Update();

    vtkSmartPointer<vtkMetaImageWriter> writer =
    vtkSmartPointer<vtkMetaImageWriter>::New();
    writer->SetFileName("SphereVolume.mhd");
#if VTK_MAJOR_VERSION <= 5
    writer->SetInput(imgstenc->GetOutput());
#else
    writer->SetInputData(imgstenc->GetOutput());
#endif
    writer->Write();
    
    return EXIT_SUCCESS;
}