Creating submesh using binanry image pixel data in Dolfinx

Hello everyone,

I want to create a submesh utilizing the binary image data. The following figure represents what I am trying to do. Let’s assume a 2*2 image data with 0s and 1s as depicted in the left figure. Each pixel should be represented by a quadrilateral element.

All the cells/elements with the zero values should be deleted from the submesh, and remaining submesh should look like the figure on the right.


I tried the following code. I represented the input data with the help of DG0 elements. This could could have worked if the marker function in mesh.locate_entities would take x as the co-ordinates of dofs instead of vertices. Please let me know how I should proceed.

import numpy as np

import ufl
from dolfinx import fem, io, mesh, plot
from ufl import ds, dx, grad, inner, nabla_grad

from mpi4py import MPI
from petsc4py.PETSc import ScalarType

## input data (typical to 2D binary image)
data = np.zeros((2,2))
data[0,0] = 1.0
data[1,1] = 1.0

msh = mesh.create_rectangle(comm=MPI.COMM_WORLD,
                            points=((0.0, 0.0), (1.0, 1.0 )), n=(2, 2),

V = fem.FunctionSpace(msh, ('DG', 0))
dof_coo = V.tabulate_dof_coordinates()

def submesh_marker(x,data):
    ## x is co-ordinates of all the vertices
    # this code could have worked, if x would have been the coordinates of dofs. 
    ix = np.round((x[0])/0.5).astype(int)
    iy = np.round((x[1])/0.5).astype(int)
    return abs(data[ix,iy]-1) < tol 

submesh_entities = mesh.locate_entities(msh, msh.topology.dim, marker = lambda x: submesh_marker(x,data)) 
submesh_omega_tilde = mesh.create_submesh(msh, msh.topology.dim, submesh_entities)[0]
dx_subdomain = ufl.Measure("dx", domain = submesh_omega_tilde)

V_sub = fem.FunctionSpace(submesh_omega_tilde, ('DG', 0))

Use locate_dofs_geometrical instead, as DG0 function space has dofs at the center of each cell, and the dof ordering aligns with the mesh cells.

1 Like

Thanks @dokken , it worked.