update live pointcloud data in vtk python - python

I have a basic question as i am new to VTK. I have to draw live point cloud data in VTK. I have modified the code given in How to display point cloud in vtk in different colors?.
The pointcloud should update for number of times given in iterations(here 30). I have used Initialize() to avoid blocking control flow as mentioned in some solutions, in every iteration the point cloud is updated, and render() is called so that it can update the window with new data.
I cannot figure out why this is blocking the control flow, and the data is not updated. Only once the iterations are over, after renderWindowInteractor.Start() is called, the interaction is enabled.
import vtk
from numpy import random
class VtkPointCloud:
def __init__(self, zMin=-10.0, zMax=10.0, maxNumPoints=1e6):
self.maxNumPoints = maxNumPoints
self.vtkPolyData = vtk.vtkPolyData()
self.clearPoints()
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputData(self.vtkPolyData)
mapper.SetColorModeToDefault()
mapper.SetScalarRange(zMin, zMax)
mapper.SetScalarVisibility(1)
self.vtkActor = vtk.vtkActor()
self.vtkActor.SetMapper(mapper)
def addPoint(self, point):
if self.vtkPoints.GetNumberOfPoints() < self.maxNumPoints:
pointId = self.vtkPoints.InsertNextPoint(point[:])
self.vtkDepth.InsertNextValue(point[2])
self.vtkCells.InsertNextCell(1)
self.vtkCells.InsertCellPoint(pointId)
else:
r = random.randint(0, self.maxNumPoints)
self.vtkPoints.SetPoint(r, point[:])
self.vtkCells.Modified()
self.vtkPoints.Modified()
self.vtkDepth.Modified()
def clearPoints(self):
self.vtkPoints = vtk.vtkPoints()
self.vtkCells = vtk.vtkCellArray()
self.vtkDepth = vtk.vtkDoubleArray()
self.vtkDepth.SetName('DepthArray')
self.vtkPolyData.SetPoints(self.vtkPoints)
self.vtkPolyData.SetVerts(self.vtkCells)
self.vtkPolyData.GetPointData().SetScalars(self.vtkDepth)
self.vtkPolyData.GetPointData().SetActiveScalars('DepthArray')
def func(pointCloud):
# Renderer
renderer = vtk.vtkRenderer()
renderer.AddActor(pointCloud.vtkActor)
renderer.SetBackground(.2, .3, .4)
renderer.ResetCamera()
# Render Window
renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)
# Interactor
renderWindowInteractor = vtk.vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
# Begin Interaction
renderWindow.Render()
renderWindowInteractor.Initialize()
return renderWindow,renderWindowInteractor
def main(iter):
while iter > 0:
pointCloud = VtkPointCloud()
for k in xrange(10000):
point = 20*(random.rand(3)-0.5)
pointCloud.addPoint(point)
pointCloud.addPoint([0,0,0])
pointCloud.addPoint([0,0,0])
pointCloud.addPoint([0,0,0])
pointCloud.addPoint([0,0,0])
if iter == 30:
renderWindow,renderWindowInteractor = func(pointCloud)
else:
#pointCloud.vtkPolyData.Modified()
renderWindow.Render()
iter -= 1
renderWindowInteractor.Start()
main(30)

