STL转12视图

conda create -n transform python=3.6
pip install numpy-stl
pip install matplotlib==2.2.3
pip install Pillow
import numpy as np
from PIL import Image, ImageChops
from os import path, makedirs
from stl import mesh
from mpl_toolkits import mplot3d
from matplotlib import pyplot as plt

def get_trim_image(data):
    def trim(im, border):
        bg = Image.new(im.mode, im.size, border)
        diff = ImageChops.difference(im, bg)
        bbox = diff.getbbox()
        if bbox:
            return im.crop(bbox)

    image = Image.fromarray(data)
    image.thumbnail((500, 500), Image.ANTIALIAS)
    return trim(image, (255, 255, 255))

class Mesh_to_Image:
    def __init__(self, image_folder='data_train', files_list='file_list.txt'):
        if not path.exists(image_folder):
            makedirs(image_folder)
        self.image_folder = image_folder
        self.files_list = files_list
        self.generate_Image()

    def generate_Image(self):
        file_no = 0
        files = open(self.files_list, 'r')
        for file in files:
            file_no += 1
            file_path = file.strip()
            self.file_name, exe = path.splitext(file_path)
            print(f"{file_no} {self.file_name}{exe}")

            figure = plt.figure(figsize=(10, 10))
            axes = mplot3d.Axes3D(figure)

            Mesh = mesh.Mesh.from_file(file_path)
            axes.add_collection3d(mplot3d.art3d.Poly3DCollection(Mesh.vectors, edgecolor='k'))

            scale = Mesh.points.flatten('C')
            axes.auto_scale_xyz(scale, scale, scale)
            axes.set_axis_off()

            for angle_no, angle in enumerate(range(0, 360, 30), start=1):
                axes.view_init(30, angle)

                file_base_name, _ = path.splitext(path.basename(file_path))
                folder_path = path.join(self.image_folder, file_base_name)
                file_name = f"{angle_no}.png"
                image_file_path = path.join(folder_path, file_name)

                if not path.exists(folder_path):
                    makedirs(folder_path)

                figure.canvas.draw()
                data = np.fromstring(figure.canvas.tostring_rgb(), dtype=np.uint8, sep='')
                data = data.reshape(figure.canvas.get_width_height()[::-1] + (3,))
                image = get_trim_image(data)
                image.save(image_file_path)
                print(f"{file_no}, {angle_no} >> {image_file_path}  Done!")

if __name__ == "__main__":
    Mesh_to_Image(image_folder='Data_lfd', files_list='train.txt')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值