Python:如何将contourf导出到2D数组?

时间:2016-06-03 14:57:48

标签: python matplotlib contourf

从复杂的3D形状中,我通过tricontourf获得了我的形状的等效top view

我现在希望在2D数组上导出此结果。 我试过这个:

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()

但不幸的是,从轮廓顶点开始,只有一个多边形由水平(我认为)创建,在我的2D数组中在contourf的末尾an incorrect projection生成。

您是否有想法在2D数组中正确表示contourf?

1 个答案:

答案 0 :(得分:0)

考虑到安德烈亚斯建议的内部循环 for path in ... get_paths(),事情会更好......但并非完全修复。 我的代码现在是:

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重新发布)。

不幸的是,最终图像中仍然存在一些空的小空格。(see contourf and final image)

path.to_polygons()是否对此负责? (仅考虑大小> 2的阵列来构建多边形,忽略'交叉'多边形并通过孤立的单个像素?)。