├── LICENSE.txt ├── Readme.md ├── images ├── 3d-sinusoidal_meshlab.png ├── jupyter_notebook_image1.png ├── jupyter_notebook_image2.png └── mobius_meshlab.png ├── surf2stl-python_example.ipynb └── surf2stl.py /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright 2020 asahidari 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # Surf2stl.py 2 | 3 | Export a surface to a STL(Stereolithography) file. 4 | 5 | ## Description 6 | Functions in this script (write, tri_write) can export 3d surface to a STL (Stereolithography) format file. This is the python version of [surf2stl.m](https://jp.mathworks.com/matlabcentral/fileexchange/4512-surf2stl) in MATLAB (or Octave). 7 | 8 | Exported files can be imported in various 3d software tools (like Blender, Meshlab, etc.) 9 | 10 | ## Installation 11 | clone this repository 12 | 13 | ```Bash 14 | git clone https://github.com/asahidari/surf2stl-python 15 | ``` 16 | 17 | ## Usage 18 | Write python script like this: 19 | 20 | ```python 21 | import numpy as np 22 | import surf2stl 23 | 24 | x = np.linspace(-6, 6, 30) 25 | y = np.linspace(-6, 6, 30) 26 | X, Y = np.meshgrid(x, y) 27 | Z = np.sin(np.sqrt(X ** 2 + Y ** 2)) 28 | 29 | surf2stl.write('3d-sinusoidal.stl', X, Y, Z) 30 | ``` 31 | 32 | Or like this: 33 | 34 | ```python 35 | import numpy as np 36 | from scipy.spatial import Delaunay 37 | import surf2stl 38 | 39 | u = np.linspace(0, 2.0 * np.pi, endpoint=True, num=50) 40 | v = np.linspace(-0.5, 0.5, endpoint=True, num=10) 41 | u, v = np.meshgrid(u, v) 42 | u, v = u.flatten(), v.flatten() 43 | 44 | x = (1 + 0.5 * v * np.cos(u / 2.0)) * np.cos(u) 45 | y = (1 + 0.5 * v * np.cos(u / 2.0)) * np.sin(u) 46 | z = 0.5 * v * np.sin(u / 2.0) 47 | 48 | delaunay_tri = Delaunay(np.array([u, v]).T) 49 | surf2stl.tri_write('mobius.stl', x, y, z, delaunay_tri) 50 | ``` 51 | 52 | If you use jupyter notebook, 53 | 'Surf2stl-python_example.ipynb' shows the examples with 3d graphs in matplotlib. 54 | 55 | ![jupyter_notebook_image1](images/jupyter_notebook_image1.png) 56 | ![meshlab_image1](images/3d-sinusoidal_meshlab.png) 57 | ![jupyter_notebook_image2](images/jupyter_notebook_image2.png) 58 | ![meshlab_image2](images/mobius_meshlab.png) 59 | 60 | 61 | ## Requirement 62 | - Python 3 63 | - numpy 64 | - scipy 65 | - matplotlib (to draw graph in python) 66 | 67 | ## Author 68 | asahidari 69 | 70 | ## License 71 | MIT 72 | -------------------------------------------------------------------------------- /images/3d-sinusoidal_meshlab.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iitrabhi/surf2stl-python/ba0d85fe2f95301ec2ba50bd3dec5cf85258abf1/images/3d-sinusoidal_meshlab.png -------------------------------------------------------------------------------- /images/jupyter_notebook_image1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iitrabhi/surf2stl-python/ba0d85fe2f95301ec2ba50bd3dec5cf85258abf1/images/jupyter_notebook_image1.png -------------------------------------------------------------------------------- /images/jupyter_notebook_image2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iitrabhi/surf2stl-python/ba0d85fe2f95301ec2ba50bd3dec5cf85258abf1/images/jupyter_notebook_image2.png -------------------------------------------------------------------------------- /images/mobius_meshlab.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iitrabhi/surf2stl-python/ba0d85fe2f95301ec2ba50bd3dec5cf85258abf1/images/mobius_meshlab.png -------------------------------------------------------------------------------- /surf2stl.py: -------------------------------------------------------------------------------- 1 | ### surf2stl.py --- Write a surface to a STL format file --- 2 | 3 | ### Copyright (c) 2020 asahidari 4 | 5 | ### This software is released under the MIT License. 6 | ### http://opensource.org/licenses/mit-license.php 7 | 8 | ### Functions in this script (write, tri_write) export 9 | ### a stereolithography (STL) file for a surface with geometry 10 | ### defined by three matrix arguments, X, Y and Z. 11 | 12 | ### This idea mainly come from surf2stl.m in MATLAB(or Octave): 13 | ### https://jp.mathworks.com/matlabcentral/fileexchange/4512-surf2stl 14 | 15 | import numpy as np 16 | import datetime 17 | import math 18 | from scipy.spatial import Delaunay 19 | import struct 20 | 21 | def write(filename, x, y, z, mode='binary'): 22 | """ 23 | Write a stl file for a surface with geometry 24 | defined from three matrix arguments, x, y, and z. 25 | Meshes are triangulated sequencially along xyz order. 26 | 27 | Parameters 28 | ---------- 29 | filename : string 30 | output file name 31 | 32 | x, y, z : ndarray 33 | Arguments x, y can be 1-dimensional arrays or 2-dimensional grids 34 | (usually generated by np.meshgrid(x,y)), and z must be 2-dimensional, 35 | which must have len(x)=n, len(y)=m where z.shape[m,n]. 36 | 37 | mode : string 38 | STL file format, 'ascii' or 'binary'(default). 39 | 40 | Examples 41 | ---------- 42 | import numpy as np 43 | import surf2stl 44 | 45 | x = np.linspace(-6, 6, 30) 46 | y = np.linspace(-6, 6, 30) 47 | X, Y = np.meshgrid(x, y) 48 | Z = np.sin(np.sqrt(X ** 2 + Y ** 2)) 49 | 50 | surf2stl.write('3d-sinusoidal.stl', X, Y, Z) 51 | 52 | """ 53 | 54 | if type(filename) is not str: 55 | raise Exception('Invalid filename') 56 | 57 | if mode != 'ascii': 58 | mode = 'binary' 59 | 60 | if z.ndim != 2: 61 | raise Exception('Variable z must be a 2-dimensional array') 62 | 63 | ### x, y can not be used as dx, dy in Python 64 | ### if arguments type of x(or y) is 'int', 65 | ### type error will raise in next 'if' block 66 | # if type(x) == int and type(y) == int: 67 | # x = np.arange(0, z.shape[1], x) 68 | # x = np.arange(0, z.shape[0], y) 69 | 70 | if len(x.shape) == 1 and x.shape[0] == z.shape[1] \ 71 | and len(y.shape) == 1 and y.shape[0] == z.shape[0]: 72 | x, y = np.meshgrid(x, y) 73 | 74 | if len(x.shape) != len(z.shape) \ 75 | or len(y.shape) != len(z.shape) \ 76 | or x.shape[1] != z.shape[1] \ 77 | or y.shape[0] != z.shape[0]: 78 | raise Exception('Unable to resolve x and y variables') 79 | 80 | nfacets = 0 81 | title_str = 'Created by surf2stl.py %s' % datetime.datetime.now().strftime('%d-%b-%Y %H:%M:%S') 82 | 83 | f = open(filename, 'wb' if mode != 'ascii' else 'w') 84 | 85 | if mode == 'ascii': 86 | f.write('solid %s\n' % title_str) 87 | else: 88 | title_str_ljust = title_str.ljust(80) 89 | # f.write(title_str_ljust.encode('utf-8')) # same as 'ascii' for alphabet characters 90 | f.write(title_str_ljust.encode('ascii')) 91 | f.write(struct.pack('i', 0)) 92 | 93 | for i in range(z.shape[0]-1): 94 | for j in range(z.shape[1]-1): 95 | p1 = np.array([x[i,j], y[i,j], z[i,j]]) 96 | p2 = np.array([x[i,j+1], y[i,j+1], z[i,j+1]]) 97 | p3 = np.array([x[i+1,j+1], y[i+1,j+1], z[i+1,j+1]]) 98 | val = local_write_facet(f, p1, p2, p3, mode) 99 | nfacets += val 100 | 101 | p1 = np.array([x[i+1,j+1], y[i+1,j+1], z[i+1,j+1]]) 102 | p2 = np.array([x[i+1,j], y[i+1,j], z[i+1,j]]) 103 | p3 = np.array([x[i,j], y[i,j], z[i,j]]) 104 | val = local_write_facet(f, p1, p2, p3, mode) 105 | nfacets += val 106 | 107 | if mode == 'ascii': 108 | f.write('endsolid %s\n' % title_str) 109 | else: 110 | f.seek(80, 0) 111 | f.write(struct.pack('i', nfacets)) 112 | 113 | f.close() 114 | 115 | print('Wrote %d facets' % nfacets) 116 | return 117 | 118 | def tri_write(filename, x, y, z, tri, mode='binary'): 119 | """ 120 | Write a stl file for a surface with geometry 121 | defined from three matrix arguments, x, y, and z 122 | with Delaunay Triangle parameter(tri). 123 | 124 | Meshes are triangulated with the 'tri' parameter 125 | usually made with parameters which determine 126 | the sequence of vertices (like [u, v]). 127 | 128 | Parameters 129 | ---------- 130 | filename : string 131 | output file name 132 | 133 | x, y, z : ndarray 134 | Each of these arguments must be 1-dimensional. 135 | 136 | tri : scipy.spatial.Delaunay 137 | Delaunay Triangulation object. 138 | When xyz coordinates are determined from other parameters(like (u, v)), 139 | this triangle faces are basically calculated with the parameters. 140 | 141 | mode : string 142 | STL file format, 'ascii' or 'binary'(default). 143 | 144 | Examples 145 | ---------- 146 | import numpy as np 147 | from scipy.spatial import Delaunay 148 | import surf2stl 149 | 150 | u = np.linspace(0, 2.0 * np.pi, endpoint=True, num=50) 151 | v = np.linspace(-0.5, 0.5, endpoint=True, num=10) 152 | u, v = np.meshgrid(u, v) 153 | u, v = u.flatten(), v.flatten() 154 | 155 | x = (1 + 0.5 * v * np.cos(u / 2.0)) * np.cos(u) 156 | y = (1 + 0.5 * v * np.cos(u / 2.0)) * np.sin(u) 157 | z = 0.5 * v * np.sin(u / 2.0) 158 | 159 | delaunay_tri = Delaunay(np.array([u, v]).T) 160 | surf2stl.tri_write('mobius.stl', x, y, z, delaunay_tri) 161 | 162 | """ 163 | 164 | if type(filename) is not str: 165 | raise Exception('Invalid filename') 166 | 167 | if mode != 'ascii': 168 | mode = 'binary' 169 | 170 | if len(x.shape) != 1 \ 171 | or len(y.shape) != 1 \ 172 | or len(z.shape) != 1: 173 | raise Exception('Each variable x,y,z must be a 1-dimensional array') 174 | 175 | if x.shape[0] != z.shape[0] \ 176 | or y.shape[0] != z.shape[0]: 177 | raise Exception('Number of x,y,z elements must be equal') 178 | 179 | nfacets = 0 180 | title_str = 'Created by surf2stl.py %s' % datetime.datetime.now().strftime('%d-%b-%Y %H:%M:%S') 181 | 182 | f = open(filename, 'wb' if mode != 'ascii' else 'w') 183 | 184 | if mode == 'ascii': 185 | f.write('solid %s\n' % title_str) 186 | else: 187 | title_str_ljust = title_str.ljust(80) 188 | # f.write(title_str_ljust.encode('utf-8')) # same as 'ascii' for alphabet characters 189 | f.write(title_str_ljust.encode('ascii')) 190 | f.write(struct.pack('i', 0)) 191 | 192 | indices = tri.simplices 193 | verts = tri.points[indices] 194 | for i in range(0, indices.shape[0], 1): 195 | p = indices[i] 196 | p1 = np.array([x[p[0]], y[p[0]], z[p[0]]]) 197 | p2 = np.array([x[p[1]], y[p[1]], z[p[1]]]) 198 | p3 = np.array([x[p[2]], y[p[2]], z[p[2]]]) 199 | val = local_write_facet(f, p1, p2, p3, mode) 200 | nfacets += val 201 | 202 | if mode == 'ascii': 203 | f.write('endsolid %s\n' % title_str) 204 | else: 205 | f.seek(80, 0) 206 | f.write(struct.pack('i', nfacets)) 207 | 208 | f.close() 209 | 210 | print('Wrote %d facets' % nfacets) 211 | return 212 | 213 | # Local subfunctions 214 | 215 | def local_write_facet(f, p1, p2, p3, mode): 216 | if np.isnan(p1).any() or np.isnan(p2).any() or np.isnan(p3).any(): 217 | return 0; 218 | 219 | n = local_find_normal(p1, p2, p3) 220 | if mode == 'ascii': 221 | f.write('facet normal %.7f %.7f %.7f\n' % (n[0], n[1], n[2])) 222 | f.write('outer loop\n') 223 | f.write('vertex %.7f %.7f %.7f\n' % (p1[0], p1[1], p1[2])) 224 | f.write('vertex %.7f %.7f %.7f\n' % (p2[0], p2[1], p2[2])) 225 | f.write('vertex %.7f %.7f %.7f\n' % (p3[0], p3[1], p3[2])) 226 | f.write('endloop\n') 227 | f.write('endfacet\n') 228 | else: 229 | f.write(struct.pack('%sf' % len(n), *n)) 230 | f.write(struct.pack('%sf' % len(p1), *p1)) 231 | f.write(struct.pack('%sf' % len(p2), *p2)) 232 | f.write(struct.pack('%sf' % len(p3), *p3)) 233 | f.write(struct.pack('h', 0)) 234 | return 1 235 | 236 | def local_find_normal(p1, p2, p3): 237 | v1 = p2 - p1 238 | v2 = p3 - p1 239 | v3 = np.cross(v1, v2) 240 | n = v3 / math.sqrt(np.sum(v3*v3)) 241 | return n 242 | 243 | --------------------------------------------------------------------------------