So you want to do an animation.
A better practice is to follow this sample explaining how to do use a TimerEvent.
Here is what it would look like with your code:
import vtk
from numpy import random
class VtkPointCloud:
def __init__(self, zMin=-10.0, zMax=10.0, maxNumPoints=1e6):
self.maxNumPoints = maxNumPoints
self.vtkPolyData = vtk.vtkPolyData()
self.clearPoints()
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputData(self.vtkPolyData)
mapper.SetColorModeToDefault()
mapper.SetScalarRange(zMin, zMax)
mapper.SetScalarVisibility(1)
self.vtkActor = vtk.vtkActor()
self.vtkActor.SetMapper(mapper)
def addPoint(self, point):
if self.vtkPoints.GetNumberOfPoints() < self.maxNumPoints:
pointId = self.vtkPoints.InsertNextPoint(point[:])
self.vtkDepth.InsertNextValue(point[2])
self.vtkCells.InsertNextCell(1)
self.vtkCells.InsertCellPoint(pointId)
else:
r = random.randint(0, self.maxNumPoints)
self.vtkPoints.SetPoint(r, point[:])
self.vtkCells.Modified()
self.vtkPoints.Modified()
self.vtkDepth.Modified()
def clearPoints(self):
self.vtkPoints = vtk.vtkPoints()
self.vtkCells = vtk.vtkCellArray()
self.vtkDepth = vtk.vtkDoubleArray()
self.vtkDepth.SetName('DepthArray')
self.vtkPolyData.SetPoints(self.vtkPoints)
self.vtkPolyData.SetVerts(self.vtkCells)
self.vtkPolyData.GetPointData().SetScalars(self.vtkDepth)
self.vtkPolyData.GetPointData().SetActiveScalars('DepthArray')
class AddPointCloudTimerCallback():
def __init__(self, renderer, iterations):
self.iterations = iterations
self.renderer = renderer
def execute(self, iren, event):
if self.iterations == 0:
iren.DestroyTimer(self.timerId)
pointCloud = VtkPointCloud()
self.renderer.AddActor(pointCloud.vtkActor)
pointCloud.clearPoints()
for k in xrange(10000):
point = 20*(random.rand(3)-0.5)
pointCloud.addPoint(point)
pointCloud.addPoint([0,0,0])
pointCloud.addPoint([0,0,0])
pointCloud.addPoint([0,0,0])
pointCloud.addPoint([0,0,0])
iren.GetRenderWindow().Render()
if self.iterations == 30:
self.renderer.ResetCamera()
self.iterations -= 1
if __name__ == "__main__":
# Renderer
renderer = vtk.vtkRenderer()
renderer.SetBackground(.2, .3, .4)
renderer.ResetCamera()
# Render Window
renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)
# Interactor
renderWindowInteractor = vtk.vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
renderWindowInteractor.Initialize()
# Initialize a timer for the animation
addPointCloudTimerCallback = AddPointCloudTimerCallback(renderer, 30)
renderWindowInteractor.AddObserver('TimerEvent', addPointCloudTimerCallback.execute)
timerId = renderWindowInteractor.CreateRepeatingTimer(10)
addPointCloudTimerCallback.timerId = timerId
# Begin Interaction
renderWindow.Render()
renderWindowInteractor.Start()
Note that I renamed iter to iterations because iter is a reserved name in Python.

Related

Maya python API: set Vertex Colors

