My first question here. I am working to a visualization pipeline with the vtk library (neuroimaging data). However, I am really struggling with the affine handling. From the documentation (example, doxygen, books) It seems I should use something like this:
transform = vtkTransform()
matrix_vtk =vtkMatrix4x4()
matrix_vtk.DeepCopy((1, 0, 0, 0, 0, 1, 0, 1, 0,0,1,0,0,0,0,1))
transform.SetMatrix(matrix_vtk)
transform_filter = vtkTransformPolyDataFilter()
transform_filter.SetTransform(transform)
dataset_mapper = vtk.vtkDataSetMapper()
dataset_mapper.SetInputConnection(transform_filter.GetOutputPort())
actor.SetMapper(dataset_mapper)
However the results are not those I expected :D
The complete code is:
from vtk import *
fname_trk = "test/L113619_imfs_d10_110mm.trk"
fname_vtk = "test/L113619_imfs_d10.vtk"
fname_ply = "test/113619_Lwhite.ply"
reader = vtkPLYReader()
reader.SetFileName(fname_ply)
reader_vtk = vtkPolyDataReader()
reader_vtk.SetFileName(fname_vtk)
ren = vtkRenderer()
wren = vtkRenderWindow()
iren = vtkRenderWindowInteractor()
wren.AddRenderer(ren)
iren.SetRenderWindow(wren)
mapper = vtkPolyDataMapper()
mapper.SetInputConnection(reader.GetOutputPort())
mapper_vtk = vtkPolyDataMapper()
mapper_vtk.SetInputConnection(reader_vtk.GetOutputPort())
actor = vtkActor()
actor.SetMapper(mapper)
actor_vtk = vtkActor()
# actor_vtk.SetMapper(mapper_vtk)
ren.AddActor(actor_vtk)
ren.AddActor(actor)
transform = vtkTransform()
matrix_vtk =vtkMatrix4x4()
matrix_vtk.DeepCopy((1, 0, 0, 0, 0, 1, 0, 1, 0,0,1,0,0,0,0,1))
transform.SetMatrix(matrix_vtk)
transform_filter = vtkTransformPolyDataFilter()
transform_filter.SetTransform(transform)
dataset_mapper = vtk.vtkDataSetMapper()
dataset_mapper.SetInputConnection(transform_filter.GetOutputPort())
actor.SetMapper(dataset_mapper)
actor.SetMapper(datasetmapper)
iren.Initialize()
iren.Start()
Any suggestions?
You didn't connect any input to filter, something like transform_filter.SetInputData(reader.GetOutputPort()).
It would be helpful if you could write what you expect.
your process is right, however, your output is not correctly defined. you can run it line by line and follow your output.
Related
I'm using the manim module in Python to display some decision trees. Fist I want to show Tree_1 as it is in the code below. Then I want it to scale it down and shift it to the left. Next I want Tree_2 to appear where Tree_1 is and them move to the upper right quadrant of the screen. Also the PURE_RED lines should move from tilted (as in Tree_1) to straight (as in Tree_2 in the code below). The same should then happen with Tree_3 just in the bottom right quadrant.
Now I could do it by figuring out all the points and then hardcode it. But I wanted to ask if there is a nicer way. Maybe one where I could define points in a local coordinate system and then I can just scale and move the whole tree.
Also I'm sorry if its is considered common knowledge, but I'm super new to manim.
from manim import *
class Tree_1(Scene):
def construct(self):
line_1 = Line([0,3,0], [-6,0,0])
line_2 = Line([0,3,0], [0,0,0])
line_3 = Line([0,3,0], [6,0,0])
self.play(
Create(line_1),
Create(line_2),
Create(line_3),
)
line_1l = Line([-6, 0, 0], [-7,-3, 0]).set_color(PURE_GREEN)
line_1r = Line([-6, 0, 0], [-5,-3, 0]).set_color(PURE_RED)
line_2l = Line([ 0, 0, 0], [-1,-3, 0]).set_color(PURE_GREEN)
line_2r = Line([ 0, 0, 0], [ 1,-3, 0]).set_color(PURE_RED)
line_3l = Line([ 6, 0, 0], [ 5,-3, 0]).set_color(PURE_GREEN)
line_3r = Line([ 6, 0, 0], [ 7,-3, 0]).set_color(PURE_RED)
self.play(
Create(line_1l),
Create(line_1r),
Create(line_2l),
Create(line_2r),
Create(line_3l),
Create(line_3r),
)
class Tree_2(Scene):
def construct(self):
line_1 = Line([0,3,0], [-6,0,0])
line_2 = Line([0,3,0], [0,0,0])
line_3 = Line([0,3,0], [6,0,0])
self.play(
Create(line_1),
Create(line_2),
Create(line_3),
)
line_4 = Line([-6, 0, 0], [-6,-3, 0]).set_color(PURE_RED)
line_5 = Line([ 0, 0, 0], [-0,-3, 0]).set_color(PURE_RED)
line_6 = Line([ 6, 0, 0], [ 6,-3, 0]).set_color(PURE_RED)
self.play(
Create(line_4),
Create(line_5),
Create(line_6),
)
class Tree_3(Scene):
def construct(self):
line_1 = Line([0,3,0], [-6,0,0])
line_2 = Line([0,3,0], [0,0,0])
line_3 = Line([0,3,0], [6,0,0])
self.play(
Create(line_1),
Create(line_2),
Create(line_3),
)
line_4 = Line([-6, 0, 0], [-6,-3, 0]).set_color(PURE_GREEN)
line_5 = Line([ 0, 0, 0], [-0,-3, 0]).set_color(PURE_GREEN)
line_6 = Line([ 6, 0, 0], [ 6,-3, 0]).set_color(PURE_GREEN)
self.play(
Create(line_4),
Create(line_5),
Create(line_6),
)
Yes there is, add them to a VGroup, here is the docs.
I have the following code :
def make_override_editable():
for area in bpy.context.screen.areas:
if area.type == "OUTLINER":
ctx = bpy.context.copy()
ctx["area"] = area
with bpy.context.temp_override(area=area):
print(bpy.context.area.type)
bpy.ops.outliner.liboverride_operation(
type="OVERRIDE_LIBRARY_CREATE_HIERARCHY",
selection_set="SELECTED_AND_CONTENT",
)
The following line when is ran through the script :
print(bpy.context.area.type)
outputs OUTLINER
but I still get the error that I have the incorrect context :
RuntimeError: Operator bpy.ops.outliner.liboverride_operation.poll() failed, context is incorrect
which normally works in blender text editor with 3 lines :
bpy.context.area.type = 'OUTLINER'
bpy.ops.outliner.liboverride_operation(type="OVERRIDE_LIBRARY_CREATE_HIERARCHY",selection_set="SELECTED_AND_CONTENT")
bpy.context.area.type = 'TEXT_EDITOR'
I'm using python in a much more complex script with QT.
any suggestions ?
I'm trying to make a linked skeleton (Armature) editable so I can change it's pose.
I've also searched for a low level function that I can use, but did not had any success.
or perhaps is there another method to LINK and animation to a LINKED Armature ?
I've tried this :
def make_override_editable():
for area in bpy.context.screen.areas:
if area.type == "OUTLINER":
ctx = bpy.context.copy()
ctx["area"] = area
with bpy.context.temp_override(area=area):
print(bpy.context.area.type)
bpy.ops.outliner.liboverride_operation(
type="OVERRIDE_LIBRARY_CREATE_HIERARCHY",
selection_set="SELECTED_AND_CONTENT",
)
And was expecting to have this
bpy.ops.outliner.liboverride_operation(type="OVERRIDE_LIBRARY_CREATE_HIERARCHY",selection_set="SELECTED_AND_CONTENT")
this works even if the Armature is linked.
no need to use operators.
# Reset the Armature to the default POSE.
for n in bpy.context.object.pose.bones:
n.location = (0, 0, 0)
n.rotation_quaternion = (1, 0, 0, 0)
n.rotation_axis_angle = (0, 0, 1, 0)
n.rotation_euler = (0, 0, 0)
n.scale = (1, 1, 1)
I have this code
joint_name = cmds.ls(sl=1)[0]
circle_name = cmds.circle(name = joint_name + "_CTL", nr=(1, 0, 0) )
group_name = cmds.group(name = joint_name + "_OFFSET")
cmds.select(joint_name, group_name)temp_constraint = cmds.parentConstraint()
cmds.delete(temp_constraint)
cmds.select(circle_name, joint_name)
cmds.pointConstraint()
cmds.orientConstraint()
When you select a joint and run this code you will get a circle that will control that joint. While going down the hierarchy you have to select that joint and then run the code.
How would I be able to have all the joints to have circles controlling them without having to go through the outliner selection a joint?
run this on your chain of joint :
for x, joint_name in enumerate(cmds.ls(sl=1, dag=True, type='joint')):
circle_name = cmds.circle(name = '{}_CTL{:02d}'.format(joint_name,x), nr=(1, 0, 0) )
group_name = cmds.group(name = '{}_OFFSET{:02d}'.format(joint_name,x))
cmds.select(joint_name, group_name)
temp_constraint = cmds.parentConstraint()
cmds.delete(temp_constraint)
cmds.select(circle_name, joint_name)
cmds.pointConstraint()
cmds.orientConstraint()
Note that instead of use select, you could feed pointConstraint :
cmds.pointConstraint(circle_name, joint_name, n='something')
I am trying to make contour plot from unstructured grid. My code does not work and I could not find an example to follow. I did not include the input file, hoping that a sample unstructured grid is easy to find. I managed to make work on Paraview by converting cell data to point data and then contouring "p" scalar. But I cannot do it with vtk. What's wrong in my code?
from vtk import *
file_name = "results.vtk"
reader = vtkUnstructuredGridReader()
reader.SetFileName(file_name)
reader.Update()
output = reader.GetOutput()
scalar_range = output.GetScalarRange()
c2p = vtkCellDataToPointData()
c2p.SetInputData(output)
contours = vtkContourGrid()
contours.SetInputData(c2p.GetOutput())
contours.SetValue(0, 0.007009505294263363)
gridmapper = vtkDataSetMapper()
gridmapper.SetInputData(output)
gridmapper.GetInput().GetCellData().SetActiveScalars("p")
gridmapper.SetScalarVisibility(1)
gridmapper.SetScalarRange(scalar_range)
mapper = vtkPolyDataMapper()
#mapper = vtkDataSetMapper()
mapper.SetInputConnection(contours.GetOutputPort())
actor = vtkActor()
actor.SetMapper(mapper)
gridactor = vtkActor()
gridactor.SetMapper(gridmapper)
gridactor.GetProperty().EdgeVisibilityOn()
renderer = vtkRenderer()
renderer.AddActor(actor)
renderer.AddActor(gridactor)
#renderer.SetBackground(1, 1, 1) # Set background to white
renderer_window = vtkRenderWindow()
renderer_window.AddRenderer(renderer)
interactor = vtkRenderWindowInteractor()
interactor.SetRenderWindow(renderer_window)
interactor.Initialize()
interactor.Start()
I'm trying to display further images (ct-scan) using numpy/vtk as describe in this sample code (http://www.vtk.org/Wiki/VTK/Examples/Python/vtkWithNumpy) but I don't get it and don't know why.
If someone could help me it would be kind.
Here's my code :
import vtk
import numpy as np
import os
import cv, cv2
import matplotlib.pyplot as plt
import PIL
import Image
DEBUG =True
directory="splitted_mri/"
w = 226
h = 186
d = 27
stack = np.zeros((w,d,h))
k=-1 #add the next picture in a differente level of depth/z-positions
for file in os.listdir(directory):
k+=1
img = directory + file
im = Image.open(img)
temp = np.asarray(im, dtype=int)
stack[:,k,:]= temp
print stack.shape
#~ plt.imshow(test)
#~ plt.show()
print type(stack[10,10,15])
res = np.amax(stack)
res1 = np.amin(stack)
print res, type(res)
print res1, type(res1)
#~ for (x,y,z), value in np.ndenumerate(stack):
#~ stack[x,y,z]=np.require(stack[x,y,z],dtype=np.int16)
#~ print type(stack[x,y,z])
stack = np.require(stack,dtype=np.uint16)
print stack.dtype
if DEBUG : print stack.shape
dataImporter = vtk.vtkImageImport()
data_string = stack.tostring()
dataImporter.CopyImportVoidPointer(data_string, len(data_string))
dataImporter.SetDataScalarTypeToUnsignedChar()
dataImporter.SetNumberOfScalarComponents(1)
dataImporter.SetDataExtent(0, w-1, 0, 1, 0, h-1)
dataImporter.SetWholeExtent(0, w-1, 0, 1, 0, h-1)
essai = raw_input()
alphaChannelFunc = vtk.vtkPiecewiseFunction()
colorFunc = vtk.vtkColorTransferFunction()
for i in range (0,255):
alphaChannelFunc.AddPoint(i, 0.9)
colorFunc.AddRGBPoint(i,i,i,i)
volumeProperty = vtk.vtkVolumeProperty()
volumeProperty.SetColor(colorFunc)
#volumeProperty.ShadeOn()
volumeProperty.SetScalarOpacity(alphaChannelFunc)
# This class describes how the volume is rendered (through ray tracing).
compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
# We can finally create our volume. We also have to specify the data for it, as well as how the data will be rendered.
volumeMapper = vtk.vtkVolumeRayCastMapper()
volumeMapper.SetVolumeRayCastFunction(compositeFunction)
volumeMapper.SetInputConnection(dataImporter.GetOutputPort())
# The class vtkVolume is used to pair the preaviusly declared volume as well as the properties to be used when rendering that volume.
volume = vtk.vtkVolume()
volume.SetMapper(volumeMapper)
volume.SetProperty(volumeProperty)
# With almost everything else ready, its time to initialize the renderer and window, as well as creating a method for exiting the application
renderer = vtk.vtkRenderer()
renderWin = vtk.vtkRenderWindow()
renderWin.AddRenderer(renderer)
renderInteractor = vtk.vtkRenderWindowInteractor()
renderInteractor.SetRenderWindow(renderWin)
# We add the volume to the renderer ...
renderer.AddVolume(volume)
# ... set background color to white ...
renderer.SetBackground(1, 1, 1)
# ... and set window size.
renderWin.SetSize(400, 400)
# A simple function to be called when the user decides to quit the application.
def exitCheck(obj, event):
if obj.GetEventPending() != 0:
obj.SetAbortRender(1)
# Tell the application to use the function as an exit check.
renderWin.AddObserver("AbortCheckEvent", exitCheck)
#to quit, press q
renderInteractor.Initialize()
# Because nothing will be rendered without any input, we order the first render manually before control is handed over to the main-loop.
renderWin.Render()
renderInteractor.Start()
I finally find out what was wrong
here's my new code
import vtk
import numpy as np
import os
import matplotlib.pyplot as plt
import PIL
import Image
DEBUG =False
directory="splitted_mri/"
l = []
k=0 #add the next picture in a differente level of depth/z-positions
for file in os.listdir(directory):
img = directory + file
if DEBUG : print img
l.append(img)
# the os.listdir function do not give the files in the right order
#so we need to sort them
l=sorted(l)
temp = Image.open(l[0])
h, w = temp.size
d = len(l)*5 #with our sample each images will be displayed 5times to get a better view
if DEBUG : print 'width, height, depth : ',w,h,d
stack = np.zeros((w,d,h),dtype=np.uint8)
for i in l:
im = Image.open(i)
temp = np.asarray(im, dtype=int)
for i in range(5):
stack[:,k+i,:]= temp
k+=5
#~ stack[:,k,:]= temp
#~ k+=1
if DEBUG :
res = np.amax(stack)
print 'max value',res
res1 = np.amin(stack)
print 'min value',res1
#convert the stack in the right dtype
stack = np.require(stack,dtype=np.uint8)
if DEBUG :#check if the image have not been modified
test = stack [:,0,:]
plt.imshow(test,cmap='gray')
plt.show()
if DEBUG : print 'stack shape & dtype' ,stack.shape,',',stack.dtype
dataImporter = vtk.vtkImageImport()
data_string = stack.tostring()
dataImporter.CopyImportVoidPointer(data_string, len(data_string))
dataImporter.SetDataScalarTypeToUnsignedChar()
dataImporter.SetNumberOfScalarComponents(1)
#vtk uses an array in the order : height, depth, width which is
#different of numpy (w,h,d)
w, d, h = stack.shape
dataImporter.SetDataExtent(0, h-1, 0, d-1, 0, w-1)
dataImporter.SetWholeExtent(0, h-1, 0, d-1, 0, w-1)
alphaChannelFunc = vtk.vtkPiecewiseFunction()
colorFunc = vtk.vtkColorTransferFunction()
for i in range(256):
alphaChannelFunc.AddPoint(i, 0.2)
colorFunc.AddRGBPoint(i,i/255.0,i/255.0,i/255.0)
# for our test sample, we set the black opacity to 0 (transparent) so as
#to see the sample
alphaChannelFunc.AddPoint(0, 0.0)
colorFunc.AddRGBPoint(0,0,0,0)
volumeProperty = vtk.vtkVolumeProperty()
volumeProperty.SetColor(colorFunc)
#volumeProperty.ShadeOn()
volumeProperty.SetScalarOpacity(alphaChannelFunc)
# This class describes how the volume is rendered (through ray tracing).
compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
# We can finally create our volume. We also have to specify the data for
# it, as well as how the data will be rendered.
volumeMapper = vtk.vtkVolumeRayCastMapper()
# function to reduce the spacing between each image
volumeMapper.SetMaximumImageSampleDistance(0.01)
volumeMapper.SetVolumeRayCastFunction(compositeFunction)
volumeMapper.SetInputConnection(dataImporter.GetOutputPort())
# The class vtkVolume is used to pair the preaviusly declared volume as
#well as the properties to be used when rendering that volume.
volume = vtk.vtkVolume()
volume.SetMapper(volumeMapper)
volume.SetProperty(volumeProperty)
# With almost everything else ready, its time to initialize the renderer and window,
# as well as creating a method for exiting the application
renderer = vtk.vtkRenderer()
renderWin = vtk.vtkRenderWindow()
renderWin.AddRenderer(renderer)
renderInteractor = vtk.vtkRenderWindowInteractor()
renderInteractor.SetRenderWindow(renderWin)
# We add the volume to the renderer ...
renderer.AddVolume(volume)
# ... set background color to white ...
renderer.SetBackground(1, 1, 1)
# ... and set window size.
renderWin.SetSize(550, 550)
renderWin.SetMultiSamples(4)
# A simple function to be called when the user decides to quit the application.
def exitCheck(obj, event):
if obj.GetEventPending() != 0:
obj.SetAbortRender(1)
# Tell the application to use the function as an exit check.
renderWin.AddObserver("AbortCheckEvent", exitCheck)
#to auit, press q
renderInteractor.Initialize()
# Because nothing will be rendered without any input, we order the first
# render manually before control is handed over to the main-loop.
renderWin.Render()
renderInteractor.Start()
If you are ok with a solution not using VTK, you could use Matplotlib imshow and interactive navigation with keys.
This tutorial shows how:
https://www.datacamp.com/community/tutorials/matplotlib-3d-volumetric-data
https://github.com/jni/mpl-volume-viewer
and here an implementation for viewing RTdose files:
https://github.com/pydicom/contrib-pydicom/pull/19
See also:
https://github.com/napari/napari