python - 在python中的3D numpy数组中绘制三角形

标签 python arrays numpy 3d

假设我有一个具有某种形状的 3D 数组(矩形长方体),例如 (48, 32, 64)。我在这个立方体中有 3 个点和一些坐标。 x1 = (10, 20, 30) x2 = (21, 15, 34) x3 = (33, 1, 62)

我需要在这个受这些点限制的 3D 数组中绘制填充平面,例如在 3D 数组中绘制三角形。在 2D 情况下,我们可以使用 openCV 来完成: Triangle Filling in opencv

import numpy as np
a = np.zeros((48, 32, 64), dtype=np.uint8)
x1 = (10, 20, 30)
x2 = (21, 15, 34)
x3 = (33, 1, 62)
a = draw_3D_triangle(a, x1, x2, x3)

但是在 3D 情况下最简单的方法是什么?

最佳答案

(已编辑:我之前忘记包含 full_triangle() 的代码)。


假设您有一个画线的算法,例如 Bresenham's Algorithm并假设它可以推广到 N-dim 情况。

幸运的是raster-geometry包中有这样一个 Bresenham 算法的 N-dim 实现。

(免责声明:我是该软件包的主要作者。)

设A、B、C为三角形ABC的顶点坐标。


如果您只需要绘制外部形状,您可以只使用使用点的各种组合来形成线的算法:AB、BC、CA。

在代码中,这将是:

import numpy as np
import raster_geometry as rg


a, b, c = (1, 1), (3, 7), (6, 4)
coords = set(rg.bresenham_lines((a, b, c), closed=True))
print(coords)
# {(1, 2), (6, 4), (3, 2), (4, 6), (5, 5), (2, 2), (2, 3), (3, 6), (2, 4), (4, 3), (3, 7), (2, 5), (1, 1), (5, 3)}
arr = rg.render_at((10, 10), coords)
print(arr.astype(int))
# [[0 0 0 0 0 0 0 0 0 0]
#  [0 1 1 0 0 0 0 0 0 0]
#  [0 0 1 1 1 1 0 0 0 0]
#  [0 0 1 0 0 0 1 1 0 0]
#  [0 0 0 1 0 0 1 0 0 0]
#  [0 0 0 1 0 1 0 0 0 0]
#  [0 0 0 0 1 0 0 0 0 0]
#  [0 0 0 0 0 0 0 0 0 0]
#  [0 0 0 0 0 0 0 0 0 0]
#  [0 0 0 0 0 0 0 0 0 0]]

如果你需要画一个完整的三角形,你可以这样做:

  • 从A点到B点画一条线
  • 从 C 到 AB 线上的一点画一条线,对于线上的每个点。

虽然这可能不是最有效的方法,但它会工作得相当好。 顶点附近的一些点可能会被遗漏。 在这种情况下,重复相同的过程循环遍历所有三个顶点就足够了。

在代码中,这可以是:

import numpy as np
import raster_geometry as rg


def full_triangle(a, b, c):
    ab = rg.bresenham_line(a, b, endpoint=True)
    for x in set(ab):
        yield from rg.bresenham_line(c, x, endpoint=True)


a, b, c = (1, 1), (3, 7), (6, 4)
coords = set(full_triangle(a, b, c))
print(coords)
# {(1, 2), (6, 4), (5, 4), (3, 2), (3, 3), (5, 5), (4, 6), (4, 5), (4, 4), (1, 1), (2, 3), (4, 3), (2, 2), (3, 6), (3, 7), (2, 5), (5, 3), (3, 4), (2, 4), (3, 5)}
arr = rg.render_at((10, 10), coords)
print(arr.astype(int))
# [[0 0 0 0 0 0 0 0 0 0]
#  [0 1 1 0 0 0 0 0 0 0]
#  [0 0 1 1 1 1 0 0 0 0]
#  [0 0 1 1 1 1 1 1 0 0]
#  [0 0 0 1 1 1 1 0 0 0]
#  [0 0 0 1 1 1 0 0 0 0]
#  [0 0 0 0 1 0 0 0 0 0]
#  [0 0 0 0 0 0 0 0 0 0]
#  [0 0 0 0 0 0 0 0 0 0]
#  [0 0 0 0 0 0 0 0 0 0]]

请注意,虽然示例是二维的,但它们适用于 N-dim。 例如,您所追求的 3D 三角形可以通过以下方式生成:

x1 = (10, 20, 30)
x2 = (21, 15, 34)
x3 = (33, 1, 62)
coords = set(full_triangle(x1, x2, x3))
arr = rg.render_at((48, 32, 64), coords)

关于python - 在python中的3D numpy数组中绘制三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60901888/

相关文章:

python - L和H之间的幸运数字怎么算?

python - 为什么 .rstrip() 有时有效但有时无效?

c - C语言中如何遍历二维数组对角线?

c - 可以使用位运算符检查数字是否在数组中

python - PDF 响应在 Python 3 中损坏但在 Python 2 中有效

python - 计算连续 "stream"图像中颜色变化的索引

c - 查找数组中第一个非整数实例

python - 在 numpy 和 python 中快速删除重复项

python - 如何以二进制表示模式打印 numpy 数组

python - 数据帧转换后保留标题