Coder Social home page Coder Social logo

pyvista / pymeshfix Goto Github PK

View Code? Open in Web Editor NEW
268.0 13.0 27.0 52.56 MB

Python Wrapper for MeshFix: easily repair holes in surface meshes

Home Page: http://pymeshfix.pyvista.org

License: GNU General Public License v3.0

Python 3.54% C++ 88.78% C 5.26% Cython 2.41%
mesh-processing mesh 3d-reconstruction 3d

pymeshfix's Introduction

PyMeshFix

Python/Cython wrapper of Marco Attene's wonderful, award-winning MeshFix software. This module brings the speed of C++ with the portability and ease of installation of Python.

This software takes as input a polygon mesh and produces a copy of the input where all the occurrences of a specific set of "defects" are corrected. MeshFix has been designed to correct typical flaws present in raw digitized mesh models, thus it might fail or produce coarse results if run on other sorts of input meshes (e.g. tessellated CAD models).

The input is assumed to represent a single closed solid object, thus the output will be a single watertight triangle mesh bounding a polyhedron. All the singularities, self-intersections and degenerate elements are removed from the input, while regions of the surface without defects are left unmodified.

C++ source last updated 1 Jul 2020

Installation

From PyPI

pip install pymeshfix

From source at GitHub

git clone https://github.com/pyvista/pymeshfix
cd pymeshfix
pip install .

Dependencies

Requires numpy and pyvista

If you can't or don't want to install vtk, you can install it without pyvista with:

pip install pymeshfix --no-dependencies

You'll miss out on some of the cool features from pyvista, but it will still function.

Examples

Test installation with the following from Python:

from pymeshfix import examples

# Test of pymeshfix without VTK module
examples.native()

# Performs same mesh repair while leveraging VTK's plotting/mesh loading
examples.with_vtk()

Easy Example

This example uses the Cython wrapper directly. No bells or whistles here:

import pymeshfix

# Read mesh from infile and output cleaned mesh to outfile
pymeshfix.clean_from_file(infile, outfile)

This example assumes the user has vertex and faces arrays in Python.

import pymeshfix

# Generate vertex and face arrays of cleaned mesh
# where v and f are numpy arrays
vclean, fclean = pymeshfix.clean_from_arrays(v, f)

Complete Examples with and without VTK

One of the main reasons to bring MeshFix to Python is to allow the library to communicate to other python programs without having to use the hard drive. Therefore, this example assumes that you have a mesh within memory and wish to repair it using MeshFix.

import pymeshfix

# Create object from vertex and face arrays
meshfix = pymeshfix.MeshFix(v, f)

# Plot input
meshfix.plot()

# Repair input mesh
meshfix.repair()

# Access the repaired mesh with vtk
mesh = meshfix.mesh

# Or, access the resulting arrays directly from the object
meshfix.v # numpy np.float64 array
meshfix.f # numpy np.int32 array

# View the repaired mesh (requires vtkInterface)
meshfix.plot()

# Save the mesh
meshfix.write('out.ply')

Alternatively, the user could use the Cython wrapper of MeshFix directly if vtk is unavailable or they wish to have more control over the cleaning algorithm.

import pymeshfix

# Create TMesh object
tin = pymeshfix.PyTMesh()

tin.LoadFile(infile)
# tin.load_array(v, f) # or read arrays from memory

# Attempt to join nearby components
# tin.join_closest_components()

# Fill holes
tin.fill_small_boundaries()
print('There are {:d} boundaries'.format(tin.boundaries()))

# Clean (removes self intersections)
tin.clean(max_iters=10, inner_loops=3)

# Check mesh for holes again
print('There are {:d} boundaries'.format(tin.boundaries()))

# Clean again if necessary...

# Output mesh
tin.save_file(outfile)

 # or return numpy arrays
vclean, fclean = tin.return_arrays()

Algorithm and Citation Policy

To better understand how the algorithm works, please refer to the following paper:

M. Attene. A lightweight approach to repairing digitized polygon meshes. The Visual Computer, 2010. (c) Springer. DOI: 10.1007/s00371-010-0416-3

This software is based on ideas published therein. If you use MeshFix for research purposes you should cite the above paper in your published results. MeshFix cannot be used for commercial purposes without a proper licensing contract.

Copyright

MeshFix is Copyright(C) 2010: IMATI-GE / CNR

All rights reserved.

This program is dual-licensed as follows:

(1) You may use MeshFix as free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.

