Giter VIP home page Giter VIP logo

pymeshfix's Introduction

PyVista

3D plotting and mesh analysis through a streamlined interface for the Visualization Toolkit (VTK)

pyvista

PyVista is:

  • Pythonic VTK: a high-level API to the Visualization Toolkit (VTK)
  • mesh data structures and filtering methods for spatial datasets
  • 3D plotting made simple and built for large/complex data geometries

PyVista is a helper module for the Visualization Toolkit (VTK) that wraps the VTK library through NumPy and direct array access through a variety of methods and classes. This package provides a Pythonic, well-documented interface exposing VTK's powerful visualization backend to facilitate rapid prototyping, analysis, and visual integration of spatially referenced datasets.

This module can be used for scientific plotting for presentations and research papers as well as a supporting module for other mesh 3D rendering dependent Python modules; see Connections for a list of projects that leverage PyVista.

Share this project on X: tweet

PyVista is a NumFOCUS affiliated project

NumFOCUS affiliated projects

Status badges

Deployment pypi conda
Build Status GH-CI python pre-commit.ci status
Metrics codacy codecov
Activity PyPIact condaact
Citation joss zenodo
License MIT
Community slack discuss
Formatter black isort prettier
Linter Ruff
Affiliated NumFOCUS Affiliated
Mentioned Awesome Scientific Computing

Highlights

Head over to the Quick Examples page in the docs to explore our gallery of examples showcasing what PyVista can do. Want to test-drive PyVista? All of the examples from the gallery are live on MyBinder for you to test drive without installing anything locally: Launch on Binder

Overview of Features

  • Extensive gallery of examples (see Quick Examples)
  • Interactive plotting in Jupyter Notebooks with server-side and client-side rendering with trame.
  • Filtering/plotting tools built for interactivity (see Widgets)
  • Direct access to mesh analysis and transformation routines (see Filters)
  • Intuitive plotting routines with matplotlib similar syntax (see Plotting)
  • Import meshes from many common formats (use pyvista.read()). Support for all formats handled by meshio is built-in.
  • Export meshes as VTK, STL, OBJ, or PLY (mesh.save()) file types or any formats supported by meshio (pyvista.save_meshio())

Documentation

Refer to the documentation for detailed installation and usage details.

For general questions about the project, its applications, or about software usage, please create a discussion in pyvista/discussions where the community can collectively address your questions. You are also welcome to join us on Slack.

Installation

PyVista can be installed from PyPI using pip on Python >= 3.8:

pip install pyvista

You can also visit PyPI, Anaconda, or GitHub to download the source.

See the Installation for more details regarding optional dependencies or if the installation through pip doesn't work out.

Connections

PyVista is a powerful tool that researchers can harness to create compelling, integrated visualizations of large datasets in an intuitive, Pythonic manner.

Learn more about how PyVista is used across science and engineering disciplines by a diverse community of users on our Connections page.

Authors

Please take a look at the contributors page and the active list of authors to learn more about the developers of PyVista.

contrib.rocks

Made with contrib rocks.

Contributing

Contributor Covenant Code Triage Open in GitHub Codespaces

We absolutely welcome contributions and we hope that our Contributing Guide will facilitate your ability to make PyVista better. PyVista is mostly maintained on a volunteer basis and thus we need to foster a community that can support user questions and develop new features to make this software a useful tool for all users while encouraging every member of the community to share their ideas. To learn more about contributing to PyVista, please see the Contributing Guide and our Code of Conduct.

Citing PyVista

There is a paper about PyVista.

If you are using PyVista in your scientific research, please help our scientific visibility by citing our work.

Sullivan and Kaszynski, (2019). PyVista: 3D plotting and mesh analysis through a streamlined interface for the Visualization Toolkit (VTK). Journal of Open Source Software, 4(37), 1450, https://doi.org/10.21105/joss.01450

BibTex:

@article{sullivan2019pyvista,
  doi = {10.21105/joss.01450},
  url = {https://doi.org/10.21105/joss.01450},
  year = {2019},
  month = {May},
  publisher = {The Open Journal},
  volume = {4},
  number = {37},
  pages = {1450},
  author = {Bane Sullivan and Alexander Kaszynski},
  title = {{PyVista}: {3D} plotting and mesh analysis through a streamlined interface for the {Visualization Toolkit} ({VTK})},
  journal = {Journal of Open Source Software}
}

Professional Support

While PyVista is an Open Source project with a big community, you might be looking for professional support. This section aims to list companies with VTK/PyVista expertise who can help you with your software project.

Company Name Kitware Inc.
Description Kitware is dedicated to build solutions for our customers based on our well-established open source platforms.
Expertise CMake, VTK, PyVista, ParaView, Trame
Contact https://www.kitware.com/contact/

pymeshfix's People

Contributors

akaszynski avatar banesullivan 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

pymeshfix's Issues

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!

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 ..

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

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.

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.

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?

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
!

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)

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?

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?

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

[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

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)

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
--------------------------------------------------------------------------------

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

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().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.

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.

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

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

Installation error

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

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

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

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
--------------------------------------------------------------------------------

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!

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.

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

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 :)

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?

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

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?

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.

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.

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

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.