【问题标题】:Python : How to export a contourf to a 2D array?Python:如何将轮廓导出到二维数组?
【发布时间】:2016-06-03 14:57:48
【问题描述】:

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

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

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 数组中轮廓的末尾 an incorrect projection 生成。

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

【问题讨论】:

  • 您想将轮廓表示为矩形数组中的数字吗?将 NaN 分配给您所在区域以外的值?
  • 如果我没记错的话,cs.collections[i].get_paths() 返回一个对应于级别i 的轮廓线段的列表。这与您仅引用...get_paths()[0] 一致。您可能必须循环 for path in ...get_paths() 并独立绘制每条路径。但请注意:可能存在开放的等高线,因此像这样使用Polygon 可能不正确(这可能会解释图中的虚假线)。我建议使用带有简单轮廓线的简单示例函数来了解这些事情是如何在幕后完成的。
  • @nicoguaro :我无法在我的区域之外分配价值,因为我不知道先验。
  • @Andreas : 越来越好(见下文)

标签: python matplotlib contourf


【解决方案1】:

考虑到 Andreas 建议的 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 的数组来构建多边形,忽略“交叉”多边形并通过孤立的单个像素??)。

【讨论】:

    猜你喜欢
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 2011-09-14
    • 2015-10-27
    • 1970-01-01
    • 2016-03-10
    相关资源
    最近更新 更多