In this case the program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License (http://www.gnu.org/licenses/gpl.txt) for more details.

(2) You may use MeshFix as part of a commercial software. In this case a proper agreement must be reached with the Authors and with IMATI-GE/CNR based on a proper licensing contract.

pymeshfix's People

Contributors

akaszynski avatar banesullivan avatar dependabot[bot] avatar jmargeta avatar larsoner avatar nachovizzo avatar pre-commit-ci[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pymeshfix's Issues

Release 0.13.2

Can we move forward with this soon?

Todos:

  • document the inputs to MeshFix class better (its inputs are not what I expected so I imagine a new user might get confused too)

BUG: Release incorrect?

The conda-forge feedstock update is failing:

conda-forge/pymeshfix-feedstock#7

https://github.com/conda-forge/pymeshfix-feedstock/pull/7/checks?check_run_id=10622344654

Processing $SRC_DIR
  Added file://$SRC_DIR to build tracker '/tmp/pip-build-tracker-d8lfz1vk'
  Created temporary directory: /tmp/pip-modern-metadata-hmzxto2b
  Preparing metadata (pyproject.toml): started
  Running command Preparing metadata (pyproject.toml)
  Traceback (most recent call last):
    File "/home/conda/feedstock_root/build_artifacts/pymeshfix_1673585787412/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/lib/python3.8/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 351, in <module>
      main()
    File "/home/conda/feedstock_root/build_artifacts/pymeshfix_1673585787412/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/lib/python3.8/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 333, in main
      json_out['return_val'] = hook(**hook_input['kwargs'])
    File "/home/conda/feedstock_root/build_artifacts/pymeshfix_1673585787412/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/lib/python3.8/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 152, in prepare_metadata_for_build_wheel
      return hook(metadata_directory, config_settings)
    File "/home/conda/feedstock_root/build_artifacts/pymeshfix_1673585787412/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/lib/python3.8/site-packages/setuptools/build_meta.py", line 377, in prepare_metadata_for_build_wheel
      self.run_setup()
    File "/home/conda/feedstock_root/build_artifacts/pymeshfix_1673585787412/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/lib/python3.8/site-packages/setuptools/build_meta.py", line 335, in run_setup
      exec(code, locals())
    File "<string>", line 63, in <module>
    File "/home/conda/feedstock_root/build_artifacts/pymeshfix_1673585787412/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/lib/python3.8/site-packages/Cython/Build/Dependencies.py", line 970, in cythonize
      module_list, module_metadata = create_extension_list(
    File "/home/conda/feedstock_root/build_artifacts/pymeshfix_1673585787412/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/lib/python3.8/site-packages/Cython/Build/Dependencies.py", line 816, in create_extension_list
      for file in nonempty(sorted(extended_iglob(filepattern)), "'%s' doesn't match any files" % filepattern):
    File "/home/conda/feedstock_root/build_artifacts/pymeshfix_1673585787412/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/lib/python3.8/site-packages/Cython/Build/Dependencies.py", line 114, in nonempty
      raise ValueError(error_msg)
  ValueError: 'pymeshfix/cython/_meshfix.pyx' doesn't match any files

Looking at the pymeshfix-0.16.2.tar.gz on PyPI, the _meshfix.pyx is indeed missing. @akaszynski did something change in recent PRs with the build infrastructure that would have caused this file to no longer be distributed?

Cannot plot using MeshFix plot

Hi,
I am using pymeshfix to detect self intersecting triangles and holes.
I am using pyvista to load the file and using meshfix plot() function to visualize the mesh.

import pyvista
reader = pyvista.get_reader('Error_Cylinder.stl')
meshfix = pymeshfix.MeshFix(mesh)
meshfix.plot()

However I am getting the following error:
AttributeError: 'MeshFix' object has no attribute 'f'

at
File ~\source\Anaconda\envs\3dEnv\lib\site-packages\pymeshfix\meshfix.py:117, in MeshFix.mesh(self)
115 if not PV_INSTALLED:
116 raise RuntimeError('Please install pyvista for this feature')
117 triangles = np.empty((self.f.shape[0], 4), dtype=pv.ID_TYPE)

Can someone help with this issue?

Segmentation fault when trying to load it through load_array

Hello, I am trying to load the attached mesh using the following code and get Segmentation fault (core dumped).
Please note that the vertices and faces are given using trimesh since I am doing some operation with it. The mesh is not watertight.

from pymeshfix._meshfix import PyTMesh
from pymeshfix import _meshfix
filepath = "/home/marios/Desktop/MARIOS/phd/CollaborativeStructure/customChunker/debugAssets/nonWatertightPosMesh.stl"
probPart = trimesh.load_mesh(filepath)
print("Is watertight: ", probPart.is_watertight)
tin = _meshfix.PyTMesh()
v = np.array(probPart.vertices)
f = np.array(probPart.faces)
tin.load_array(v, f)

However if I load it as follows I do not get any error and the mesh is watertight.

from pymeshfix._meshfix import PyTMesh
from pymeshfix import _meshfix
filepath = "/home/marios/Desktop/MARIOS/phd/CollaborativeStructure/customChunker/debugAssets/nonWatertightPosMesh.stl"
tin = _meshfix.PyTMesh()
tin.load_file(filepath)

Do you maybe have any suggestions or possible solutions that I could use?

nonWatertightPosMesh.zip

examples test failed

Hi,
I use the test code in introduction parts:
to use example.native()
error:
/usr/bin/python3.6 /home/absarthas/PycharmProjects/pymeshfixtest/testcode.py
Traceback (most recent call last):
File "/home/absarthas/PycharmProjects/pymeshfixtest/testcode.py", line 5, in
examples.native()
File "/home/absarthas/.local/lib/python3.6/site-packages/pymeshfix/examples/fix.py", line 12, in native
pymeshfix._meshfix.CleanFromFile(bunny_scan, outfile)
AttributeError: module 'pymeshfix._meshfix' has no attribute 'CleanFromFile'

if use examples.with_vtk()
error:
/usr/bin/python3.6 /home/absarthas/PycharmProjects/pymeshfixtest/testcode.py
Plotting input mesh
Traceback (most recent call last):
File "/home/absarthas/PycharmProjects/pymeshfixtest/testcode.py", line 8, in
examples.with_vtk()
File "/home/absarthas/.local/lib/python3.6/site-packages/pymeshfix/examples/fix.py", line 21, in with_vtk
meshfix.Plot()
AttributeError: 'MeshFix' object has no attribute 'Plot'

Would you please help me resolve this problem?
the platform is ubuntu 18.04, python 3.6

Thank you!!
Bowen

Continously error in Slicer3d when import pymeshfix library in module

I´m trying to use your pymeshfix library in Slicer3d with Python version 3.6.7 (default, Oct 23 2021, 23:20:53) [MSC v.1924 64 bit (AMD64). If I make the import in Python interractor, it works fine but if I add "import pymeshfix" to a module, Python Interactor send me continously an error message like:

Input port 0 of algorithm vtkTubeFilter(000001DB85805BE0) has 0 connections but is not optional.".

It´s something recurrent, tons of messages but nothing crash despite of this...

Thanks in advance!

Meshfix leaves only one triangle

I have a bad mesh generated from another piece of software. I am trying to figure out what exactly the problem is so that I can provide some feedback to the software developers. I thought I would try some independent solutions.

Here is the obj file:
section 5.zip

I am learning how to use PyVista and I have run it through mesh cleaning there. It seems to work fine and clean up the mesh to a state where it is consistent (if you translate the original mesh to the origin and determine the volume, it is different). After cleaning it is consistent. However the cleaning routine isn't verbose (or I haven't figured out) enough to tell me what problems it encountered during the cleaning process.

I decided to try this library.

I have the following code:

import pyvista as pv
import pyvistaqt as pvqt # allow for rendering in a background thread in a separate window

# pv.set_plot_theme('document')

bad_mesh_path = Path('./data/section 5.obj')
m = pv.read(bad_mesh_path)

print(f'volume = {m.volume}')
print(f'faces  = {m.n_faces}')
print(f'points = {m.n_points}')
print(f'bounds = {m.bounds}')
print()

meshfix = pymeshfix.MeshFix(m) # this fails directly
meshfix.repair(verbose=True)
repaired = meshfix.mesh

print()
print(f'volume = {repaired.volume}')
print(f'faces  = {repaired.n_faces}')
print(f'points = {repaired.n_points}')
print(f'bounds = {repaired.bounds}')
print()

repaired.plot()

It produces the following output:

volume = 149.95313299066808
faces  = 132
points = 396
bounds = [613887.6875, 613902.5, 8453912.0, 8453914.0, 2711.08740234375, 2722.792236328125]

Removed 131 small components
Patching holes...
Patched 1 holes
Fixing degeneracies and intersections
Patching holes...
Patched 1 holes
Performing final check...

volume = 289258.8383483886
faces  = 1
points = 3
bounds = [613888.0, 613888.4375, 8453913.0, 8453914.0, 2716.02978515625, 2716.990966796875]

The fixed mesh only has one triangle and 3 points, something is very wrong.

I do notice that running it through PyVista's clean routine the number of points it removes is quite large.

I would appreciate any insight. For what I am doing, I don't necessarily need a repair - that is nice, what I need is a detailed diagnosis of what is wrong with the mesh.

If you need any more wireframes, let me know. I have quite a few of them.

Loading a mesh to fill holes in it .obj file

I tried repair() to fill holes in my mesh .
But it cutted my mesh into half and filled areas within it ..
Can it be solved..

And also my mesh has vertex colors and how can I extract textures from it.

Fixing Specific Hole

Hi!
Currently, there's an option to fill only small holes, i.e., holes that have only a maximum number of boundary edges. It would be cool to have a more general option to specifically select a hole. A start would be to have a similar method to Basic_TMesh::fillSmallBoundaries() that would make the check grd == nbe instead of grd <= nbe. This would ensure that only those holes with a specific number of boundary edges are filled. To avoid any kind of ambiguities, an option to specify the indices of the boundary would be best.

Unexpected cleaning result

Hey,

I try to repair the following mesh (a dental bridge):

1
2

Within the mesh are some holes and also intersecting triangles. I use the function tin.small_boundaries() and if i detect intersecting triangles also tin.clean(max_iters=10, inner_loops=3). Unfortunately, the dental bridge is split, leaving only one tooth in the end:

3

Do you maybe have some ideas how i can fix this issue? You can find the used source code and the *.stl file below:
ScriptAndModel.zip

# -*- coding: utf-8 -*-
import pymeshfix



def plotMesh(tin):
    
    # return vertices and faces
    vertices, faces = tin.return_arrays()
    
    # Create object from vertex and face arrays
    meshfix = pymeshfix.MeshFix(vertices, faces)

    # Plot input
    meshfix.plot()





# Create TMesh object
tin = pymeshfix.PyTMesh()

# load stl file
tin.load_file("bridge08.stl")

# visualize input Mesh
plotMesh(tin)



###############################################################################
# CLEANING ROUTINE

# Attempt to join nearby components
# tin.join_closest_components()

# Fill holes
tin.fill_small_boundaries()
print('There are {:d} boundaries'.format(tin.boundaries()))

# check for intersecting triangles
faces = [tin.select_intersecting_triangles()]

# if intersecting triangles are detected within the mesh
if faces:
    # Clean (removes self intersections)
    tin.clean(max_iters=10, inner_loops=3)
###############################################################################



# visualize output Mesh
plotMesh(tin)

Meshfix().repair() crashes Python code with no error message

I am iterating through a set of .STL files and repairing the meshes if they are broken using MeshFix().repair(), and the program is terminating without any error message, warning message, exception or any other indication that there is an issue.

One thing that I have noticed is that it is terminating on larger files.

Is it possible to extract individual holes

Hello,

Just wonder if it is possible extract individual holes, so that I can iterate those holes.

meshfix = mf.MeshFix(holy_cow)
holes = meshfix.extract_holes()
for hole in holes:
    do_something()

image

Always triangulate input PolyData meshes

Realized when addressing pyvista/pyvista-support#71

if faces.size % 4:
tri_mesh = mesh.tri_filter()
faces = tri_mesh.faces

That test does not always work. You can easily have a faces array that is a multiple of 4 but not all triangules. For example, a cylinder:

import pyvista as pv
import pymeshfix

cyl = pv.Cylinder(direction=(0.0, 0.0, 1.0), radius=1.0, height=5.0)
cyl_clipped = cyl.clip('z', value=1.0, 
                       origin=(0.0, 0.0, -2.5))
cyl_clipped.plot(show_edges=True)

download

But:

print(cyl_clipped.faces.size % 4)

0

so when you try to just pass that mesh tp MesFix, it segfaults because it thinks all cells are triangles when in fact they are not

fixer = pymeshfix.MeshFix(cyl_clipped)
fixer.repair()
repaired = fixer.mesh

Solution:

Always call .triangulate() on PyVista meshes - if it is already triangles, then it won't make a difference.

Interoperability with PyVista (& relicensing?)

PyVista is currently a dependency of PyMeshFix - this is compliant with the GPL license. However we cannot provide a link in the other direction as the GPL license forbids any dynamic linking from non-GPL software to GPL-software.

It'd be awesome if we could provide a link to PyMeshFix from PyVista to make mesh repair easily accessible to a broader audience. Unfortunately, this would require PyVista to be relicensed under GPL which is likely not an option as PyVista has many non-GPL downstream dependencies.

Pinging @MarcoAttene: would it be possible for us to collaborate here and relicense this Python wrapper for MeshFix such that is has minimal impacts on downstream dependencies?

Error when accessing to the mesh

Description of the bug
Try to access to the mesh of a MeshFix is broken


Steps to reproduce

import pyvista as pv
import pymeshfix as mf

o = pv.Sphere()
fix = mf.MeshFix(o)
print(fix.mesh)

The result:

Traceback (most recent call last):
  File "\tests\meshfixbug.py", line 6, in <module>
    print(fix.mesh)
  File "\lib\site-packages\pymeshfix\meshfix.py", line 92, in mesh
    return pv.PolyData(self.v, triangles, deep=False)
  File "\lib\site-packages\pyvista\core\pointset.py", line 181, in __init__
    self._from_arrays(args[0], args[1], deep)
  File "\lib\site-packages\pyvista\core\pointset.py", line 278, in _from_arrays
    self.SetPolys(CellArray(faces))
  File "\lib\site-packages\pyvista\utilities\cells.py", line 56, in __init__
    self._set_cells(cells, n_cells, deep)
  File "\lib\site-packages\pyvista\utilities\cells.py", line 59, in _set_cells
    vtk_idarr, cells = numpy_to_idarr(cells, deep=deep, return_ind=True)
  File "\lib\site-packages\pyvista\utilities\cells.py", line 17, in numpy_to_idarr
    raise TypeError('Indices must be either a mask or an integer array-like')
TypeError: Indices must be either a mask or an integer array-like

System Information:

# Get system info
import pyvista as pv
print(pv.Report())
--------------------------------------------------------------------------------
  Date: Fri Feb 05 08:37:30 2021 Paris, Madrid

                OS : Windows
            CPU(s) : 8
           Machine : AMD64
      Architecture : 64bit
       Environment : Python
        GPU Vendor : NVIDIA Corporation
      GPU Renderer : GeForce RTX 2080 Ti/PCIe/SSE2
       GPU Version : 4.5.0 NVIDIA 461.09

  Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit
  (AMD64)]

           pyvista : 0.28.1
               vtk : Version unknown
             numpy : 1.19.5
           imageio : 2.9.0
           appdirs : 1.4.4
            scooby : 0.5.6
            meshio : 4.3.8
        matplotlib : 3.3.4
             PyQt5 : 5.15.2
             scipy : 1.6.0
              tqdm : 4.54.1
--------------------------------------------------------------------------------

Fix:
Define a dtype=int in mesh property of MeshFix

Unable to load the .obj file

Hi,
I am trying to load an obj file and fix the hole in the mesh.
But I got an error message when using the function load_file():
image

Following is my code:

import pymeshfix

infile = '/media/caig/423ECD443ECD3229/part_dataset/partnet_chair_level_1_obj/partnet_chair_level_1/1a6f615e8b1b5ae4dbbc9440457e303e/model_0.obj'

# Create TMesh object
meshfix = pymeshfix.PyTMesh()

meshfix.load_file(infile)

And this is my .obj file:
https://drive.google.com/file/d/1dnR8FDXCcJW6eon5YRpaHHtkw0ADBY6X/view?usp=sharing

Is something wrong with my .obj file?

Thanks

Help: non-volume meshes

I have install pymeshfix using: pip install pymeshfix on my python 3.6 conda enviroment along some other libraries such as pymesh, pythonOCC, ifcopenshell, and trimesh.
I simply want to make sure my meshes are water tight. I am trying to run:
meshfix = pymeshfix.MeshFix(vertices, faces)
meshfix.repair()
pmfv = meshfix.v

However, I always end up with the error below:

File "/home/alpay/PycharmProjects/Hiwi/hi.py", line 98, in
pmfv,pmff = pymeshfixfix(cverts,cfaces)
File "/home/alpay/PycharmProjects/Hiwi/hi.py", line 58, in pymeshfixfix
meshfix.repair()
File "/home/alpay/anaconda3/envs/hiwi36/lib/python3.6/site-packages/pymeshfix/meshfix.py", line 133, in repair
remove_smallest_components)
File "pymeshfix/cython/_meshfix.pyx", line 324, in pymeshfix._meshfix.clean_from_arrays
File "pymeshfix/cython/_meshfix.pyx", line 163, in pymeshfix._meshfix.PyTMesh.load_array
File "stringsource", line 654, in View.MemoryView.memoryview_cwrapper
File "stringsource", line 349, in View.MemoryView.memoryview.cinit
ValueError: buffer source array is read-only

Any help would be appreciated :)

