Projection of 3D convex hull onto xy plane with a colour map - python

What I'd like at the end is the smoothed colour map with contours plotted on top of it. The idea is to preserve as much as possible information from the 3D convex hull.
The problem is that the code I developed so far doesn't work for all the inputs.
Example
If I set tricontourf() integer parameter let say to 8 and provide 10 input files I will get 8 plots which are OK but 2 will be solid colour.
Next if I change parameter to 9 I'll get 7 good and 3 odd. Some of the good ones from the first step are now wrong!
Ideally I'd like to have this parameter fixed at ~25 so the colour map is smoothed.
Have look at the pictures:
This is wrong, int parameter = 9
this is what I want but smoother, int parameter 8
What is important to me is to have triangulation based on the convex hull.
import matplotlib.pyplot as plt
import numpy as np
import sys, os, time, math
from scipy.spatial import ConvexHull
from matplotlib.tri import Triangulation
import matplotlib.cm as cm
# get covex hull data and save them to an array
cvx = []
dataX = []
for filename in sys.argv[1:]:
X = np.genfromtxt(filename,delimiter="", skip_header=2)
dataX.append(X)
hull = ConvexHull(X)
cvx.append(hull)
for idx,filename in enumerate(sys.argv[1:]):
# start plotting data
x, y, z = dataX[idx].T
# triangulation based on a convex hull
simpl = cvx[idx].simplices
tri = Triangulation(x, y, triangles=simpl)
# plot lines (triangles)
plt.triplot(tri, color='k')
# plot contour lines based on convex hull facets
plt.tricontour(x, y, z, 5, linewidths=0.5, colors='k', triangles=simpl)
# plot colour map
plt.tricontourf(x, y, z, 8, cmap=plt.cm.rainbow, triangles=simpl)
plt.show()

Related

How to draw pentagonl with opencv in Python

I'm trying to draw a convex hull on random points but I have to do this using with opencv - not convexhull command or scpiy or hull lib)
First step, I create random points between 14 - 20 numbers.
However, I need something like this.
How can I save the plt.show() resultant graphic and draw convex hull like that?
Here's my code:
import random
import matplotlib.pyplot as plt
import cv2
points = []
points_limit = 12+random.randint(0, 7)
print(points_limit)
for x in range(points_limit):
points.append([random.randint(0, 9),random.randint(0, 9)])
print(points)
for point in points:
plt.scatter(point[0],point[1], color='k', s=100)
print(points)
plt.show()

color every point of path based on curvature using python

How do I encode the color in a scatter plot, to color every point (x,y) with black when the variable curvature is 0, then fade to green the higher the curvature it gets and fade to red the negative it gets?
Your question seem to raise several issue.
First, you have to compute the curvature of your (x,y) data. I suggest that you have a look here.
Then, perhaps you could have a look at all the available colomaps in matplotlib documentation. It may not be necessary to create your own colormap, though it is possible.
Finally, your code would be something like:
import numpy as np
import matplotlib.pyplot as plt
x = range(10)
y = np.random.rand(10) # generate random points
curvature = range(10) #compute your curvature here
plt.figure()
plt.scatter(x, y, s=20, c=curvature, cmap=plt.cm.seismic)
#perhaps you want to link points:
plt.plot(x,y)

Boundary points from a set of coordinates

I have a set of lat,long points, and from this points I'd like to extract the points that form the boundaries, I've used convexhull, but for my purpouse is not enough as convehull just returns the most distant points that form the polygon where all the points fit, I need ALL the points that form the peremiter, something like the image I've attached. What could I do? Is there some kind of package ready to use instead of implement any spatial algorithm?
Thanks
You must use a package for convex polygons. Here is an example:
import alphashape
import matplotlib.pyplot as plt
points = put your points here (can be array)!
alpha = 0.95 * alphashape.optimizealpha(points)
hull = alphashape.alphashape(points, alpha)
hull_pts = hull.exterior.coords.xy
fig, ax = plt.subplots()
ax.scatter(hull_pts[0], hull_pts[1], color='red')
Use Concave hull (Alpha shape) instead.
Assuming that you have all points (latitudes and longitudes) in two lists LATS, LONGS respectively, this python snippet cand do the trick. hullPoint will have the set of points that can draw the convex hull.
import numpy as np
from scipy.spatial import ConvexHull
allPoints=np.column_stack((LATS,LONGS))
hullPoints = ConvexHull(allPoints)