How can I set vertex colors with the Maya python api, given a number of uv shells? So for each shell within a single mesh assign a random vertex color. At the bottom I have the previous code which is too slow in more dense meshes.
def setColors():
shells = getUvShelList( cmds.ls(sl=1)[0] )
print ( shells )
"""
#3 similar objects combined into one
{0: ['pCube4.map[0]', 'pCube4.map[1]', 'pCube4.map[2]', 'pCube4.map[3]', 'pCube4.map[4]', 'pCube4.map[5]', 'pCube4.map[6]', 'pCube4.map[7]', 'pCube4.map[8]', 'pCube4.map[9]', 'pCube4.map[10]', 'pCube4.map[11]', 'pCube4.map[12]', 'pCube4.map[13]'],
1: ['pCube4.map[14]', 'pCube4.map[15]', 'pCube4.map[16]', 'pCube4.map[17]', 'pCube4.map[18]', 'pCube4.map[19]', 'pCube4.map[20]', 'pCube4.map[21]', 'pCube4.map[22]', 'pCube4.map[23]', 'pCube4.map[24]', 'pCube4.map[25]', 'pCube4.map[26]', 'pCube4.map[27]'],
2: ['pCube4.map[28]', 'pCube4.map[29]', 'pCube4.map[30]', 'pCube4.map[31]', 'pCube4.map[32]', 'pCube4.map[33]', 'pCube4.map[34]', 'pCube4.map[35]', 'pCube4.map[36]', 'pCube4.map[37]', 'pCube4.map[38]', 'pCube4.map[39]', 'pCube4.map[40]', 'pCube4.map[41]']}
"""
selList2 = om2.MGlobal.getActiveSelectionList()
dagPath = selList2.getDagPath(0)
selMesh = om2.MFnMesh(dagPath)
vertList = list(set(selMesh.getVertices()[1]))
lenVertList = len(vertList)
for shell in shells:
selection_shell = shells.get(shell)
r = [random.random() for i in range(3)]
tempColor = om2.MColor([r[0],r[1],r[2]])
vertexColorList = om2.MColorArray(lenVertList, tempColor)
selMesh.setVertexColors(vertexColorList, vertList)
setColors()
My previous code(too slow):
for shell in chunk:
selection_shell = shells.get(shell)
cmds.select(selection_shell)
facesSel = cmds.polyListComponentConversion(fromUV=True, toFace=True)
cmds.select(facesSel)
r = [random.random() for i in range(3)]
cmds.polyColorPerVertex(facesSel,rgb=(r[0], r[1], r[2]), cdo=1 )
cmds.select(deselect=1)
Here's what I ended up doing, creating a random color per element within a mesh. Similar to element ID in 3ds max.
To answer my own question, I had to convert the UV indices to Vertex indices per shell.
import maya.cmds as cmds
import maya.api.OpenMaya as om
from itertools import zip_longest
from itertools import chain
import random
import colorsys
import time
import maya.mel as mel
class colorVariationShell():
def __init__(self):
self.setSelection()
self.setColors()
def setSelection(self):
# Get the currently selected mesh.
self.mSelList = om.MGlobal.getActiveSelectionList()
self.path = self.mSelList.getDagPath(0)
self.fnMesh = om.MFnMesh(self.path)
def get_progress_bar(self,status_text, max_value):
try:
progress_bar = mel.eval("$tmp = $gMainProgressBar")
except RuntimeError:
progress_bar = None
if progress_bar:
cmds.progressBar(
progress_bar,
edit=True,
beginProgress=True,
isInterruptable=False,
status=status_text,
maxValue=max_value
)
return progress_bar
def getUvShellsOnObj(self):
#Get UV Sets
uvSets = self.fnMesh.getUVSetNames()
for uvset in uvSets:
uvShellIds = self.fnMesh.getUvShellsIds(uvset)[1]
polyVertices = self.fnMesh.getVertices()
polyUvs = self.fnMesh.getAssignedUVs(uvset)
shells = {}
vertexGroup = []
list_zip = zip(polyVertices[1], polyUvs[1])
zipped_list = list(list_zip)
main_progress_bar_3 = self.get_progress_bar("Getting UV Shells IDS", len(zipped_list))
for i, n in enumerate(uvShellIds):
if n in shells:
shells[n].append( i )
else:
shells[n] = [ ( i ) ]
cmds.progressBar(main_progress_bar_3, edit=True, step=1)
cmds.progressBar(main_progress_bar_3, edit=True, endProgress=True)
vertsID = []
uvsID = []
main_progress_bar = self.get_progress_bar("Gathering UV and Vertex Info", len(zipped_list))
for zipItem in zipped_list:
vertsID.append(zipItem[0])
uvsID.append(zipItem[1])
cmds.progressBar(main_progress_bar, edit=True, step=1)
cmds.progressBar(main_progress_bar, edit=True, endProgress=True)
vertex_id_from_shell = {}
main_progress_bar_2 = self.get_progress_bar("Passing UV and Vertex data", len(shells))
for shell in shells:
selection_shell = shells.get(shell)
for idx, item in enumerate(selection_shell):
if item in uvsID:
uv_index = uvsID.index(item)
vertex_ids = vertsID[uv_index]
# if the list does not exist, create it
if shell not in vertex_id_from_shell:
vertex_id_from_shell[shell] = []
# append to list
vertex_id_from_shell[shell].append(vertex_ids)
cmds.progressBar(main_progress_bar_2, edit=True, step=1)
cmds.progressBar(main_progress_bar_2, edit=True, endProgress=True)
return shells, vertex_id_from_shell
def setColors(self):
shells, target_vertex_id = self.getUvShellsOnObj()
#ammount of different colors
var = 3
vertexData = {key : [] for key in range(var)}
pool = []
for val in target_vertex_id.values():
if not pool:
pool = list(range(var))
random.shuffle(pool)
vertexData[pool.pop()].extend(val)
main_progress_bar = self.get_progress_bar("Applying Vertex Colors", len(vertexData))
for vertex_idx, selection_vertex in vertexData.items():
vertexIds = selection_vertex
lenVertList = len(vertexIds)
sat_random = random.uniform(0.5, 1)
increment = 1/len(vertexData)
color_hsv = (vertex_idx*increment, sat_random, vertex_idx*increment+1/len(vertexData))
rgb_color = colorsys.hsv_to_rgb(color_hsv[0],color_hsv[1],color_hsv[2])
final_color = om.MColor(rgb_color)
vertexColorList = om.MColorArray(lenVertList, final_color)
#apply the color
self.fnMesh.setVertexColors(vertexColorList, vertexIds)
cmds.progressBar(main_progress_bar, edit=True, step=1)
cmds.polyOptions(colorShadedDisplay=1)
cmds.progressBar(main_progress_bar, edit=True, endProgress=True)
start_time = time.time()
colorVariationShell()

