-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdepth_map_to_stl,_2.py
70 lines (48 loc) · 2.36 KB
/
depth_map_to_stl,_2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# -*- coding: utf-8 -*-
"""Depth map to STL, 2.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1dttpXakpLFlKuMk8byAOl_zry5MvpCmK
Depth Map to STL
Uses numpy-stl to create files
Each square of four pixels is divided into two triangles
Processing time is ~2min per megapixel
Project is at https://github.com/BillFSmith/depth_map_to_stl
Example depth map from https://johnflower.org/sites/default/files/2018-07/08-new-plymouth-15m-dem-n-mt-taranaki_5.png
"""
#@title Press Ctrl + F9 to run code
print("Depth maps only show relative depth, so the division of the maximum depth and the width of the image is needed.")
print("E.g. an object that is 10cm tall and 20cm wide, the value would be 0.5")
height_div_width = input('Enter desired value for image depth/width: ')
print('')
print("Upload depth maps:")
from google.colab import files
uploaded = files.upload()
!pip install numpy-stl
import numpy as np
from stl import mesh
import cv2
file_names = list(uploaded.keys())
for file_name in file_names:
im = cv2.imread(file_name, cv2.IMREAD_UNCHANGED)
im_array = np.array(im) #.transpose((1, 0, 2))
im_array = np.rot90(im_array, -1, (0,1))
mesh_size = [im_array.shape[0],im_array.shape[1]]
mesh_max = np.max(im_array)
if len(im_array.shape) == 3:
scaled_mesh = mesh_size[0] * float(height_div_width) * im_array[:,:,0] / mesh_max
else:
scaled_mesh = mesh_size[0] * float(height_div_width) * im_array / mesh_max
# rand_mesh = np.random.rand(mesh_size[0],mesh_size[1])
mesh_shape = mesh.Mesh(np.zeros((mesh_size[0] - 1) * (mesh_size[1] - 1) * 2, dtype=mesh.Mesh.dtype))
for i in range(0, mesh_size[0]-1):
for j in range(0, mesh_size[1]-1):
mesh_num = i * (mesh_size[1]-1) + j
mesh_shape.vectors[2 * mesh_num][2] = [i, j, scaled_mesh[i,j]]
mesh_shape.vectors[2 * mesh_num][1] = [i, j+1, scaled_mesh[i,j+1]]
mesh_shape.vectors[2 * mesh_num][0] = [i+1, j, scaled_mesh[i+1,j]]
mesh_shape.vectors[2 * mesh_num + 1][0] = [i+1, j+1, scaled_mesh[i+1,j+1]]
mesh_shape.vectors[2 * mesh_num + 1][1] = [i, j+1, scaled_mesh[i,j+1]]
mesh_shape.vectors[2 * mesh_num + 1][2] = [i+1, j, scaled_mesh[i+1,j]]
mesh_shape.save(str(file_name) + '.stl')
files.download(str(file_name) + '.stl')