# How to convert 3D numpy array to vtk and save the .vtk file?

**URL:** <https://discourse.slicer.org/t/how-to-convert-3d-numpy-array-to-vtk-and-save-the-vtk-file/22327>\
**Category:** Support\
**Tags:** vtk, python\
**Created:** [March 5, 2022, 6:23pm UTC](https://discourse.slicer.org/t/how-to-convert-3d-numpy-array-to-vtk-and-save-the-vtk-file/22327 "2022-03-05T18:23:12Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![user4](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/user4/32/13172_2.png) [@user4](https://discourse.slicer.org/u/user4)\
**Post date:** [March 8, 2022, 9:06am UTC](https://discourse.slicer.org/t/how-to-convert-3d-numpy-array-to-vtk-and-save-the-vtk-file/22327/3 "2022-03-08T09:06:52Z")

</div>

yes you are right.

```auto
import vtk.util.numpy_support as numpy_support

def numpyToVTK(data):
    data_type = vtk.VTK_FLOAT
    shape = data.shape

    flat_data_array = data.flatten()
    vtk_data = numpy_support.numpy_to_vtk(num_array=flat_data_array, deep=True, array_type=data_type)
    
    img = vtk.vtkImageData()
    img.GetPointData().SetScalars(vtk_data)
    img.SetDimensions(shape[0], shape[1], shape[2])
    return img

```

with the above function I did a quick test below:

```auto
test_arr = np.arange(36).reshape(3,4,3)
test_arr

--> array([[
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [9, 10, 11]],

       [[12, 13, 14],
        [15, 16, 17],
        [18, 19, 20],
        [21, 22, 23]],

       [[24, 25, 26],
        [27, 28, 29],
        [30, 31, 32],
        [33, 34, 35]]])

```

img = numpyToVTK(data)

**Then verify the vtkImageData is right or not**

```auto
test = vtk.util.numpy_support.vtk_to_numpy(img.GetPointData().GetScalars())
test = test.reshape(3,4,3)
(test == test_arr).all()

-->True

```

However,I’m like you and don’t know how to save the vtk file to the hard drive

---

_[View the full topic](https://discourse.slicer.org/t/how-to-convert-3d-numpy-array-to-vtk-and-save-the-vtk-file/22327)._
