将图片转换为灰度图,根据灰度值确定stl文件深度。做到透光显图的效果。
效果
Python实现
# 工功能:将图片根据灰度转换为stl文件
# 作者:Oyontalas
# CSDN: https://blog.csdn.net/oyontalas
import numpy as np
from PIL import Image
from stl import mesh
def image_to_stl(image_path, stl_path, resize=1.0, pic_size=100.0, h_size=1.0, h_bias=0.2):
'''
image_path: 图片路径
stl_path: 保存stl文件路径
resize: 缩放比例
pic_size: 图片长边大小(单位mm)
h_size: 图片高度(单位mm)
h_bias: 图片高度偏移(单位mm)
'''
# Load image and convert to grayscale
img = Image.open(image_path).convert('L')
img_array = np.array(img)
# Get image dimensions
height, width = img_array.shape
# resize image
img = img.resize((int(width * resize), int(height * resize)))
# 保存图片
# img.save('resize.jpg')
img_array = np.array(img)
height, width = img_array.shape
# 将img_array的数据类型转换为浮点型
img_array = img_array.astype(np.float32)
# img_array转换到0-1之间
img_array = img_array/255.0
# img_array反向
img_array = 1 - img_array
# 设置高度
img_array = img_array*h_size
# img_array加上高度偏移
img_array = img_array + h_bias
# 选出width和height中的最大值
pic_scale = max(width, height)
# Create vertices and faces arrays
vertices = [[[[x / pic_scale * pic_size, y / pic_scale * pic_size, -1*img_array[y, x]],
[x / pic_scale * pic_size, y / pic_scale * pic_size, 0]] for x in range(width)] for y in range(height)]
# Generate faces
faces = []
# top faces
for y in range(height - 1):
for x in range(width - 1):
# Top surface faces
faces.append([(y, x, 0), (y, x+1, 0), (y+1, x, 0)])
faces.append([(y, x+1, 0), (y+1, x+1, 0), (y+1, x, 0)])
# bottom faces
faces.append([(y, x, 1), (y, x+1, 1), (y+1, x, 1)])
faces.append([(y, x+1, 1), (y+1, x+1, 1), (y+1, x, 1)])
# side faces
for y in range(height - 1):
faces.append(
[(y, width - 1, 0), (y+1, width - 1, 0), (y, width - 1, 1)])
faces.append(
[(y+1, width - 1, 0), (y, width - 1, 1), (y+1, width - 1, 1)])
faces.append([(y, 0, 0), (y, 0, 1), (y+1, 0, 0)])
faces.append([(y+1, 0, 0), (y, 0, 1), (y+1, 0, 1)])
for x in range(width - 1):
faces.append(
[(height - 1, x, 0), (height - 1, x+1, 0), (height - 1, x, 1)])
faces.append(
[(height - 1, x+1, 0), (height - 1, x+1, 1), (height - 1, x, 1)])
faces.append([(0, x, 0), (0, x, 1), (0, x+1, 0)])
faces.append([(0, x+1, 0), (0, x, 1), (0, x+1, 1)])
# Convert to numpy arrays
vertices = np.array(vertices)
faces = np.array(faces)
# Create the mesh
surface = mesh.Mesh(np.zeros(faces.shape[0], dtype=mesh.Mesh.dtype))
# print(faces.shape)
for i, f in enumerate(faces):
for j in range(3):
# print(i, j, f[j][0], f[j][1], f[j][2])
surface.vectors[i][j] = vertices[f[j][0], f[j][1], f[j][2], :]
# Save to file
surface.save(stl_path)
# 定义图片路径
image_path = 'example.jpg'
# 定义保存stl文件路径
stl_path = 'example.stl'
# Example usage
image_to_stl(image_path, stl_path, resize=1.0, pic_size=50.0, h_size=1.0,h_bias=0.3)