How to convert .stl file to 3D .mha or .nii - vtk

Can someone please guide me through how to convert .stl file to .nii or .mha file? I use the below code to load the .stl file and render it. But I am still unable to find a code to save that render file into .nii or .mha, I am very new to this VTK and ITK library. Thank you in advance for your help.
import vtkmodules.vtkInteractionStyle
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkIOGeometry import vtkSTLReader
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
filename = 'filename.stl'
colors = vtkNamedColors()
reader = vtkSTLReader()
reader.SetFileName(filename)
mapper = vtkPolyDataMapper()
if vtk.VTK_MAJOR_VERSION <= 5:
mapper.SetInput(reader.GetOutput())
else:
mapper.SetInputConnection(reader.GetOutputPort())
actor = vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetDiffuse(0.8)
#actor.GetProperty().SetDiffuseColor(colors.GetColor3d('LightSteelBlue'))
actor.GetProperty().SetSpecular(0.3)
actor.GetProperty().SetSpecularPower(60.0)
# Create a rendering window and renderer
ren = vtkRenderer()
renWin = vtkRenderWindow()
renWin.AddRenderer(ren)
renWin.SetWindowName('ReadSTL')
# Create a renderwindowinteractor
iren = vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# Assign actor to the renderer
ren.AddActor(actor)
#ren.SetBackground(colors.GetColor3d('DarkOliveGreen'))
# Enable user interface interactor
iren.Initialize()
renWin.Render()
iren.Start()

There is a VTK C++ example which does what you want. There is also a Python example that does a bit more. You can combine them to get what you want.

There is an ITK C++ example and Python code snippet which show how to do this using ITK.

Related

Rendering a gltf/glb file in jupyter notebook using vtk and k3d

I have explored the available methods of how to render a gltf/glb file inline in a jupyter notebook to keep the viewer callback interactivity intact. I have eventually ended up using vtk and k3d to achieve this. The two hurdles I have are:
How to use the vtkGLTFReader() to get vtkPolyData objects from the
glb and render these in k3d? SOLUTION: See method posted in the comments.
How to display colors/textures embedded in the gltf/glb to show them in
k3d?
Here is the code to get vtkPolyData and pass it to k3d.
import k3d
import vtk
import ipywidgets as widgets
reader = vtk.vtkGLTFReader()
reader.SetFileName('sample_glb/GroundVehicle.glb')
reader.Update()
plot = k3d.plot()
mb = reader.GetOutput()
iterator = mb.NewIterator()
vtk_polyobjects = []
while not iterator.IsDoneWithTraversal():
item = iterator.GetCurrentDataObject()
vtk_polyobjects.append(item)
iterator.GoToNextItem()
for obj in vtk_polyobjects:
plot += k3d.vtk_poly_data(obj, color=0x222222)
plot.display()
debug_info = widgets.HTML()

vtkOBJReader object has no attribute SetFileNameMTL (.mtl) for Object (.obj) files

The code below complains that vtk.vtkOBJReader() object has no method SetFileNameMTL().
In the documentation it appears to exist vtkOBJImporter.SetFileNameMTL (Maybe the python wrapper for this is missing?).
How can the material (.mtl) for the object be set when parsing the (.obj) in vtk and made visible in k3d?
import k3d
import vtk
import ipywidgets as widgets
reader = vtk.vtkOBJReader()
reader.SetFileName('sample_obj/Model.obj')
reader.SetFileNameMTL('sample_obj/Model.mtl') #Attribute not found
reader.Update()
plot = k3d.plot()
poly_data = reader.GetOutput()
plot += k3d.vtk_poly_data(poly_data)
plot.display()
You are using vtkOBJReader, not vtkOBJImporter. Those are two different classes. vtkOBJReader is the older class, I think, and only reads in the geometry file. To load the material info, you need to use vtkOBJImporter.

Python Pillow ImageChops.difference always None