vtk.vtkOBJExporter not exporting entire rendering

I am trying to export a VTK rendering as an OBJ file to be viewed in Meshlab. Everything appears normal until I open the .obj file in Meshlab, where only the spheres have been exported and not any of the tubes I have connecting the spheres. I have tried exporting the rendering in different file types but only the spheres are exported for some reason. Could it be because the tube filter doesn't actually create a 3D object? Looking for any solutions to this problem! The writer is at the bottom of the code. Thanks
np={}
for n in G.nodes():
np[n]=node_pos[n]
nodePoints = vtk.vtkPoints()
i=0
for (x,y,z) in np.values():
nodePoints.InsertPoint(i, x, y, z)
i=i+1
# Create a polydata to be glyphed.
inputData = vtk.vtkPolyData()
inputData.SetPoints(nodePoints)
# Use sphere as glyph source.
balls = vtk.vtkSphereSource()
balls.SetRadius(.1)
balls.SetPhiResolution(20)
balls.SetThetaResolution(20)
glyphPoints = vtk.vtkGlyph3D()
glyphPoints.SetInputData(inputData)
glyphPoints.SetSourceData(balls.GetOutput())
glyphMapper = vtk.vtkPolyDataMapper()
glyphMapper.SetInputData(glyphPoints.GetOutput())
glyph = vtk.vtkActor()
glyph.SetMapper(glyphMapper)
glyph.GetProperty().SetDiffuseColor(plum)
glyph.GetProperty().SetSpecular(.3)
glyph.GetProperty().SetSpecularPower(30)
# Generate the polyline for the spline.
points = vtk.vtkPoints()
edgeData = vtk.vtkPolyData()
# Edges
lines = vtk.vtkCellArray()
i=0
for e in G.edges:
u=e[0]
v=e[1]
lines.InsertNextCell(2)
for n in (u,v):
(x,y,z)=node_pos[n]
points.InsertPoint(i, x, y, z)
lines.InsertCellPoint(i)
i=i+1
edgeData.SetPoints(points)
edgeData.SetLines(lines)
Tubes = vtk.vtkTubeFilter()
Tubes.SetNumberOfSides(16)
Tubes.SetInputData(edgeData)
Tubes.SetRadius(0.05) # edge RADIUS
profileMapper = vtk.vtkPolyDataMapper()
profileMapper.SetInputData(Tubes.GetOutput())
balls.Update()
glyphPoints.Update()
Tubes.Update()
profile = vtk.vtkActor()
profile.SetMapper(profileMapper)
profile.GetProperty().SetDiffuseColor(banana)
profile.GetProperty().SetSpecular(.3)
profile.GetProperty().SetSpecularPower(30)
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
ren.AddActor(profile)
ren.AddActor(glyph)
renWin.SetSize(1000, 1000)
iren.Initialize()
renWin.Render()
iren.Start()
writer = vtk.vtkOBJExporter()
writer.SetFilePrefix('test')
writer.SetInput(renWin)
writer.Write()

