# vtk polydata to binary mask

**URL:** https://discourse.vtk.org/t/vtk-polydata-to-binary-mask/11244
**Category:** Support
**Tags:** python, code, file-formats
**Created:** [April 18, 2023, 4:21pm UTC](https://discourse.vtk.org/t/vtk-polydata-to-binary-mask/11244 "2023-04-18T16:21:50Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![HuiLin0220](https://discourse.vtk.org/user_avatar/discourse.vtk.org/huilin0220/32/6791_2.png) [@HuiLin0220](https://discourse.vtk.org/u/HuiLin0220)
#### Post date: [April 18, 2023, 4:21pm UTC](https://discourse.vtk.org/t/vtk-polydata-to-binary-mask/11244/1 "2023-04-18T16:21:50Z")

</div>

I have a patient’s cardiac MRI scan (Dicom file) and its corresponding LA label in a VTK format. I wrote a code to convert the VTK file to binary mask images (like nrrd, nii.gz,etc.) I want the generated binary mask map MRIs. How to set the origin, spacing, and orientation in the code?  
My code is as follows:  
import numpy as np  
import vtk  
import cv2  
import pydicom  
import os

vtk\_path =XX  
dcms\_path=XX  
output\_path = XXXX + ‘niigz/’ + patient + ‘\_LA.nii.gz’

def get\_matrix\_patienttodicom(dicom\_file):  
# Load DICOM file  
ds = pydicom.dcmread(dicom\_file)  
## Extract image orientation and position  
iop = ds.ImageOrientationPatient  
ipp = ds.ImagePositionPatient  
print(iop)  
image\_spacing = ds.PixelSpacing  
slice\_thickness = ds.SliceThickness  
origin\_image\_spacing = [image\_spacing[0], image\_spacing[1], slice\_thickness]  
# Calculate the normal vector of the image plane  
normal = np.cross(iop[:3], iop[3:])  
w=normal / np.linalg.norm(normal)  
# Create a 4x4 transformation matrix  
matrix = np.zeros((4, 4))  
a=np.reshape(iop, (2, 3))  
matrix[:3, :2] = a.transpose()  
matrix[:3, 2] = np.array(w)  
matrix[:3, 3] = np.array([0,0,0])  
matrix[3, 3] = 1.0  
#Return the matrix  
dicom\_to\_patient = matrix  
patient\_to\_dicom = np.linalg.inv(dicom\_to\_patient)  
patient\_to\_dicom[0, :]/=origin\_image\_spacing[0]  
patient\_to\_dicom[1, :]/=origin\_image\_spacing[1]  
patient\_to\_dicom[2, :]/=origin\_image\_spacing[2]  
return patient\_to\_dicom

patient\_to\_dicom = get\_matrix\_patienttodicom(dcms\_path + “/LGE3D\_Slice1.dcm”)  
print(patient\_to\_dicom)  
‘’’  
[0.46748185 -0.46422961 0. 0.]  
[-0. -0. -0.65882351 -0.]  
[0.32028829 0.32253213 0. 0.]  
[0. 0. 0. 1.]  
‘’’  
#vtk\_to\_patient=??

vtk\_dicom = np.dot(patient\_to\_dicom,vtk\_to\_patient)  
#transform vtk to dicom  
reader = vtk.vtkPolyDataReader()  
reader.SetFileName(vtk\_path)  
reader.Update()  
#create a vtkMatrix4x4 object  
vtk\_matrix = vtk.vtkMatrix4x4()  
for i in range(4):  
for j in range(4):  
vtk\_matrix.SetElement(i, j, vtk\_dicom[i, j])

#set the matrix to the transform  
transform.SetMatrix(vtk\_matrix)  
transform\_filter = vtk.vtkTransformPolyDataFilter()  
transform\_filter.SetInputData(reader.GetOutput())  
transform\_filter.SetTransform(transform)  
transform\_filter.Update()  
transformed\_poly = transform\_filter.GetOutput()#

#obtain MRIs size  
dcm\_path = dcms\_path + “/LGE3D\_Slice1.dcm”  
dcm\_file = pydicom.dcmread(dcm\_path)  
image\_position = dcm\_file.ImagePositionPatient  
h = dcm\_file.Rows  
w = dcm\_file.Columns  
z = len(os.listdir(dcms\_path))

print("size: %d\*%d\*%d " %(h,w,z))

#set origin  
original\_origin\_array = [image\_position[0], image\_position[1], image\_position[2],1.0]  
transformed\_origin\_array = np.dot(patient\_to\_dicom,original\_origin\_array)  
print(transformed\_origin\_array)

polydata = transformed\_poly

origin = np.zeros(3)  
spacing = np.zeros(3)

spacing = [1,1,1]

dx=h  
dy=z  
dz=w

origin[0] = transformed\_origin\_array[0]  
origin[1] = transformed\_origin\_array[1]  
origin[2] = transformed\_origin\_array[2]#

sx, sy, sz = spacing  
ox, oy, oz = origin # Origin

image = vtk.vtkImageData()  
image.SetSpacing((sx, sy, sz))  
image.SetDimensions((dx, dy, dz))  
image.SetExtent(0, dx - 1, 0, dy - 1, 0, dz - 1)  
image.SetOrigin((ox, oy, oz))  
image.AllocateScalars(vtk.VTK\_UNSIGNED\_CHAR, 1)  
inval = 1  
outval = 0

for i in range(image.GetNumberOfPoints()):  
image.GetPointData().GetScalars().SetTuple1(i, inval)

pol2stenc = vtk.vtkPolyDataToImageStencil()  
pol2stenc.SetInputData(polydata)  
pol2stenc.SetOutputOrigin((ox, oy, oz))  
pol2stenc.SetOutputSpacing((sx, sy, sz))  
pol2stenc.SetOutputWholeExtent(image.GetExtent())  
pol2stenc.Update()

imgstenc = vtk.vtkImageStencil()  
imgstenc.SetInputData(image)  
imgstenc.SetStencilConnection(pol2stenc.GetOutputPort())  
imgstenc.ReverseStencilOff()  
imgstenc.SetBackgroundValue(outval)  
imgstenc.Update()

writer = vtk.vtkNIFTIImageWriter()  
writer.SetFileName(output\_path)  
writer.SetInputConnection(imgstenc.GetOutputPort())  
writer.Write()
