简体   繁体   English

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

[英]Python : How to export a contourf to a 2D array?

From a complex 3D shape, I have obtained by tricontourf the equivalent top view of my shape. 从一个复杂的3D形状中,我通过tricontourf获得了我的形状的等效俯视图

I wish now to export this result on a 2D array. 我现在希望将此结果导出到2D数组中。 I have tried this : 我已经试过了:

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

but unfortunately, from contours vertices only one polygon is created by level (I think), generated at the end an incorrect projection of my contourf in my 2D array. 但是不幸的是,根据等高线(按我的想法),只能从等高线顶点创建一个多边形,最后在我的2D数组中生成了我的轮廓线不正确的投影

Do you have an idea to correctly represent contourf in a 2D array ? 您是否有想法在2D数组中正确表示Contourf?

Considering a inner loop with for path in ...get_paths() as suggested by Andreas, things are better ... but not completely fixed . 考虑到Andreas建议的在... get_paths()中使用for路径的内部循环,情况会好一些,但并不能完全固定 My code is now : 我的代码现在是:

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 )

The final image is not so far from the original one (retunred by plt.contourf). 最终图像与原始图像相距不远(由plt.contourf还原)。

Unfortunately, some empty little spaces still remains in the final image. 不幸的是,最终图像中仍然留有一些空的小空间。 (see contourf and final image) (请参见contourf和最终图像)

Is path.to_polygons() responsible for that ? 是path.to_polygons()负责吗? (considering only array with size > 2 to build polygons, ignoring 'crossed' polygons and passing through isolated single pixels ??). (仅考虑大小大于2的数组以构建多边形,忽略“交叉”多边形并通过孤立的单个像素??)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM