【AI赋能工作流】一个程序员的自白:我如何利用大语言模型将工作效率提升50%翻译 ChatGPT 会话 之 033 Create Cube STL
写在前面
- C++很难吧
- STL 的书汗牛充栋了吧
- 但是好像也不是完全不行呀
Create Cube STL
July 8, 2024
https://chatgpt.com/share/7e9bdcab-dba8-4b68-8742-877be9f1cc7e
Create Cube STL
🧑🦰User
1 | I want to generate an STL file with the following type |
🤖 Assistant
一个立方体的 STL 文件包含 12 个三角形(每个面由 2 个三角形组成)。
在生成 STL 文件之前,我们需要确定立方体的尺寸和位置。为了简化,我选择一个中心在原点、边长为 2 个单位的立方体。
以下是 STL 文件的内容:
1 | B: ( 1, -1, -1) |
Here’s the STL file:
1 | // Bottom Face |
每个面的法线方向取决于该面的朝向。每个面由两个三角形构成。这种 STL 文件使用 ASCII STL 格式,可以兼容大多数 STL 查看器和 3 D 打印机。如果需要更紧凑的表示,可以使用二进制 STL 格式。
🧑🦰User
现在我们进行程序化处理。我有一个名为 “img. Png” 的二维图像,其中像素有明暗之分。如果像素是亮的,我想在该位置生成一个小立方体;如果是暗的,则不生成。请编写一个 python 程序实现这一功能。
以下是一个生成立方体的函数:
1 | def generate_cube(x, y, z, size=1): |
接下来,如果图像中一列的像素值为 1,则生成立方体。
🤖 Assistant
当然!为了从图像生成 STL 文件,可以在每个亮像素的位置生成立方体。首先需要将图像转换为灰度并进行阈值处理,以创建一个由亮暗像素组成的二值矩阵。对于每个亮像素,我们生成立方体的顶点,并将生成的三角形添加到 STL 数据中。
generate_cube
函数生成立方体的顶点,并提供构成立方体面的索引。不过,由于 STL 格式使用三角形表示面,所以我们需要将每个四边形分解为两个三角形。
我已经修改并完成了 image_to_stl
函数:
1 | from PIL import Image |
This script utilizes the PIL
library from Pillow
to handle image operations. Make sure you have Pillow
installed:
1 | pip install Pillow |
Remember that the generated STL will have cubes for every light pixel in the image. Depending on the image resolution and the cube size, the resulting STL file could be large. Adjust the
cube_size` parameter to change the size of the generated cubes.
🧑🦰User
1 | I want to not make too many extra faces. If two pixels are adjacent and are both 1 make only one box. I don't want an approximation I want to merge only if it's exact. |
🤖 Assistant
If you want to merge adjacent cubes into a larger block, then you need a different approach. Essentially, you’d like to merge regions of adjacent light pixels into larger rectangles. This process can be likened to image segmentation, where we group connected components of light pixels.
The most straightforward method to achieve this is by performing a flood fill for each light pixel, and then marking those pixels as visited. This way, we’d determine the bounding box of each group of adjacent light pixels.
Once we determine these bounding boxes, we can generate cubes (or rather, rectangular prisms) based on these bounding boxes.
Here’s how this can be done:
1 | from PIL import Image |
This code takes an image and generates an STL where each region of light pixels gets transformed into a single rectangular prism. Adjacent light pixels are merged into larger blocks, reducing the number of generated faces.
🧑🦰User
1 | Compute the outer combination of [1, 2, 4, 8, 16[ with itself using itertools |
🤖 Assistant
You can use the product
function from itertools
to compute the outer combination (or outer product) of a list with itself. Here’s how you can achieve this with your list:
1 | import itertools |
This will produce a list of tuples where each tuple contains a combination from the list with itself.