Plot3d in Python

I have an OBJ File Generated by Meshlab with Vertices and Faces data.
In MATLAB i used the function ''patch'' with Vertices data in 1 array (5937x3) and Faces (11870x3) data in another and the result is this:
Simplified version of the code
[V,F] = read_vertices_and_faces_from_obj_file(filename);
patch('Vertices',V,'Faces',F,'FaceColor','r','LineStyle','-')
axis equal
Result
The question is,how can I do that in Python ? There's a simple way like in Matlab??
I'll really appreciate any help.
Your best bet would be to make use of the mplot3d toolkit from the matplotlib library.
A similar question was asked here. Perhaps this slightly edited code excerpt from that question will help you.
The Code:
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.pyplot as plt
fig = plt.figure()
ax = Axes3D(fig)
# Specify 4 vertices
x = [0,1,1,0] # Specify x-coordinates of vertices
y = [0,0,1,1] # Specify y-coordinates of vertices
z = [0,1,0,1] # Specify z-coordinates of vertices
verts = [zip(x, y, z)] # [(0,0,0), (1,0,1), (1,1,0), (0,1,1)]
tri = Poly3DCollection(verts) # Create polygons by connecting all of the vertices you have specified
tri.set_color(colors.rgb2hex(sp.rand(3))) # Give the faces random colors
tri.set_edgecolor('k') # Color the edges of every polygon black
ax.add_collection3d(tri) # Connect polygon collection to the 3D axis
plt.show()

Making a contour plot with solutions from systems of differential equations with pylab

So, I'm solving a system of differential equations numerically i have x,y,z each a solution. Each array is one dimensional and and for example x[0],y[0],z[0] goes with a point in space. i want to graph these in a contour like the usual x y z coordinates, it says i need z to be a 2d array, i know how to make a mesh from x and y, but how do i do this to z?
I have made a mesh out of the x,y, but for z i don't know what to do.
if someone could give me insight it would be much appreciated.
It is not enough to just mesh in x and y, you need to grid your data on a regular grid to be able to do a contour plot. To do this you should look into matplotlib.mlab.griddata (http://matplotlib.org/examples/pylab_examples/griddata_demo.html).
I'll paste the example code from the link below with some extra comments:
from numpy.random import uniform, seed
from matplotlib.mlab import griddata
import matplotlib.pyplot as plt
import numpy as np
# Here the code generates some x and y coordinates and some corresponding z values.
seed(0)
npts = 200
x = uniform(-2,2,npts)
y = uniform(-2,2,npts)
z = x*np.exp(-x**2-y**2)
# Here you define a grid (of arbitrary dimensions, but equal spacing) onto which your data will be mapped
xi = np.linspace(-2.1,2.1,100)
yi = np.linspace(-2.1,2.1,200)
# Map the data to the grid to get a 2D array of remapped z values
zi = griddata(x,y,z,xi,yi,interp='linear')
# contour the gridded data, plotting dots at the nonuniform data points.
CS = plt.contour(xi,yi,zi,15,linewidths=0.5,colors='k')
CS = plt.contourf(xi,yi,zi,15,cmap=plt.cm.rainbow,
vmax=abs(zi).max(), vmin=-abs(zi).max())
plt.colorbar() # draw colorbar
# Plot the original sampling
plt.scatter(x,y,marker='o',c='b',s=5,zorder=10)
plt.xlim(-2,2)
plt.ylim(-2,2)
plt.title('griddata test (%d points)' % npts)
plt.show()
It looks like you are looking for line or scatter plots instead of contour.

Categories

Resources