How to generate a 2d mesh from a binary image in python?

1.4k Views Asked by At

I'm digging in scikits image toolbox and similars in order to manipulate image data in python.

When we have a binary (x,y) image how could we use it as mask to generate a mesh inside the image limits? I want to export this mesh to a CAE program. So, I need to collect the mesh coordinates and also the element list

I found out some tools such as meshpy, but I didn't figure it out how can I solve this.

Thank you

1

There are 1 best solutions below

0
On

The following solution is based on MeshLib python package.

Let us have a binary image with 3 coins:3 coins

Then one can convert it in triangular mesh as follows:

import meshlib.mrmeshpy as mr
# load raster image:
dm = mr.loadDistanceMapFromImage(mr.Path("Binary_coins.png"), 0)
# find the boundary contour between black and white:
polyline2 = mr.distanceMapTo2DIsoPolyline(dm, isoValue=127)
# compute the triangulation inside the contour
mesh = mr.triangulateContours(polyline2.contours2())
# save 2D triangulation in a textual OBJ file:
mr.saveMesh(mesh, mr.Path("Binary_coins.obj"))

At this moment we got

2d triangulation

To construct a mesh with not that much degenerate triangles, long edges can be subdivided:

# by default split 1000 edges:
mr.subdivideMesh(mesh)
# save 2D mesh in a textual OBJ file:
mr.saveMesh(mesh, mr.Path("Binary_coins1.obj"))

Our final result:

2d mesh