我需要使用scipy.spatial.Voronoi
在现有图像上绘制Voronoi曲面细分。我使用numpy
将图像导入为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)
当我显示图像时,它可以正常工作:
ax.imshow(img)
然后我想在它上面添加一个Voronoi图(对于我任意选择的一些点),所以我这样做:
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()
我明白了:Failed attempt to overlay the graph on the image
当我绘制图表时,这就是我得到的:Voronoi tessellation separately
因此,我想通过使用相同的轴(ax
)将它们绘制在彼此之上,但这最终会在Voronoi的区域中着色。任何帮助找出如何在背景上的图像和Voronoi在顶部将非常感谢!
它实际上有效,我想需要正确选择voronoi点:
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()