[vtkusers] how to export a ply file with color infomation

David Doria daviddoria at gmail.com
Tue Aug 9 08:17:27 EDT 2011

See some inline comments:

>         vtkSmartPointer<vtkPolyDataReader>
> reader=vtkSmartPointer<vtkPolyDataReader>::New();
>         reader->SetFileName("mesh.vtk");

Just FYI, .vtk is a legacy format. It seems like you have data already
in that form so there may be nothing you can do about it now, but the
preferred way would be to use .vtp files and vtkXMLPolyDataReader.

>         vtkSmartPointer<vtkDataObject>
> vtkdata=vtkSmartPointer<vtkDataObject>::New();
>         vtkdata=reader->GetOutputDataObject(0);

Two things here. 1) I believe you should know the type more
specifically, that is vtkPolyData instead of vtkDataObject, unless
.vtk files work differently than .vtp files. 2) I also believe you are
creating memory with New() and the immediately pointing the pointer
somewhere else. You should just use:

vtkPolyData* vtkdata = reader->GetOutput();

>         vtkIdType  size=36; //SIZE OF POINTS (I also do not known how to extract
> this number from reader)

vtkIdType  size = vtkdata->GetNumberOfPoints();

>         // Set the color  infomation
>        vtkSmartPointer<vtkUnsignedCharArray>
> color_array=vtkSmartPointer<vtkUnsignedCharArray>::New();
>        color_array->SetName("RGB");
>        color_array->SetNumberOfComponents(3);
>        color_array->SetNumberOfTuples(size);
>     for(vtkIdType j =0; j!=size; ++j)
>           for(vtkIdType i = 0; i!=3; ++i)
>         {
>                 color_array->SetValue(j*3+i,255);
>         }

It looks like the color array is setup properly.

>        // Convert vtk file to ply(add color info)
>        vtkSmartPointer<vtkPLYWriter> writer=vtkSmartPointer<vtkPLYWriter>::New();
>        writer->SetFileName("mesh.ply");
>        writer->SetInput(vtkdata);
>        writer->SetFileTypeToASCII();
>        writer->SetColorModeToDefault();
>        writer->SetArrayName("RGB");
>        writer->Write();

I have never seen it done like this. Typically the colors are added to
the vtkPolyData, and the writer takes care of everything with only a
SetInput call to pass the vtkPolyData. You can setup the polydata like
this: http://www.vtk.org/Wiki/VTK/Examples/Cxx/PolyData/ColoredPoints


More information about the vtkusers mailing list