Random lag spikes with pygame parallax background

I'm trying to make a platformer with a parallax background. I managed the code and also made sure to add .convert.
It is running pretty well for the most part, but every now and then there are periodic lag spikes.
# Imports
from vars import *
# Background class
class Background(pygame.sprite.Sprite):
def __init__(self, image, x):
super(Background, self).__init__()
self.surf = pygame.transform.smoothscale(pygame.image.load(image).convert_alpha(), (s_width, s_height))
self.rect = self.surf.get_rect(center=(x, s_height/2))
# Cave Background
class BgSurface(pygame.sprite.Sprite):
def __init__(self):
super(BgSurface, self).__init__()
self.surf = pygame.Surface((s_width, s_height))
self.rect = self.surf.get_rect(center=(s_width/2, s_height/2))
self.surf.fill((144, 156, 156))
# Background stuff
cave_air = BgSurface()
l1 = Background("layer1.png", s_width/2)
l2 = Background("layer2.png", s_width/2)
layer_list = [pygame.sprite.Group(l1), pygame.sprite.Group(l2)]
head_list = [pygame.sprite.Group(l1), pygame.sprite.Group(l2)]
bg_img_list = ["layer1.png", "layer2.png"]
def parallax(s_xdir, s_ydir):
for i in range(len(layer_list)):
ind = 0
for x in layer_list[i]:
ind += 1
x.rect.move_ip(s_xdir * vel_list[i], s_ydir * vel_list[2])
# Adding to left
if x.rect.left > 0 and ind == len(layer_list[i]) and not x.rect.centerx > s_width:
new_bg = Background(bg_img_list[i], x.rect.centerx - s_width)
new_bg.rect.centery = x.rect.centery
layer_list[i].add(new_bg)
# Memory optimization
if x.rect.left > s_width or x.rect.right < 1:
if x in head_list[i]:
x.kill()
for a in layer_list[i]:
head_list[i] = pygame.sprite.Group(a)
x.kill()
# Adding to right side
for a in head_list[i]:
if a.rect.right < s_width:
new_head = Background(bg_img_list[i], a.rect.centerx + s_width)
new_head.rect.centery = a.rect.centery
layer_list[i].add(new_head)
head_list[i] = pygame.sprite.Group(new_head)
# Experimental deletion of common centers
for p in layer_list[i]:
for q in layer_list[i]:
if p.rect.centerx == q.rect.centerx and p != q:
p.kill()
(Stuff like s_width and s_height are defined in the vars module which I import)
I moved the last killing loop out of the function and checked how many sprites are there in the background every second, but it returns that there are no unnecessary sprites being added during the lag spikes.
The spikes don't even coincide with the moments in which a new surface is added to fill the screen. Do any of you know why this is happening?
Do not load the images in the application loop. Loading an image is very time consuming because the image file has to be read and interpreted. Load the images once at the begin of the application:
# Background class
class Background(pygame.sprite.Sprite):
def __init__(self, image, x):
super(Background, self).__init__()
self.surf = pygame.transform.smoothscale(image, (s_width, s_height))
self.rect = self.surf.get_rect(center=(x, s_height/2))
bg_img_filelist = ["layer1.png", "layer2.png"]
bg_img_list = [pygame.image.load(f).convert_alpha() for f in bg_img_filelist ]
l1 = Background(bg_img_list[0], s_width/2)
l2 = Background(bg_img_list[1], s_width/2)

How to save Intel Realsense images in list (pyrealsense2)

