Skip to content

ImageDataToPointSet

vtk-examples/Cxx/ImageData/ImageDataToPointSet

Question

If you have a question about this example, please use the VTK Discourse Forum

Code

ImageDataToPointSet.cxx

#include <vtkImageData.h>
#include <vtkPoints.h>
#include <vtkImageDataToPointSet.h>
#include <vtkNew.h>
#include <vtkXMLStructuredGridWriter.h>
#include <vtkStructuredGrid.h>

namespace {

void CreateImage(vtkImageData* image);
}

int main(int, char *[])
{
  vtkNew<vtkImageData> image;
  CreateImage(image);

  vtkNew<vtkImageDataToPointSet> imageDataToPointSet;
  imageDataToPointSet->SetInputData(image);
  imageDataToPointSet->Update();

  vtkNew<vtkXMLStructuredGridWriter> writer;
  writer->SetInputConnection(imageDataToPointSet->GetOutputPort());
  writer->SetFileName("Test.vts");
  writer->Write();

  return EXIT_SUCCESS;
}

namespace {

void CreateImage(vtkImageData* image)
{
  // Create an image
  image->SetDimensions(3,3,1);
  image->AllocateScalars(VTK_UNSIGNED_CHAR,1);

  int dims[3];
  image->GetDimensions(dims);
  for(int i = 0; i < dims[0]; i++)
  {
    for(int j = 0; j < dims[1]; j++)
    {
      unsigned char* pixel = static_cast<unsigned char*>(image->GetScalarPointer(i,j,0));
      pixel[0] = 1;
    }
  }
}

}

CMakeLists.txt

cmake_minimum_required(VERSION 3.12 FATAL_ERROR)

project(ImageDataToPointSet)

find_package(VTK COMPONENTS 
  CommonCore
  CommonDataModel
  FiltersGeneral
  IOXML
)

if (NOT VTK_FOUND)
  message(FATAL_ERROR "ImageDataToPointSet: Unable to find the VTK build folder.")
endif()

# Prevent a "command line is too long" failure in Windows.
set(CMAKE_NINJA_FORCE_RESPONSE_FILE "ON" CACHE BOOL "Force Ninja to use response files.")
add_executable(ImageDataToPointSet MACOSX_BUNDLE ImageDataToPointSet.cxx )
  target_link_libraries(ImageDataToPointSet PRIVATE ${VTK_LIBRARIES}
)
# vtk_module_autoinit is needed
vtk_module_autoinit(
  TARGETS ImageDataToPointSet
  MODULES ${VTK_LIBRARIES}
)

Download and Build ImageDataToPointSet

Click here to download ImageDataToPointSet and its CMakeLists.txt file. Once the tarball ImageDataToPointSet.tar has been downloaded and extracted,

cd ImageDataToPointSet/build

If VTK is installed:

cmake ..

If VTK is not installed but compiled on your system, you will need to specify the path to your VTK build:

cmake -DVTK_DIR:PATH=/home/me/vtk_build ..

Build the project:

make

and run it:

./ImageDataToPointSet

WINDOWS USERS

Be sure to add the VTK bin directory to your path. This will resolve the VTK dll's at run time.