0

从一个复杂的 3D 形状中,我通过 tricontourf 获得了我的形状的等效顶视图

我现在希望将此结果导出到二维数组上。我试过这个:

import numpy as np
from shapely.geometry import Polygon
import skimage.draw as skdraw
import matplotlib.pyplot as plt

x = [...]
y = [...]
z = [...]
levels = [....]

cs = plt.tricontourf(x, y, triangles, z, levels=levels)

image = np.zeros((100,100))

for i in range(len(cs.collections)):
    p = cs.collections[i].get_paths()[0]
    v = p.vertices
    x = v[:,0]
    y = v[:,1]
    z = cs.levels[i]

    # to see polygon at level i
    poly = Polygon([(i[0], i[1]) for i in zip(x,y)])
    x1, y1 = poly.exterior.xy
    plt.plot(x1,y1)
    plt.show()


    rr, cc = skdraw.polygon(x, y)
    image[rr, cc] = z

plt.imshow(image)
plt.show()

但不幸的是,从轮廓顶点只创建一个多边形(我认为),最后在我的二维数组中生成我的轮廓的不正确投影。

您是否有想法在二维数组中正确表示轮廓?

4

1 回答 1

0

考虑到 Andreas 建议的在 ...get_paths() 中使用 for path 的内部循环,情况会更好......但不是完全固定的。我的代码现在是:

import numpy as np
import matplotlib.pyplot as plt
import cv2

x = [...]
y = [...]
z = [...]
levels = [....]
...

cs = plt.tricontourf(x, y, triangles, z, levels=levels)

nbpixels = 1024
image = np.zeros((nbpixels,nbpixels))
pixel_size = 0.15 # relation between a pixel and its physical size

for i,collection in enumerate(cs.collections):
    z = cs.levels[i]
    for path in collection.get_paths():
        verts = path.to_polygons()
        for v in verts:
            v = v/pixel_size+0.5*nbpixels # to centered and convert vertices in physical space to image pixels 
            poly = np.array([v], dtype=np.int32) # dtype integer is necessary for the next instruction
            cv2.fillPoly( image, poly, z )

最终图像与原始图像相差不远(由 plt.contourf 返回)。

不幸的是,一些空白的小空间仍然保留在最终图像中。(见轮廓和最终图像)

path.to_polygons() 对此负责吗?(仅考虑大小> 2 的数组来构建多边形,忽略“交叉”多边形并通过孤立的单个像素??)。

于 2016-06-08T09:46:52.407 回答