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.
Related
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.
From the Matplotlib's official website I can get that the function 'ax.set()' can bset attributes.But I haven't known what attributes can I set actually.For instance:
from matplotlib import pyplot as plt
import numpy as np
import matplotlib
fig=plt.figure(
figsize=(15,6),
dpi=120,
)
#definition layout
layout=(2,4)
#create
axes=fig.subplots(*layout)
ax_plot_function=axes[0][0]
ax_scatter=axes[0][1]
#plot the first axes
props = {
'title': 'function_example$f(x)=cos(x)$',
'xlabel': 'X',
'ylabel':'Y',
'xlim':(-(2*np.pi),2*np.pi),
'ylim':(-(np.pi),np.pi),
'grid':True,
}
ax_plot_function.set(**props)
x=np.arange(-(2*np.pi),2*np.pi,0.01)
y=np.cos(x)
ax_plot_function.plot(x,y)
plt.show()
in Line29 happens an error that says
AttributeError: 'AxesSubplot' object has no property 'grid'
So I know that the function 'set()' can not have the attribute 'grid' in Line27,But how can I fix it and What attributes can I set exactly by using the function 'ax.set()'.
Could I get a list of all attributes that can set by the function 'set()'? Or Please tell me where I can find the list.
ax.set() can set the properties defined in class matplotlib.axes.Axes.
There is also set_xxx() api where xxx is also the property in class matplotlib.axes.Axes.
The idea is simple, image you create a Python class and some properties. The related getter and setter method should be defined. Also, the constructor method can take initial values of those properties.
If you want to turn on the grid, use ax.grid(True).
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()
This is a continuation of this question. I understand that calling a plotting function from a block thread is problematic because it might conflict with the WX Gui thread.
Can anyone show me a very simple code snippet which plots the value of input_items using an existing visualizer instead of plotting it inside the block thread?
Here is an outline of the GNU Radio sync_block which receives the values to be plotted in input_items :
import numpy
from gnuradio import gr
class xyz(gr.sync_block):
def __init__(self, multiple):
gr.sync_block.__init__(self,
name="xyz",
in_sig=[<+numpy.float+>],
out_sig=[<+numpy.float+>])
def work(self, input_items, output_items):
in0 = input_items[0]
out = output_items[0]
.....
# How to pass the value of input_items to an existing visualizer which plots a graph based on these values on the GUI
.....
out[:] = in0
return len(output_items[0])
Also which existing plot block(in gnuradio/gr-wxgui) is suggested to be used as a reference for this?
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.