I'm trying to save both, the depth and color images of the Intel Realsense D435i camera in a list of 300 images. Then I will use multiprocessing to save this chunk of 300 images onto my disk. But every time I try, the program successfully appends 15 images in the list and then I get this error:
Frame didn't arrived within 5000
I made sure I had the 64 bit version on python 3.6 installed and the camera streams perfectly well when I do not try to save the images in a list. The real-sense viewer works great too. I also tried with different resolutions and frame rates but it doesn't seem to work either. What is interesting is if I only save the color images, I will not get the same error, instead I will get the same color image over and over in the list.
if __name__ == '__main__':
pipeline = rs.pipeline()
config = rs.config()
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
config.enable_stream(rs.stream.color, 1280, 720, rs.format.bgr8, 30)
profile = pipeline.start(config)
depth_sensor = profile.get_device().first_depth_sensor()
depth_sensor.set_option(
rs.option.visual_preset, 3
) # Set high accuracy for depth sensor
depth_scale = depth_sensor.get_depth_scale()
align_to = rs.stream.color
align = rs.align(align_to)
# Init variables
im_count = 0
image_chunk = []
image_chunk2 = []
# sentinel = True
try:
while True:
# Wait for a coherent pair of frames: depth and color
frames = pipeline.wait_for_frames()
aligned_frames = align.process(frames)
aligned_depth_frame = aligned_frames.get_depth_frame()
color_frame = aligned_frames.get_color_frame()
if not aligned_depth_frame or not color_frame:
print("problem here")
raise RuntimeError("Could not acquire depth or color frames.")
depth_image = np.asanyarray(aligned_depth_frame.get_data())
color_image = np.asanyarray(color_frame.get_data())
image_chunk.append(color_image)
image_chunk2.append(depth_image)
except Exception as e:
print(e)
finally:
# Stop streaming
pipeline.stop()
I simply need it to save 300 images in a row, that's all, so I am quite troubled as to what is causing this issue.
Holding onto the frame locks the memory, and eventually it hits a limit, which prevents acquiring more images. Even though you are creating an image, the data is still from the frame. You need to clone the image after you create it to release the link to the frame's memory.
depth_image = np.asanyarray(aligned_depth_frame.get_data())
color_image = np.asanyarray(color_frame.get_data())
depth_image = depth_image.copy()
color_image = color_image.copy()
image_chunk.append(color_image)
image_chunk2.append(depth_image)
Read more on frames and memory management here:
https://dev.intelrealsense.com/docs/frame-management
I created a wrapper class to extract the various elements out of the frame set that can't be recreated later. It's a bit heavy, but shows some common operations that might be helpful for others:
colorizer = None
align_to_depth = None
align_to_color = None
pointcloud = rs.pointcloud()
class IntelD435ImagePacket:
"""
Class that contains image and associated processing data.
"""
#property
def frame_id(self):
return self._frame_id
#property
def timestamp(self):
return self._timestamp
#property
def image_color(self):
return self._image_color
#property
def image_depth(self):
return self._image_depth
#property
def image_color_aligned(self):
return self._image_color_aligned
#property
def image_depth_aligned(self):
return self._image_depth_aligned
#property
def image_depth_colorized(self):
if not self._image_depth_colorized:
self._image_depth_colorized = cv2.applyColorMap(self.image_depth, cv2.COLORMAP_JET);
return self._image_depth_colorized
#property
def intrinsics(self):
return self._intrinsics
#property
def pointcloud(self):
return self._pointcloud
#property
def pointcloud_texture(self):
return self._pointcloud_texture
def _rs_intrinsics_to_opencv_matrix(self, rs_intrinsics):
fx = rs_intrinsics.fx
fy = rs_intrinsics.fy
cx = rs_intrinsics.ppx
cy = rs_intrinsics.ppy
s = 0 # skew
return np.array([fx, s, cx,
0, fy, cy,
0, 0, 1]).reshape(3, 3)
def __init__(self, frame_set, frame_id=None, timestamp=None, *args, **kwargs):
global colorizer
if not colorizer:
colorizer = rs.colorizer()
colorizer.set_option(rs.option.color_scheme, 0)
global align_to_depth
if not align_to_depth:
align_to_depth = rs.align(rs.stream.depth)
global align_to_color
if not align_to_color:
align_to_color = rs.align(rs.stream.color)
global pointcloud
if not pointcloud:
pointcloud = rs.pointcloud()
# Get intrinsics
profile = frame_set.get_profile()
video_stream_profile = profile.as_video_stream_profile()
rs_intrinsics = video_stream_profile.get_intrinsics()
self._intrinsics = self._rs_intrinsics_to_opencv_matrix(rs_intrinsics)
# Get pointcloud
depth_frame = frame_set.get_depth_frame()
color_frame = frame_set.get_color_frame()
pointcloud.map_to(color_frame)
points = pointcloud.calculate(depth_frame)
vtx = np.asanyarray(points.get_vertices())
points_arr = vtx.view(np.float32).reshape(vtx.shape + (-1,)).copy()
self._pointcloud = points_arr
# Get pointcloud texture mapping
tex = np.asanyarray(points.get_texture_coordinates())
color_map_arr = tex.view(np.float32).reshape(tex.shape + (-1,)).copy()
self._pointcloud_texture = color_map_arr
# Extract color image
color_frame = frame_set.get_color_frame()
self._image_color = np.asanyarray(color_frame.get_data()).copy()
# Extract depth image
depth_frame = frame_set.get_depth_frame()
self._image_depth = np.asanyarray(depth_frame.get_data()).copy()
# Align the color frame to depth frame and extract color image
color_frame_aligned = align_to_depth.process(frame_set).get_color_frame()
self._image_color_aligned = np.asanyarray(color_frame_aligned.get_data()).copy()
# Align the depth frame to color frame and extract depth image
depth_frame_aligned = align_to_color.process(frame_set).get_depth_frame()
self._image_depth_aligned = np.asanyarray(depth_frame_aligned.get_data()).copy()
self._image_depth_colorized = None
if frame_id:
self._frame_id = frame_id
else:
self._frame_id = frame_set.frame_number
if timestamp:
self._timestamp = timestamp
else:
self._timestamp = frame_set.timestamp
self.__dict__.update(kwargs)

VTK can not create its own map vtk.vtkDataSetMapper - Python

There is here such code.
import vtk
file_name = "1.vtk"
reader = vtk.vtkUnstructuredGridReader()
reader.SetFileName(file_name)
reader.Update() # Needed because of GetScalarRange
output = reader.GetOutput()
scalar_range = output.GetScalarRange()
lut = vtk.vtkLookupTable()
mapper = vtk.vtkDataSetMapper()
if vtk.VTK_MAJOR_VERSION <= 5:
mapper.SetInput(output)
else:
mapper.SetInputData(output)
mapper.SetScalarRange(scalar_range )
mapper.SetLookupTable(lut)
print(mapper)
actor = vtk.vtkActor()
actor.SetMapper(mapper)
scalar_bar = vtk.vtkScalarBarActor()
scalar_bar.SetLookupTable(lut)
scalar_bar.SetTitle(u'AS1_X\nARM')
renderer = vtk.vtkRenderer()
renderer.AddActor(actor)
renderer.SetBackground(0.1, 0.2, 0.4)
renderer.AddActor2D(scalar_bar)
render_window = vtk.vtkRenderWindow()
render_window.AddRenderer(renderer)
render_window.SetSize(800, 600)
interactor = vtk.vtkRenderWindowInteractor()
interactor.SetRenderWindow(render_window)
interactor.Initialize()
render_window.Render()
interactor.Start()
He gives this picture
https://i.stack.imgur.com/jgsWP.png
But I do not like such a map, I need to get this card ...
https://i.stack.imgur.com/Nochv.png
I also would like to sign the values in the scalar bar.
In principle, I do all this with the help of Paraview, but there it must be fairly hands on it, I would like to automatically create everything.

Categories

Resources