Package: qtreemesh
QTREEMESHGeneration of QuadTree mesh from an imageExplore the docs »View Demo·Report Bug·Request FeatureTable of ContentsAbout The ProjectGetting StartedInstallationUsageRead ImagePreprocessingQuadTree AlgorithmMesh GenerationExport and ImplementationTheoretical ExplanationRoadmapContributingLicenseContactAcknowledgmentsAbout The ProjectQTREEMESH is a python package that can create aQuadtreestructure from an image. This tree data structure can also be converted to mesh structure that can be used in different areas of science, e.g. finite element analysis. The Quadtree algorithm in this package is based on pixels' intensity. For more information about this algorithm, please refer toTheoretical Explanationsection of this doc.(back to top)Getting StartedThis part explains how to install and use this package.InstallationInstallQTREEMESHfrom PyPI via pip.pipinstallqtreemesh(back to top)UsageThere is atest.pyfile inexamplesfolder that demonstrate how different parts of this package work. Here we go through this file line by line:1. Read ImageFirst we import required tools from other librariesfromPILimportImage# to read image file properlyfromnumpyimportasarray# for converting image matrix to arrayThen we read the image and convert it to gray-scale. There are three example images inexamplesfolder.4.jpgis smaller than the two others and need fewer computation efforts.im=Image.open("4.jpg").convert('L')2. PreprocessingThe quadtree algorithm is most efficient when the image is square and the number of its pixels is an integer power of 2, i.e. $2^n$. There is a functionimage_preprocess()dedicated to the modification of the original image by padding it with zero intensity pixels and satisfying the mentioned requirement:fromqtreemeshimportimage_preprocessimar=image_preprocess(asarray(im))3. QuadTree AlgorithmThe QuadTree decomposition can be performed onimage_arrayusing a recursive classQTreebased on giventolerance.fromqtreemeshimportQTreequad=QTree(None,imar,125)# QTree(None, image_array, tolerance)QTreeobject may have 4 childrenQTreeobjects (can be accessed through attributes:north_west,north_east,south_west,south_east) and so on. EachQTreehas an attributedividedthat determines the existence of children partitions. There are also an property method for countingcount_leavesand a method for saving tree leavessave_leaves(i.e. undivided partitions).4. Mesh GenerationCommon mesh data structure can be extracted from QuadTree structure usingQTreeMeshclass. After initiating the class, correspondingelementsandnodescan be generated as attributes of theQTreeMeshobject with the methodcreate_elements. The resulted mesh may be illustrated usingdrawmethod.fromqtreemeshimportQTreeMeshmesh=QTreeMesh(quad)mesh.create_elements()mesh.draw(True,'orangered')# mesh.draw(fill_inside, edge_color, save_name)Each element inelementsis aQTreeElementobject that contains many attributes, e.g. element number :number, element nodes :nodes_numbers, element property (average of pixel intensities) :element_propertyand etc.ExampleImageMesh4.jpg5.jpgFor more examples, please refer to theDocumentation5. Export and ImplementationOne can easily export generated mesh asvtkformat using following line:mesh.vtk_export(filename="4_meshed.vtk")and the result can be viewed in visualization applications such asParaView:It's worth mentioning that the methodvtk_export()has no dependency to vtk related libraries and create.vtkfile manually.It is also possible to adjust the elements to handle hanging nodes and generate a mesh that is either triangular or quadrilateral/triangular (based on templates available in [2] and [3]).:fem_nodes,fem_elements,fem_properties=mesh.adjust_mesh_for_FEM()The default configuration generates FEM elements as triangles. To include both quadrilateral and triangle elements, setforce_triagulationtoFalse.(back to top)Theoretical ExplanationIntroductionAQuadtreeis a special type of tree where each parent node has exactly four smaller nodes connected to it. Each square in the Quadtree is represented by a node. If a node has children, their squares are the four quadrants of its own square, which is why the tree is called a tree. This means that when you put the smaller squares of the leaves together, they make up the bigger square of the root.In this figure, labelsNW,NE,SE, andSWare representing different quadrants (North-West, North-East, South-East and South-West respectively).While this algorithm has many applications in various fields of science (e.g., collision detection, image compression, etc.), this doc especially focuses on the mesh generation subject. There almost three major definition of problem:Points set problems:In this case, there are a set of points ${p_i} : (x_i , y_i)$ (which can be interpreted as the position of objects), and we need to build the quadtree in such a way that every square contains at most $c$ point(s). First we consider the root square which contains all the points. Then we start recursively splitting squares until the criteria $n_p \le c$ met. In following figure, the quadtree of 11 points with $c = 1$ is illustrated:There are many different implementations of this variation of algorithm, for example inPython,C++, andC#.Domain boundary problems:This type of problem is very common in mesh generation for CAD models. The domain of interest is defined by some lines that usually separate inside of the domain from outside of it. A common approach is to generateseed pointson the boundary and create a quadtree just the same as points set problems. There will be some additional steps to convert quadtree to FEM mesh, such as removing the outside squares and trimming of boundary squares. The following figure illustrate quadtree ofa circular domain.Digital images problems:The quadtree decomposition of an image means dividing the image into squares with the same color (within a given threshold). Considering an image consisting of $2^n × 2^n$ pixels, the algorithm recursively split the image into four quadrants until the difference between the maximum and minimum pixels intensities becomes less than the specified tolerance.The current package is dedicated to these types of problems.Referencesde Berg, M., Cheong, O., van Kreveld, M., & Overmars, M. (2008). Computational geometry: Algorithms and applications. In Computational Geometry: Algorithms and Applications. Springer Berlin Heidelberg.https://doi.org/10.1007/978-3-540-77974-2Lo, D.S.H. (2015). Finite Element Mesh Generation (1st ed.). CRC Press.https://doi.org/10.1201/b17713George, P. L. (1992). Automatic mesh generation and finite element method. Wiley.https://doi.org/10.1016/S1570-8659(96)80003-2RoadmapCompleting the codes documentationAdding details to README fileExporting data asvtkformatSuccessfully implement in FEM softwareHandling hanging nodesPrepare required dataIllustrate usage in open-source FEM programsPrepare required data for SBFEMSee theopen issuesfor a full list of proposed features (and known issues).(back to top)ContributingContributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make aregreatly appreciated.If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement".
Don't forget to give the project a star! Thanks again!(back to top)LicenseDistributed under the MIT License. SeeLICENSE.txtfor more information.(back to top)ContactSadjad Abedi -AbediSadjad@gmail.comProject Link:https://github.com/Sad-Abd/qtreemesh(back to top)Acknowledgments(back to top)