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

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 ?

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 ??).

Related

Sorting Data for Matplotlib Surface Plot

I’m trying to plot Riemann surface (imaginary part, real part is color-coded) for a complex valued function
using matplolib.
As it follows from nature of complex multivalued function, when some path passes a branch cut
its image jumps on f(z) plane.
As you can see in the code below, my mesh consists of circles
in polar coordinate system, which are the paths, passing the branch cut. It results in a jump that you can see in the figure below.
Question:
Is there any way to stitch the parts of the plot in a proper way.
To me a possible solution looks like either:
generate the values of mesh, bounded by the branch cut, and then concatenate the parts of them somehow (maybe even matplotlib itself has a function for it), or
sort out z-axis values being obtained on a simple mesh, which I use in the code
I've tried both but not succeeded.
If anybody has already faced such issues, or has any ideas, I would appreciate your comments!
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
k0 = 3 - 0.5j
# polar coordinates r and phi
Uphi = np.arange(0,2*np.pi,0.002) # phi from 0 to 2pi
Vr = np.arange(0,5,0.02) # r from 0 to 5
# polar grid
U, V = np.meshgrid(Uphi, Vr)
# coordinates on conplex plane: Z = X + iY; X,Y - cartezian coords
X = V*np.cos(U)
Y = V*np.sin(U)
Z1 = np.imag(-np.sqrt(-k0**2 + (X + 1j*Y)**2)) # first branch of the multivalued function
Z2 = np.imag(+np.sqrt(-k0**2 + (X + 1j*Y)**2)) # second branch
Z = np.zeros((Z1.shape[0],2*Z1.shape[1])) # resultng array to plot
Z[:,:Z1.shape[1]] = Z1
Z[:,Z1.shape[1]:] = Z2
# colormap -- color-coding the imaginary part of the 4D function -- another dimension
Z_cv = np.zeros((Z1.shape[0],2*Z1.shape[1]))
Z_cv[:,:Z1.shape[1]] = np.real(-np.sqrt(-k0**2 + (X + 1j*Y)**2))
Z_cv[:,Z1.shape[1]:] = np.real(+np.sqrt(-k0**2 + (X + 1j*Y)**2))
# expanding grid for two branches Z1 and Z2
X1 = np.zeros((Z1.shape[0],2*Z1.shape[1]))
Y1 = np.zeros((Z1.shape[0],2*Z1.shape[1]))
X1[:,:Z1.shape[1]] = X
X1[:,Z1.shape[1]:] = X
Y1[:,:Z1.shape[1]] = Y
Y1[:,Z1.shape[1]:] = Y
# plotting the surface
F = plt.figure(figsize=(12,8),dpi=100)
A = F.gca(projection='3d',autoscale_on=True)
# normalizing the values of color map
CV = (Z_cv + np.abs(np.min(Z_cv)))/(np.max(Z_cv) + np.abs(np.min(Z_cv)))
A.plot_surface(X1, Y1, Z, rcount=100, ccount=200, facecolors=cm.jet(CV,alpha=.3))
A.view_init(40,70)
m = cm.ScalarMappable(cmap=cm.jet)
m.set_array(Z_cv)
plt.colorbar(m)
plt.show()
The following figures represent two regular branches of the function on the Riemann surface using using Domain coloring approach. It more clearly shows those jumps.
import cplot
import numpy as np
cplot.show(lambda z: np.sqrt(z**2 - k0**2), -5, +5, -5, +5, 100, 100,alpha=0.7)
cplot.show(lambda z: -np.sqrt(z**2 - k0**2), -5, +5, -5, +5, 100, 100,alpha=0.7)

render Voronoi diagram to numpy array

