Image and Voronoi diagram on the same figure

丶灬走出姿态 提交于 2021-02-08 07:59:25

问题


I need to plot a Voronoi tessellation on top of an existing image using scipy.spatial.Voronoi. I have imported an image as a numpy array using matplotlib.pyplot:

img_file = 'my_image.png'
img = plt.imread(os.path.join(data_dir, img_file))
fig = plt.figure()
ax = fig.add_subplot(111)

When I display the image it works ok:

ax.imshow(img)

my initial image

Then I want to add a Voronoi graph (for some points I choose arbitrarily) on it so I do:

points = np.array([[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]])

vor = Voronoi(points)
voronoi_plot_2d(vor, ax=ax)
plt.show()

and I get this: Failed attempt to overlay the graph on the image

And when I plot just the graph this is what I get: Voronoi tessellation separately

So, I wanted to draw them on top of each other by using the same axis (ax) but this ended up coloring in the regions of Voronoi instead. Any help with figuring out how to have the image on the background and the Voronoi on top would be much appreciated!


回答1:


It actually works, i guess the voronoi points need to be chosen properly:

import matplotlib.pylab as plt
import numpy as np
from scipy.spatial import Voronoi, voronoi_plot_2d
import scipy.ndimage as ndimage

img_file = 'bear.png'
img = plt.imread(img_file)

points = [] 
for i in range(100):
    points.append([np.random.uniform(0, img.shape[0]),np.random.uniform(0, img.shape[1])])
points = np.array(points)

vor = Voronoi(points)

fig = plt.figure(figsize=(20,20))
ax = fig.add_subplot(111)
ax.imshow(ndimage.rotate(img, 90))
voronoi_plot_2d(vor, point_size=10, ax=ax)
plt.show()



来源:https://stackoverflow.com/questions/52184271/image-and-voronoi-diagram-on-the-same-figure

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