2

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!

Community
  • 1
  • 1
Shushan
  • 21
  • 1
  • 3

1 Answers1

3

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

enter image description here

Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63