I'd like to generate Voronoi regions, based on a list of centers and an image size.
I'm tryed the next code, based on https://rosettacode.org/wiki/Voronoi_diagram
def generate_voronoi_diagram(width, height, centers_x, centers_y):
image = Image.new("RGB", (width, height))
putpixel = image.putpixel
imgx, imgy = image.size
num_cells=len(centers_x)
nx = centers_x
ny = centers_y
nr,ng,nb=[],[],[]
for i in range (num_cells):
nr.append(randint(0, 255));ng.append(randint(0, 255));nb.append(randint(0, 255));
for y in range(imgy):
for x in range(imgx):
dmin = math.hypot(imgx-1, imgy-1)
j = -1
for i in range(num_cells):
d = math.hypot(nx[i]-x, ny[i]-y)
if d < dmin:
dmin = d
j = i
putpixel((x, y), (nr[j], ng[j], nb[j]))
image.save("VoronoiDiagram.png", "PNG")
image.show()
I have the desired output:
But it takes too much to generate the output.
I also tried https://stackoverflow.com/a/20678647
It is fast, but I didn't find the way to translate it to numpy array of img_width X img_height. Mostly, because I don't know how to give image size parameter to scipy Voronoi class.
Is there any faster way to have this output? No centers or polygon edges are needed
Thanks in advance
Edited 2018-12-11:
Using #tel "Fast Solution"
The code execution is faster, it seems that the centers have been transformed. Probably this method is adding a margin to the image
Fast solution
Here's how you can convert the output of the fast solution based on scipy.spatial.Voronoi that you linked to into a Numpy array of arbitrary width and height. Given the set of regions, vertices that you get as output from the voronoi_finite_polygons_2d function in the linked code, here's a helper function that will convert that output to an array:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
def vorarr(regions, vertices, width, height, dpi=100):
fig = plt.Figure(figsize=(width/dpi, height/dpi), dpi=dpi)
canvas = FigureCanvas(fig)
ax = fig.add_axes([0,0,1,1])
# colorize
for region in regions:
polygon = vertices[region]
ax.fill(*zip(*polygon), alpha=0.4)
ax.plot(points[:,0], points[:,1], 'ko')
ax.set_xlim(vor.min_bound[0] - 0.1, vor.max_bound[0] + 0.1)
ax.set_ylim(vor.min_bound[1] - 0.1, vor.max_bound[1] + 0.1)
canvas.draw()
return np.frombuffer(canvas.tostring_rgb(), dtype='uint8').reshape(height, width, 3)
Testing it out
Here's a complete example of vorarr in action:
from scipy.spatial import Voronoi
# get random points
np.random.seed(1234)
points = np.random.rand(15, 2)
# compute Voronoi tesselation
vor = Voronoi(points)
# voronoi_finite_polygons_2d function from https://stackoverflow.com/a/20678647/425458
regions, vertices = voronoi_finite_polygons_2d(vor)
# convert plotting data to numpy array
arr = vorarr(regions, vertices, width=1000, height=1000)
# plot the numpy array
plt.imshow(arr)
Output:
As you can see, the resulting Numpy array does indeed have a shape of (1000, 1000), as specified in the call to vorarr.
If you want to fix up your existing code
Here's how you could alter your current code to work with/return a Numpy array:
import math
import matplotlib.pyplot as plt
import numpy as np
def generate_voronoi_diagram(width, height, centers_x, centers_y):
arr = np.zeros((width, height, 3), dtype=int)
imgx,imgy = width, height
num_cells=len(centers_x)
nx = centers_x
ny = centers_y
randcolors = np.random.randint(0, 255, size=(num_cells, 3))
for y in range(imgy):
for x in range(imgx):
dmin = math.hypot(imgx-1, imgy-1)
j = -1
for i in range(num_cells):
d = math.hypot(nx[i]-x, ny[i]-y)
if d < dmin:
dmin = d
j = i
arr[x, y, :] = randcolors[j]
plt.imshow(arr.transpose(1, 0, 2))
plt.scatter(cx, cy, c='w', edgecolors='k')
plt.show()
return arr
Example usage:
np.random.seed(1234)
width = 500
cx = np.random.rand(15)*width
height = 300
cy = np.random.rand(15)*height
arr = generate_voronoi_diagram(width, height, cx, cy)
Example output:
A fast solution without using matplotlib is also possible. Your solution is slow because you're iterating over all pixels, which incurs a lot of overhead in Python. A simple solution to this is to compute all distances in a single numpy operation and assigning all colors in another single operation.
def generate_voronoi_diagram_fast(width, height, centers_x, centers_y):
# Create grid containing all pixel locations in image
x, y = np.meshgrid(np.arange(width), np.arange(height))
# Find squared distance of each pixel location from each center: the (i, j, k)th
# entry in this array is the squared distance from pixel (i, j) to the kth center.
squared_dist = (x[:, :, np.newaxis] - centers_x[np.newaxis, np.newaxis, :]) ** 2 + \
(y[:, :, np.newaxis] - centers_y[np.newaxis, np.newaxis, :]) ** 2
# Find closest center to each pixel location
indices = np.argmin(squared_dist, axis=2) # Array containing index of closest center
# Convert the previous 2D array to a 3D array where the extra dimension is a one-hot
# encoding of the index
one_hot_indices = indices[:, :, np.newaxis, np.newaxis] == np.arange(centers_x.size)[np.newaxis, np.newaxis, :, np.newaxis]
# Create a random color for each center
colors = np.random.randint(0, 255, (centers_x.size, 3))
# Return an image where each pixel has a color chosen from `colors` by its
# closest center
return (one_hot_indices * colors[np.newaxis, np.newaxis, :, :]).sum(axis=2)
Running this function on my machine obtains a ~10x speedup relative to the original iterative solution (not taking plotting and saving the result to disk into account). I'm sure there are still a lot of other tweaks which could further accelerate my solution.

How to add simplices to a scipy Delaunay triangulation object

I already have a rectangle triangulated by a scipy.spatial.Delaunay() object. I manage to stretch and curve it around so that it looks like an annulus cut along a line. Here is some code to make something with the same topology:
from scipy.spatial import Delaunay
NR = 22
NTheta = 36
Rin = 1
Rout = 3
alphaFactor = 33/64
alpha = np.pi/alphaFactor # opening angle of wedge
u=np.linspace(pi/2, pi/2 + alpha, NTheta)
v=np.linspace(Rin, Rout, NR)
u,v=np.meshgrid(u,v)
u=u.flatten()
v=v.flatten()
#evaluate the parameterization at the flattened u and v
x=v*np.cos(u)
y=v*np.sin(u)
#define 2D points, as input data for the Delaunay triangulation of U
points2D=np.vstack([u,v]).T
xy0 = np.vstack([x,y]).T
triLattice = Delaunay(points2D) #triangulate the rectangle U
triSimplices = triLattice.simplices
plt.figure()
plt.triplot(x, y, triSimplices, linewidth=0.5)
Starting from this topology, I now want to join up the two open edges, and make a closed annulus (change the topology, that is). How do I manually add new triangles to the existing triangulation?
A solution is to merge the points around the gap. Here is a way to do this, by keeping track of the indexes of the corresponding points:
import matplotlib.pylab as plt
from scipy.spatial import Delaunay
import numpy as np
NR = 4
NTheta = 16
Rin = 1
Rout = 3
alphaFactor = 33/64 # -- set to .5 to close the gap
alpha = np.pi/alphaFactor # opening angle of wedge
u = np.linspace(np.pi/2, np.pi/2 + alpha, NTheta)
v = np.linspace(Rin, Rout, NR)
u_grid, v_grid = np.meshgrid(u, v)
u = u_grid.flatten()
v = v_grid.flatten()
# Get the indexes of the points on the first and last columns:
idx_grid_first = (np.arange(u_grid.shape[0]),
np.zeros(u_grid.shape[0], dtype=int))
idx_grid_last = (np.arange(u_grid.shape[0]),
(u_grid.shape[1]-1)*np.ones(u_grid.shape[0], dtype=int))
# Convert these 2D indexes to 1D indexes, on the flatten array:
idx_flat_first = np.ravel_multi_index(idx_grid_first, u_grid.shape)
idx_flat_last = np.ravel_multi_index(idx_grid_last, u_grid.shape)
# Evaluate the parameterization at the flattened u and v
x = v * np.cos(u)
y = v * np.sin(u)
# Define 2D points, as input data for the Delaunay triangulation of U
points2D = np.vstack([u, v]).T
triLattice = Delaunay(points2D) # triangulate the rectangle U
triSimplices = triLattice.simplices
# Replace the 'last' index by the corresponding 'first':
triSimplices_merged = triSimplices.copy()
for i_first, i_last in zip(idx_flat_first, idx_flat_last):
triSimplices_merged[triSimplices == i_last] = i_first
# Graph
plt.figure(figsize=(7, 7))
plt.triplot(x, y, triSimplices, linewidth=0.5)
plt.triplot(x, y, triSimplices_merged, linewidth=0.5, color='k')
plt.axis('equal');
plt.plot(x[idx_flat_first], y[idx_flat_first], 'or', label='first')
plt.plot(x[idx_flat_last], y[idx_flat_last], 'ob', label='last')
plt.legend();
which gives:
Maybe you will have to adjust the definition of the alphaFactor so that the gap has the right size.

how to deform an image deforming the coordinates

I would like to see how an image get deformed if I know how its coordinates are deformed.
for example: here I draw a circle
import numpy as np
import matplotlib.pyplot as plt
from math import *
plane_side = 500.0 #arcsec
y_l, x_l, = np.mgrid[-plane_side:plane_side:1000j, -plane_side:plane_side:1000j]
r = np.sqrt(y_l**2 + x_l**2)
indexes1 = np.where(r<150.0)
indexes2 = np.where(r>160.0)
image = r.copy()
image[:,:] = 1.0
image[indexes1] = 0.0
image[indexes2] = 0.0
imgplot = plt.imshow(image,cmap="rainbow")
plt.colorbar()
plt.show()
If I want to deform the coordinates like this:
y_c = y_lense**3
x_c = x_lense**2
and plot the image distorted, what should I do?
You can use plt.pcolormesh():
y_c = (y_l/plane_side)**3
x_c = (x_l/plane_side)**2
ax = plt.gca()
ax.set_aspect("equal")
plt.pcolormesh(x_c, y_c, image, cmap="rainbow")
ax.set_xlim(0, 0.2)
ax.set_ylim(-0.1, 0.1);
the result:
In general (without using a dedicated library), you should apply an inverse transformation to the coordinates of the new image. Than, you interpolate values from the original image at the calculated coordinates.
For example, if you want to apply the following transformation:
x_new = x**2
y_new = y**2
you would do something like that:
import numpy as np
# some random image
image = np.random.rand(10,10)
# new interpolated image - actually not interpolated yet :p
# TODO: in some cases, this image should be bigger than the original image. You can calculate optimal size from the original image considering the transformation used.
image_new = np.zeros(image.shape)
# get the coordinates
x_new, y_new = np.meshgrid( range(0,image_new.shape[1]), range(0,image_new.shape[0]) )
x_new = np.reshape(x_new, x_new.size)
y_new = np.reshape(y_new, y_new.size)
# do the inverse transformation
x = np.sqrt(x_new)
y = np.sqrt(y_new)
# TODO: here you should check that all x, y coordinates fall inside the image borders
# do the interpolation. The simplest one is nearest neighbour interpolation. For better image quality, bilinear interpolation should be used.
image_new[y_new,x_new] = image[np.round(y).astype(np.int) , np.round(x).astype(np.int)]

Specify absolute colour for 3D points in MayaVi

I am using the MayaVi Python library to plot 3d points, using the points3d class. The documentation specifies that the colour of each point is specified through a fourth argument, s:
In addition, you can pass a fourth array s of the same shape as x, y,
and z giving an associated scalar value for each point, or a function
f(x, y, z) returning the scalar value. This scalar value can be used
to modulate the color and the size of the points.
This specifies a scalar value for each point, which maps the point to a colourmap, such as copper, jet or hsv. E.g. from their documentation:
import numpy
from mayavi.mlab import *
def test_points3d():
t = numpy.linspace(0, 4*numpy.pi, 20)
cos = numpy.cos
sin = numpy.sin
x = sin(2*t)
y = cos(t)
z = cos(2*t)
s = 2+sin(t)
return points3d(x, y, z, s, colormap="copper", scale_factor=.25)
Gives:
Instead, I would like to specify the actual value for each point as an (r, g, b) tuple. Is this possible in MayaVi? I have tried replacing the s with an array of tuples, but an error is thrown.
After struggling with this for most of today, I found a relatively simple way to do exactly what the question asks -- specify an RGB tuple for each point. The trick is just to define a color map with exactly the same number of entries as there are points to plot, and then set the argument to be a list of indices:
# Imports
import numpy as np
from mayavi.mlab import quiver3d, draw
# Primitives
N = 200 # Number of points
ones = np.ones(N)
scalars = np.arange(N) # Key point: set an integer for each point
# Define color table (including alpha), which must be uint8 and [0,255]
colors = (np.random.random((N, 4))*255).astype(np.uint8)
colors[:,-1] = 255 # No transparency
# Define coordinates and points
x, y, z = colors[:,0], colors[:,1], colors[:,2] # Assign x, y, z values to match color
pts = quiver3d(x, y, z, ones, ones, ones, scalars=scalars, mode='sphere') # Create points
pts.glyph.color_mode = 'color_by_scalar' # Color by scalar
# Set look-up table and redraw
pts.module_manager.scalar_lut_manager.lut.table = colors
draw()
I've found a better way to set the colors directly.
You can create your own direct LUT pretty easily. Let's say we want 256**3 granularity:
#create direct grid as 256**3 x 4 array
def create_8bit_rgb_lut():
xl = numpy.mgrid[0:256, 0:256, 0:256]
lut = numpy.vstack((xl[0].reshape(1, 256**3),
xl[1].reshape(1, 256**3),
xl[2].reshape(1, 256**3),
255 * numpy.ones((1, 256**3)))).T
return lut.astype('int32')
# indexing function to above grid
def rgb_2_scalar_idx(r, g, b):
return 256**2 *r + 256 * g + b
#N x 3 colors. <This is where you are storing your custom colors in RGB>
colors = numpy.array([_.color for _ in points])
#N scalars
scalars = numpy.zeros((colors.shape[0],))
for (kp_idx, kp_c) in enumerate(colors):
scalars[kp_idx] = rgb_2_scalar_idx(kp_c[0], kp_c[1], kp_c[2])
rgb_lut = create_8bit_rgb_lut()
points_mlab = mayavi.mlab.points3d(x, y, z, scalars, mode='point')
#magic to modify lookup table
points_mlab.module_manager.scalar_lut_manager.lut._vtk_obj.SetTableRange(0, rgb_lut.shape[0])
points_mlab.module_manager.scalar_lut_manager.lut.number_of_colors = rgb_lut.shape[0]
points_mlab.module_manager.scalar_lut_manager.lut.table = rgb_lut
You can use a rgb look up table and map your rgb values to it using whatever logic you want. Here's a simple example:
import numpy, random
from mayavi.mlab import *
def cMap(x,y,z):
#whatever logic you want for colors
return [random.random() for i in x]
def test_points3d():
t = numpy.linspace(0, 4*numpy.pi, 20)
cos = numpy.cos
sin = numpy.sin
x = sin(2*t)
y = cos(t)
z = cos(2*t)
s = cMap(x,y,z)
return points3d(x, y, z, s, colormap="spectral", scale_factor=0.25)
test_points3d()
I have no idea what color scheme you want, but you can evaluate the positions of x,y,z and return whatever scalar corresponds to the rgb value you are seeking.
This can now simply be done with the color argument
from mayavi import mlab
import numpy as np
c = np.random.rand(200, 3)
r = np.random.rand(200) / 10.
mlab.points3d(c[:, 0], c[:, 1], c[:, 2], r, color=(0.2, 0.4, 0.5))
mlab.show()

Categories