Error- float property expected

import pyvista as pv
from pymeshfix._meshfix import PyTMesh
mfix = PyTMesh('output2.ply')  # False removes extra verbose output
mfix.load_file(planar_mesh)

On calling load_file function (which is an inbuilt function of PyTMesh) the program exits with error code 255 and the kernel stops. I have attached the .ply file.
Any help will be appreciated.
Thanks
output2.ply.zip

Installation error

clang: error: no such file or directory: 'pymeshfix/cython/_meshfix.cpp'

Is it process also color information for hole filling?

Thank you very much for your nice repository.
I am trying to fill hole in pointcloud using your method:

# Fill holes
tin.fill_small_boundaries()
print('There are {:d} boundaries'.format(tin.boundaries())

can I use it for pointcloud with color information?

silence meshfix output

It would be nice to have a "quiet" option to stop meshfix output. I tried changing sys.stderr and stdout but it did not seem to help.

[question] Using only the meshfix wrapper without VTK possible?

First, thanks for writing a python wrapper for MeshFix, Great idea.
I've seen the following statement in the readme:

Alternatively, the user could use the Cython wrapper of MeshFix directly if vtk is unavailable

This sounds great, but i couldn't get it to work. I must say, that i'm a total beginner in python devlopment, so i assume it's fully my fault, but for me this sounds like i could use the wrapper without having vtk installed!

The problem is, if i use the import statement from the example from pymeshfix import _meshfix i always get the error "module named 'vtk' not found', and nothing is imported.

After a little googling i found a dirty hack that fakes an already installed module: sys.modules['vtk'] = object(). But then the import fails with "object has no attribute 'VTK_ARIAL'.

I realy only need the mesh cleaning functions and absolutly no display stuff. The original MeshFix commandline tool has no UI elements and does only pure mesh processing.

Can you help me, or point me in the right direction, on howto use the pure meshfix wrapper without any dependency on 'pyvista' and 'vtk'?

For your interest: I'm working on some extra nodes for Meshroom to get better Retopology(integrating Instant Meshes) and Mesh-Repair funtionality (hence trying to use the MeshFix functions) inside it.
See: natowi/meshroom_external_plugins#2

Many thanks in advance

Segmentation fault with meshes containing 2 holes or more when trying to repair them

I receive the error message

WARNING:root:DEPRECATED: ``.extract_edges`` is deprecated. Use ``.extract_feature_edges`` > instead.
WARNING- forceNormalConsistence: Basic_TMesh was not orientable. Cut performed.
Fatal Python error: Segmentation fault

Current thread 0x00007f212e597740 (most recent call first):
  File "/mnt/4EB2FF89256EC207/anaconda3/envs/pymesh/lib/python3.7/site- packages/pymeshfix/meshfix.py", line 164 in repair

When trying to repair these meshes with 2 holes or more, is there a way to repair this type of meshes ?

mini_mesh4.zip
spinetest.zip

Thank you

Unable to install on Mac OS

Line 33 in setup.py should be commented out, at least for MacOS system. Else the following error occurs:

error: invalid argument '-std=gnu++11' not allowed with 'C'
error: command 'gcc' failed with exit status 1

Error while running meshfix.repair()

Hey,

If i try to repair an input mesh file, the following error will follow:

Windows fatal exception: access violation


Main thread:
Current thread 0x000031d4 (most recent call first):
  File "C:\Developer\WPy64-3950\python-3.9.5.amd64\lib\site-packages\pymeshfix\meshfix.py", line 207 in repair
  File "C:\Users\Marcel\Desktop\untitled5.py", line 84 in <module>
  File "C:\Developer\WPy64-3950\python-3.9.5.amd64\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 465 in exec_code
  File "C:\Developer\WPy64-3950\python-3.9.5.amd64\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 585 in runfile
  File "C:\Users\Marcel\AppData\Local\Temp\ipykernel_6628\358323758.py", line 1 in <module>


Restarting kernel...

i got the following pyvista Report:

--------------------------------------------------------------------------------
  Date: Thu Feb 24 12:00:46 2022 Mitteleuropäische Zeit

                OS : Windows
            CPU(s) : 8
           Machine : AMD64
      Architecture : 64bit
               RAM : 31.7 GiB
       Environment : IPython
       File system : unknown
       GPU Details : None

  Python 3.9.5 (tags/v3.9.5:0a7dcbd, May  3 2021, 17:27:52) [MSC v.1928 64 bit
  (AMD64)]

           pyvista : 0.33.2
               vtk : 9.1.0
             numpy : 1.21.0
           imageio : 2.9.0
           appdirs : 1.4.4
            scooby : 0.5.11
        matplotlib : 3.4.2
             PyQt5 : 5.12.3
           IPython : 7.25.0
          colorcet : 1.0.0
             scipy : 1.7.0
              tqdm : 4.61.1

  Intel(R) Math Kernel Library Version 2020.0.4 Product Build 20200917 for
  Intel(R) 64 architecture applications
--------------------------------------------------------------------------------

Disable print output for fill_small_boundaries

Hi,

I'm using meshfix to fill holes in my mesh - is there anyway to disable the output when running the fill_small_boundaries command? I am running it on very large meshes which results in a lot of unwanted output at the moment as it prints every time a hole is filled.

from pymeshfix._meshfix import PyTMesh

mfix = PyTMesh(False)
mfix.load_file(file_path)
fixed_mesh = mfix.fill_small_boundaries(nbe=0, refine=True)

Many thanks!

Does Pymeshfix has anything to remove overlapping mesh regions

I have 2 mesh which are similar not exactly same but has 30-35% similarities..
I combined them using concatenate() in trimesh library

Like one mesh on another

But after concatenation I find places where the lower mesh overlaps at certain places above the upper mesh..
Is there any function to remove only the overlapping parts of the lower positioned mesh..without using any backend like blender..

For eg Take a look at the image below :

maxresdefault (1)

Thanks in advance for anyone who took time to go through it ..

New release for numpy 2.0 necessary?

Hi,

Is it possible we need a new release of pymeshfix now that numpy 2.0.0 is out? Or update dependency requirements in setup.py so that only numpy 1.X is supported?

I get the following error during unit tests of a library that uses pymeshfix

lib\my-lib\dev\meshfix.py:9: in
from pymeshfix import meshfix
.venv\lib\site-packages\pymeshfix_init
.py:2: in
from pymeshfix import _meshfix # noqa: F401
pymeshfix\cython\_meshfix.pyx:1: in init pymeshfix._meshfix
???
E ImportError: numpy.core.multiarray failed to import (auto-generated because you didn't call 'numpy.import_array()' after cimporting numpy; use 'numpy._import_array' to disable if you are certain you don't need it).
------------------------------- Captured stderr -------------------------------

A module that was compiled using NumPy 1.x cannot be run in
NumPy 2.0.0 as it may crash. To support both 1.x and 2.x
versions of NumPy, modules must be compiled with NumPy 2.0.
Some module may need to rebuild instead e.g. with 'pybind11>=2.12'.

If you are a user of the module, the easiest solution will be to
downgrade to 'numpy<2' or try to upgrade the affected module.
We expect that some modules will need time to support NumPy 2.

Move all pyvista specific code into pyvista

It is currently impossible to use the core of the pymeshfix without installing pyvista. It is true that using pip install pymeshfix --nodependencies will not install pyvista (see #16 ), but this is not possible when pyvista is part of a requirements.txt file for example. Also, we don't want no dependencies at all, we just don't want any unnecessary dependencies for the core of the library (like pyvista, depending on imageio, appdirs, scooby, meshio and vtk).

To me it seems backwards that pymeshfix has a pyvista interface at all, and this code is not just included into pyvista. pymeshfix could be specified as a pyvista requirement and all plotting and vtk interfaces could be implented at the pyvista side.
This would imo be much more logical because you will not have to deal with any optional requirements anymore. If you want to use the core of pymeshfix, you just install pymeshfix. If you want to use a pyvista interface and fix meshes and plot them, use pyvista, which includes pymeshfix as a utility.

Is there any reason why pymeshfix is not a dependency of pyvista?

I really believe the functionality in pymeshfix is very useful. However, the unnecessary dependency of pyvista will push away people that are only looking for a way to fix meshes or perform mesh validity checks.

I would be willing to contribute and create a pull request for both pymeshfix and pyvista with the necessary changes.

Installing in conda env, reinstalls VTK

Hi, not sure if this is an issue with my install method or not, but any help would be appreciated.

I'm trying to install pymeshfix in an existing conda environment in which PyVista is working fine. But in this environment, my VTK is sourced from the channel vmtk (http://www.vmtk.org/) rather than conda-forge.

When I try to install pymeshfix in this environment, it doesn't detect the existing VTK installation. I get a "Requirement already satisfied" message for pyvista, but "Collecting vtk" for VTK.

Here's how I'm creating the env:
conda create -n vmtk -c vmtk -c conda-forge python=3.6 itk vtk vmtk pyvista
Followed by:
pip install pymeshfix

I've tried creating a conda env from scratch with just PyVista, and then pip install pymeshfix works without any issues. Again, I'm not sure if this is expected behaviour and maybe I'm doing something unwise with my installation.

Thanks!

How to close gaps in PyVista

Hi!
I am struggling trying to close open gaps that I have in planar non-watertight meshes. Is there any way I could close these long open gaps that appear, not the holes using pymeshfix?
Thanks
region_8.zip
Screenshot from 2021-09-17 12-40-18
!

examples.native() AND examples.with_vtk() fail

running pymeshfix after install with pip
first error:

import pymeshfix
from pymeshfix import examples
examples.native()

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-0f795062c8aa> in <module>
----> 1 examples.native()

~/anaconda3/envs/test/lib/python3.7/site-packages/pymeshfix/examples/fix.py in native(outfile)
     12 def native(outfile='repaired.ply'):
     13     """ Repair Stanford Bunny Mesh """
---> 14     pymeshfix._meshfix.CleanFromFile(bunny_scan, outfile)

AttributeError: module 'pymeshfix._meshfix' has no attribute 'CleanFromFile'

The second error happens with examples.with_vtk() after closing the window that pops up

examples.with_vtk()                                                                                                                     
Plotting input mesh
Plotting repaired mesh
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-6-d930cf051638> in <module>
----> 1 examples.with_vtk()

~/anaconda3/envs/test/lib/python3.7/site-packages/pymeshfix/examples/fix.py in with_vtk(plot)
     25     if plot:
     26         print('Plotting repaired mesh')
---> 27         meshfix.plot()
     28 
     29     return meshfix.mesh

~/anaconda3/envs/test/lib/python3.7/site-packages/pymeshfix/meshfix.py in plot(self, show_holes, **kwargs)
    113             plotter = pv.Plotter()
    114             plotter.add_mesh(self.mesh, label='mesh')
--> 115             plotter.add_mesh(edges, 'r', label='edges')
    116             plotter.show()
    117 

~/anaconda3/envs/test/lib/python3.7/site-packages/pyvista/plotting/plotting.py in add_mesh(self, mesh, color, style, scalars, clim, show_edges, edge_color, point_size, line_width, opacity, flip_scalars, lighting, n_colors, interpolate_before_map, cmap, label, reset_camera, scalar_bar_args, show_scalar_bar, stitle, multi_colors, name, texture, render_points_as_spheres, render_lines_as_tubes, smooth_shading, ambient, diffuse, specular, specular_power, nan_color, nan_opacity, loc, backface_culling, rgb, categories, use_transparency, below_color, above_color, annotations, pickable, **kwargs)
    804 
    805         if mesh.n_points < 1:
--> 806             raise RuntimeError('Empty meshes cannot be plotted. Input mesh has zero points.')
    807 
    808         # Try to plot something if no preference given

RuntimeError: Empty meshes cannot be plotted. Input mesh has zero points.
~/anaconda3/envs/test/lib/python3.7/site-packages/pymeshfix/meshfix.py in plot(self, show_holes, **kwargs)
    113             plotter = pv.Plotter()
    114             plotter.add_mesh(self.mesh, label='mesh')
--> 115             plotter.add_mesh(edges, 'r', label='edges')
    116             plotter.show()
    117 

~/anaconda3/envs/test/lib/python3.7/site-packages/pyvista/plotting/plotting.py in add_mesh(self, mesh, color, style, scalars, clim, show_edges, edge_color, point_size, line_width, opacity, flip_scalars, lighting, n_colors, interpolate_before_map, cmap, label, reset_camera, scalar_bar_args, show_scalar_bar, stitle, multi_colors, name, texture, render_points_as_spheres, render_lines_as_tubes, smooth_shading, ambient, diffuse, specular, specular_power, nan_color, nan_opacity, loc, backface_culling, rgb, categories, use_transparency, below_color, above_color, annotations, pickable, **kwargs)
    804 
    805         if mesh.n_points < 1:
--> 806             raise RuntimeError('Empty meshes cannot be plotted. Input mesh has zero points.')
    807 
    808         # Try to plot something if no preference given

RuntimeError: Empty meshes cannot be plotted. Input mesh has zero points.


I have run this now on linux and osx and get the same errors

print(pv.Report('pymeshfix'))                                                                                                                                             

--------------------------------------------------------------------------------
  Date: Fri Sep 20 16:36:00 2019 CDT

             Linux : OS
                12 : CPU(s)
            x86_64 : Machine
             64bit : Architecture
           31.2 GB : RAM
           IPython : Environment

  Python 3.7.4 (default, Aug 13 2019, 20:35:49)  [GCC 7.3.0]

            0.13.2 : pymeshfix
            0.22.2 : pyvista
             8.1.2 : vtk
            1.16.5 : numpy
             2.5.0 : imageio
             1.4.3 : appdirs
             0.4.3 : scooby
             3.1.1 : matplotlib
             5.9.2 : PyQt5
             7.8.0 : IPython
             7.5.1 : ipywidgets

  Intel(R) Math Kernel Library Version 2019.0.4 Product Build 20190411 for
  Intel(R) 64 architecture applications
--------------------------------------------------------------------------------

Pymeshfix incompatible with numpy>=1.20

Pymeshfix crashes in the following way when installed with windows, python=3.9 and numpy>=1.20 (Tried with numpy 1.20 and 1.21.6). A similar problem occured here, but they solved the problem by upgrading to 1.20, which is already the case here. Numpy seems to have a change in C API with 1.20 which probably causes the problem.

  1. conda create -n pmfbug python=3.9
  2. conda activate pmfbug
  3. pip install python==1.20
  4. pip install pymeshfix
  5. python
  6. import pymeshfix
(pmfbug) C:\Users\lfranz\PycharmProjects\follicle-tracker>python
Python 3.9.13 | packaged by conda-forge | (main, May 27 2022, 16:51:29) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymeshfix
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\lfranz\Anaconda3\envs\pmffix\lib\site-packages\pymeshfix\__init__.py", line 1, in <module>
    from pymeshfix.meshfix import *
  File "C:\Users\lfranz\Anaconda3\envs\pmffix\lib\site-packages\pymeshfix\meshfix.py", line 7, in <module>
    from pymeshfix import _meshfix
  File "pymeshfix\cython\_meshfix.pyx", line 1, in init pymeshfix._meshfix
ValueError: numpy.ndarray size changed, may indicate binary incompatibility. Expected 96 from C header, got 88 from PyObject

numpy.ufunc size changed

On debian, python 2.7 and 3.5, installed with pip I get the following error:

----> 8 from pymeshfix import _meshfix
init.pxd in init pymeshfix._meshfix()

ValueError: numpy.ufunc size changed, may indicate binary incompatibility. Expected 216 from C header, got 192 from PyObject

Better error message on instantiation

def __init__(self, *args):
""" initializes MeshFix """
if isinstance(args[0], pv.PolyData):
mesh = args[0]
self.v = mesh.points
faces = mesh.faces
if faces.size % 4:
raise Exception('Invalid mesh. Must be an all triangular mesh.')
self.f = np.ascontiguousarray(faces.reshape(-1 , 4)[:, 1:])
elif isinstance(args[0], np.ndarray):
self.load_arrays(args[0], args[1])
else:
raise Exception('Invalid input')

Should we include a more user-friendly error message here?

Because if we pass a PyVista mesh that isn't PolyData, then this error gets thrown... this could be very confusing for a new user.

Also, what if we added a catch to automatically cast things like UnstructuredGrids to PolyData and use a .tri_filter to ensure it is a triangular mesh?

.extract_geometry().tri_filter()

Thoughts, @akaszynski?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.