Convert png to vti

Hello!

I want to convert png to vti.

However, the following code does not work correctly.

import os
import cv2
import numpy as np
import pydicom
import matplotlib.pylab as plt

from glob import glob

def dividePath(dataPath):
imgFileList =

for idx, name in enumerate(dataPath):
    imgFileList.append(name)
imgFileList.sort()

return imgFileList

def imageLoad(imageFileName):
firstImage = cv2.imread(os.path.join(path, imageFileName[0]))

if len(firstImage.shape) == 2:
    imgRows, imgCols = firstImage.shape[:2]
    imageList = np.zeros((len(imageFileName), imgRows, imgCols, 1))

else:
    imgRows, imgCols, imgColor = firstImage.shape[:3]
    imageList = np.zeros((len(imageFileName), imgRows, imgCols, imgColor))

for idx, fileName in enumerate(imageFileName):
    imageData = cv2.imread(os.path.join(path, fileName))
    copyImageData = imageData.copy()

    imageList[idx, :, :, :] = copyImageData

#print(imageList.shape)
return imageList

global path
global dataPath
path = “C:/JLKINSPECTION_NUC/Material/PNG/patient002_image”
dataPath = os.listdir(path)

imageFileList= dividePath(dataPath)

imageList = imageLoad(imageFileList)
print(imageList)

from pyevtk.hl import imageToVTK

imageToVTK(“./brainResult8”, pointData={“DICOMImages” : imageList})

However, the following error occurs.

"Bad array shape: " + str(data.shape)

I think there is a problem with png’s data array to convert to vti. But I can’t find a solution.

Can anyone tell me if I know about this?

Could you provide a sample PNG image?

You may want to use VTK’s vtkPNGReader class which PyVista leverages to load image files as vtkImageData (vti). Here’s an example using a PNG that is shipped with PyVista:

import pyvista as pv
from pyvista import examples

# This is a jpeg but could be a PNG
image_file = examples.mapfile

image = pv.read(image_file)
image.save('my_image.vti')

image.plot(cpos='xy')

1 Like

Thank you for your reply,

It really helped me a lot.

Can I load a png as a directory instead of just one?

If you use ParaView with pvpython you can execute the following code sample

from paraview import simple

imageStack = simple.PNGSeriesReader(
    FileNames=[
        '/datasets/l00001.png', 
        '/datasets/l00002.png', 
        ...
    ],
    DataSpacing=[1,1,1])

simple.SaveData('/tmp/deleteMe.vti', proxy=imageStack, CompressorType='ZLib')
2 Likes

I was able to solve it with your help.

Thank you again!:grinning:

1 Like