Python : How to export a contourf to a 2D array?

坚强是说给别人听的谎言 提交于 2020-01-06 08:15:32

问题


From a complex 3D shape, I have obtained by tricontourf the equivalent top view of my shape.

I wish now to export this result on a 2D array. 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.

Do you have an idea to correctly represent contourf in a 2D array ?


回答1:


Considering a inner loop with for path in ...get_paths() as suggested by Andreas, things are better ... but not completely fixed. 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).

Unfortunately, some empty little spaces still remains in the final image.(see contourf and final image)

Is path.to_polygons() responsible for that ? (considering only array with size > 2 to build polygons, ignoring 'crossed' polygons and passing through isolated single pixels ??).



来源:https://stackoverflow.com/questions/37617623/python-how-to-export-a-contourf-to-a-2d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!