I'm just new to python and I can't seem to find a solution to my problem, since it seems to be pretty simple. I have a geometry on paraview, I'm saving it as a vtk file and I'm trying to use python to calculate it's volume.
This is the code I'm using:
import vtk
reader = vtk.vtkPolyDataReader()
reader.SetFileName("C:\Users\Pauuu\Google Drive\2016-01\SURF\Sim Vascular\Modelos\apoE183 Day 14 3D\AAA.vtk")
reader.Update()
polydata = reader.GetOutput()
Mass = vtk.vtkMassProperties()
Mass.SetInputConnection(polydata.GetOutput())
Mass.Update()
print "Volume = ", Mass.GetVolume()
print "Surface = ", Mass.GetSurfaceArea()
I think there might be a problem with the way im loding the data, and i get the AttributeError: GetOutput.
Do you know what might be happening or what I'm doing wrong?
Thank you in advance.
Depending on your version of vtk package you may want to test the following syntax if your version <= 5:
Mass.SetInput(polydata.GetOutput());
Otherwise, the actual syntax is:
Mass.SetInputData(polydata.GetOutputPort());
PS: you can check the python-wrapped vtk version by running:
import vtk
print vtk.vtkVersion.GetVTKSourceVersion()
You have assigned reader.GetOutput() in polydata. From polydata, I believe you need to do, polydata.GetOutputPort()
I guess you have VTK 6 , you can provide as input to a filter either the output port of a filter or a vtkDataObject :
Mass.SetInputConnection(reader.GetOutputPort())
Mass.SetInputData(polydata) #that is Mass.SetInputData(reader.GetOutput())
For understanding why these method are not equivalent when updating a pipeline, and for comparison with the previous version, see http://www.vtk.org/Wiki/VTK/VTK_6_Migration/Removal_of_GetProducerPort http://www.vtk.org/Wiki/VTK/VTK_6_Migration/Replacement_of_SetInput
Related
I have been working on this code for a project at work which will (hopefully) take in images from a scanning electron microscope and generate 3D STL files of the structures were imaging. I'm at the stage with the code where I'm trying to generate a 3D structure from a 'coloured in' binary image I've made with some edge detection code I wrote. I came across this post How can i extrude a stl with python that basically does exactly what I need (generating a meshed 3D structure from a binary image). I've tried using/adapting the code in the answer to that post (see below) but I keep running into the following error: polyline2 = mr.distanceMapTo2DIsoPolyline(dm.value(), isoValue=127) RuntimeError: Bad expected access. I cant find anything online about why this is happening and I'm no expert in Python so have no idea myself. If anyone has an idea, I'd really appreciate it!
Code from answer to above post:
import meshlib.mrmeshpy as mr
# load image as Distance Map object:
dm = mr.loadDistanceMapFromImage(mr.Path("your-image.png"), 0)
# find boundary contour of the letter:
polyline2 = mr.distanceMapTo2DIsoPolyline(dm.value(), isoValue=127)
# triangulate the contour
mesh = mr.triangulateContours(polyline2.contours2())
# extrude itself:
mr.addBaseToPlanarMesh(mesh, zOffset=30)
# export the result:
mr.saveMesh(mesh, mr.Path("output-mesh.stl"))
I have tried the following:
Reconfigured the MeshLib package that this command uses. Package docs here: https://meshinspector.github.io/MeshLib/html/index.html#PythonIntegration
Updating VS studio/python/MeshLib
In older version of meshlib python module RuntimeError: Bad expected access indicated that mr.loadDistanceMapFromImage had failed, you should had checked it like this:
import meshlib.mrmeshpy as mr
# load image as Distance Map object:
dm = mr.loadDistanceMapFromImage(mr.Path("your-image.png"), 0)
# check dm
if ( not dm.has_value() ):
raise Exception(dm.error())
# find boundary contour of the letter:
polyline2 = mr.distanceMapTo2DIsoPolyline(dm.value(), isoValue=127)
# triangulate the contour
mesh = mr.triangulateContours(polyline2.contours2())
# extrude itself:
mr.addBaseToPlanarMesh(mesh, zOffset=30)
# export the result:
mr.saveMesh(mesh, mr.Path("output-mesh.stl"))
But in actual release your code will rise exception with real error.
Please make sure that path is correct, if it doesn't help please provide more info like png file and version of python and version of MeshLib and anything else you find related.
P.S. If there is real problem with MeshLib better open issue in github.
I am using the python API of openslide packages to read some ndpi file.When I use the read_region function, sometimes it return a odd image. What problems could have happend?
I have tried to read the full image, and it will be worked well. Therefore, I think there is no problem with the original file.
from openslide import OpenSlide
import cv2
import numpy as np
slide = OpenSlide('/Users/xiaoying/django/ndpi-rest-api/slide/read/21814102D-PAS - 2018-05-28 17.18.24.ndpi')
image = slide.read_region((1, 0),6, (780, 960))
image.save('image1.png')
The output is strange output
As the read_region documentation says, the x and y parameters are always in the coordinate space of level 0. For the behavior you want, you'll need to multiply those parameters by the downsample of the level you're reading.
This appears to be a version-realted bug, see also
https://github.com/openslide/openslide/issues/291#issuecomment-722935212
The problem seems to relate to libpixman verions 0.38.x . There is a Workaround section written by GunnarFarneback suggesting to load a different version first e.g.
export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libpixman-1.so.0.34.0
upadte easier solution is:
We are using Python 3.6.8+ and this did the trick for us: conda install pixman=0.36.0
I have a huge grid in *.pvd format. I would like to ensure some cells size specification have been respected when building said grid. To do so, I should get a cell data array with (dx,dy,dz)
I first tried to check this in Paraview with very little success. Then I resolved to export the mesh in various format (vtk, vtu, ex2) and import things into python using the vtk module, as in the code below. Unfortunately, the size of the mesh forbids it and I get various error messages stating "Unable to allocate n cells of size x".
import vtk
reader = vtk.vtkXMLUnstructuredGridReader()
reader.SetFileName("my_mesh.vtu")
reader.Update()
Finally, in Paraview there is a python-shell that allows me to open the grid file in either pvd or vtk format:
>>> from paraview.simple import *
>>> my_vtk = OpenDataFile("my_mesh.vtk")
>>> print dir(my_vtk)
Despite my browsing the methods and attribute of this reader object, I remain clueless about where to fetch any geometry information on the grid. I also browsed through the simple module documentation and I can't really wrap my head around it.
So how can one retrieve information regarding the geometry of cells from a paraview.servermanager.LegacyVTKReader object?
Any clue about how to achieve this with through the paraview GUI, or any kludge to load the vtk object into python vtk despite the memory issue is also very welcome. Sorry for such a hazy question, but I don't really know where to get started...
You can use GetClientSideObject() (see here) to get a VTK object in the Paraview Python shell. After that you can use all the regular VTK Python functions. For example, you can write the following in the Paraview Python shell
>>> from paraview.simple import *
>>> currentSelection = GetActiveSource()
>>> readerObj = currentSelection.GetClientSideObject()
>>> unstructgrid = readerObj.GetOutput()
>>> firstCell = unstructgrid.GetCell(0)
>>> cellPoints = firstCell.GetPoints()
Alternatively, you can use Programmable Filter in ParaView. This allows access to full VTK python module and even NumPy or other modules. You can enter following script in the script window of the programmable filter:
import vtk as v
import numpy as np
inp = self.GetUnstructuredGridInput()
cells = inp.GetCells()
cells.InitTraversal()
cellPtIds = v.vtkIdList()
lenArr = v.vtkDoubleArray()
lenArr.SetNumberOfComponents(3)
lenArr.SetName('CellSize')
while cells.GetNextCell( cellPtIds ):
pts = []
for i in range( cellPtIds.GetNumberOfIds() ):
ptCoords = inp.GetPoint( cellPtIds.GetId(i) )
pts.append( ptCoords )
pts = np.array( pts )
dx = np.max(pts[:,0]) - np.min(pts[:,0])
dy = np.max(pts[:,1]) - np.min(pts[:,1])
dz = np.max(pts[:,2]) - np.min(pts[:,2])
lenArr.InsertNextTuple3(dx, dy, dz)
out = self.GetUnstructuredGridOutput()
out.ShallowCopy( inp )
out.GetCellData().AddArray( lenArr )
In Paraview when you select the 'ProgrammableFilter1' icon in your pipeline, a new cell data array will be available to you from the drop-down as shown in the screenshot below. You can modify the script above to save the data to file to analyze externally.
This information is visible in the Information Tab.
I am trying to read raw image data from a cr2 (canon raw image file). I want to read the data only (no header, etc.) pre-processed if possible (i.e pre-bayer/the most native unprocessed data) and store it in a numpy array. I have tried a bunch of libraries such as opencv, rawkit, rawpy but nothing seems to work correctly.
Any suggestion on how I should do this? What I should use? I have tried a bunch of things.
Thank you
Since libraw/dcraw can read cr2, it should be easy to do. With rawpy:
#!/usr/bin/env python
import rawpy
raw = rawpy.imread("/some/path.cr2")
bayer = raw.raw_image # with border
bayer_visible = raw.raw_image_visible # just visible area
Both bayer and bayer_visible are then a 2D numpy array.
You can use rawkit to get this data, however, you won't be able to use the actual rawkit module (which provides higher level APIs for dealing with Raw images). Instead, you'll want to use mostly the libraw module which allows you to access the underlying LibRaw APIs.
It's hard to tell exactly what you want from this question, but I'm going to assume the following: Raw bayer data, including the "masked" border pixels (which aren't displayed, but are used to calculate various things about the image). Something like the following (completely untested) script will allow you to get what you want:
#!/usr/bin/env python
import ctypes
from rawkit.raw import Raw
with Raw(filename="some_file.CR2") as raw:
raw.unpack()
# For more information, see the LibRaw docs:
# http://www.libraw.org/docs/API-datastruct-eng.html#libraw_rawdata_t
rawdata = raw.data.contents.rawdata
data_size = rawdata.sizes.raw_height * rawdata.sizes.raw_width
data_pointer = ctypes.cast(
rawdata.raw_image,
ctypes.POINTER(ctypes.c_ushort * data_size)
)
data = data_pointer.contents
# Grab the first few pixels for demonstration purposes...
for i in range(5):
print('Pixel {}: {}'.format(i, data[i]))
There's a good chance that I'm misunderstanding something and the size is off, in which case this will segfault eventually, but this isn't something I've tried to make LibRaw do before.
More information can be found in this question on the LibRaw forums, or in the LibRaw struct docs.
Storing in a numpy array I leave as an excersize for the user, or for a follow up answer (I have no experience with numpy).
I am trying to write a VTK Image Data file (.vti) with python. For my python coding I am using the Anaconda distribution. I am using the evtk package, which has the ability to write a vtk file.
The data I need to write is a velocity for which I have the 3d X,Y,Z and U,V,W 3d arrays. I have found some sample code which uses the evtk package to write a .vti file.(http://www.vtk.org/Wiki/VTK/Writing_VTK_files_using_python)
The problem is that the sample code and built in functions only take scalar point or cell data. So I am able to write a file with scalars, but I need it to have the data as vectors.
I am digging through the actual package files and trying to find a solution or tools to code one.I would extremely appreciate if somebody had suggestions or solutions to give me a hand.
I enclose the test code I have written from info on the wiki just in case I am missing a way of inputing to the function, but I fear I am going to need to start from scratch.
Thanks in advance
(removed the code since the one bellow is more recent)
Managed to write an unstructured file (.vtu), but I would really like to be a able to write an Image Data file.(Found the following link helpful during the process. http://www.aero.iitb.ac.in/~prabhu/tmp/python_cep07/course_handouts/viz3d_handout.pdf)
Thanks again in advance
I attach the code to see if anybody has any suggestions.
from tvtk.api import tvtk, write_data
import numpy as N
##Generation of data
#array of x,y,z coordinates
[Z,Y,X] = N.mgrid[-2.:2+1, -2.:2+1, -2.:2+1]
#array of zeros to add the u,v,w components
[W,V,U] = N.zeros_like([Z,Y,X],dtype=float)
#loop through data to have correct format
points = N.array([N.zeros(3) for i in range(len(Z)*len(Z[0])*len(Z[0][0]))])
velF = N.zeros_like(points)
c=0
for k in range(len(Z)):
for j in range(len(Z[0])):
for i in range(len(Z[0][0])):
#coordinates of point
x = X[k][j][i]
y = Y[k][j][i]
z = Z[k][j][i]
points[c] = N.array([x,y,z])
#test velocity field
u = k -2.
v = 0.
w = 0.
velF[c] = N.array([u,v,w])
#update counter
c = c+1
##Generate and write the vtk file
Ugrid = tvtk.UnstructuredGrid()
Ugrid.points = points
Ugrid.point_data.vectors = velF
Ugrid.point_data.vectors.name = 'velocity'
write_data(Ugrid, 'vtktest.vtu')
If you want to write the unstructured grids using evtk, here you can find a full demo with point and cell data (both vector and scalar fields): https://gist.github.com/dromanov/0fb8bacff5342a56a690.
Description of the technique and explanations are here: http://spikard.blogspot.ru/2015/07/visualization-of-unstructured-grid-data.html.
Good luck!