I'm trying to compare screenshots of 2 interactive maps. The screenshots are taken with Selenium and using Pillow to compare.
...
from selenium.webdriver.common.by import By
from selenium import webdriver
from io import BytesIO
from PIL import ImageChops, Image
...
png_bytes1 = driver.find_element(By.CSS_SELECTOR, "body").screenshot_as_png
png_bytes2 = driver2.find_element(By.CSS_SELECTOR, "body").screenshot_as_png
img1 = Image.open(BytesIO(png_bytes1))
img2 = Image.open(BytesIO(png_bytes2))
diff = ImageChops.difference(img1, img2)
print(diff.getbbox())
But diff is always blank. I manually used img1.show() and img2.show() to obtain the images below. diff.show() is always blank and diff.getbbox() prints None. What am I doing wrong and is there a better way of doing it?
Update: It works if I first save these images as jpg. Anyone have ideas why?
It seems ImageChops.difference() will only work if the image parameters are Image objects. PNG files are PngImageFile objects, with an RGBA mode for an extra alpha layer and need to be converted using converted_img1 = img1.convert('RGB').

Add text contents to Photoshop layer via the comtypes library

I want to add a text layer to a psd file. I was able to add a layer but I don't know how to write a content or to locate the content in that layer.
Can anyone tell me?
I imported win32com and this is what I got for now.
import win32com.client
psApp = win32com.client.Dispatch("Photoshop.Application")
psApp.Open('file path') # Opens a PSD file
doc = psApp.Application.ActiveDocument # Get active document object
layers = doc.ArtLayers
newTextLayer = layers.add # add a layer
newTextLayer.kind = 2 # specify a text layer
newTextLayer.name = 'new' # name the layer
newTextLayer = 'text content' # this line is what I am struggling with.
doc.save
doc.close
Edit: I am using python 3.6. and Photoshop CC.
I recommend you to format your code using Markdown (or the internal editor) so that's more clear for other readers to help you. See this link .
The newTextLayer is basically inheriting from the main TextItem object. That's why to solve your problem you need to do this:
import win32com.client
psApp = win32com.client.Dispatch("Photoshop.Application")
psApp.Open('file path') # Opens a PSD file
doc = psApp.Application.ActiveDocument # Get active document object
layers = doc.ArtLayers
newTextLayer = layers.add # add a layer
newTextLayer.kind = 2 # specify a text layer
newTextLayer.name = 'new' # name the layer
newTextLayer.TextItem.Contents = 'text content'
doc.save
doc.close

STEP file reading issue in Python

I am using Python3.4.2 and pythonOCC-0.16.0-win32-py34.exe to draw components. Every components are rendered properly with one defined color but that is not look like a real world component.
Above image is my Python implementation which generate 3D image from STEP file with one color.
Below image is rendered one of my windows software and there I have used Step file. I want to render component same as look like in below image so its look like a real world component.
Is there any way to get correct colored output in Python by read STEP file? I have searched a lot but didn't get a way to implement it. Please help me to go in forward direction.
from future import print_function
import sys
#from OCC.STEPCAFControl import STEPCAFControl_Reader
from OCC.STEPControl import STEPControl_Reader
from OCC.IFSelect import IFSelect_RetDone, IFSelect_ItemsByEntity
from OCC.Display.SimpleGui import init_display
from OCC.Display.WebGl import threejs_renderer
step_reader = STEPControl_Reader()
status = step_reader.ReadFile('./models/test.STEP')
if status == IFSelect_RetDone: # check status
failsonly = False
step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)
step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity)
ok = step_reader.TransferRoot(1)
_nbs = step_reader.NbShapes()
aResShape = step_reader.Shape(1)
else:
print("Error: can't read file.")
sys.exit(0)
#display, start_display, add_menu, add_function_to_menu = init_display()
#display.DisplayShape(aResShape, update=True)
#start_display()
my_renderer = threejs_renderer.ThreejsRenderer(background_color="#123345")
my_renderer.DisplayShape(aResShape)
The above code is used for read STEP file using Python.

Resources