E.g., when processing the set of plane contours:
each one consists of N nodes and may be described by the matrix N*2
(x, y coordinates of every node).
In MATLAB it may be done with cell array Contours{}.
Every element corresponds to one contour and storeы the array of coordinates of the nodes.
What is the recommended object (data type) in Python for such set of contours ?
Related
I would like to use Smooth.ppp in spatstat to calculate a sort of "moving average" according to a specific function. The specific distance-dependent weights I would like to use are given by a function wt; for simplicity
wt=function(x,y) exp(-1e5*(x-y)^2)
In the extreme case where wt=kernel, I'd expect no smoothing (ie input marks = smoothed estimates). I'm wondering what I am mis-understanding here about the kernel and how it is applied?
remotes::install_github("spatstat/spatstat.core")
n=4; PPP=ppp(rep(1:n,each=n),rep(1:n,n), c(1,n),c(1,n), marks=1:n^2);
smo=Smooth.ppp(PPP,cutoff=2,kernel=wt,at="points")
rbind(marks(PPP),smo)
(I'm using the latest spatstat build to allow estimates at points using a custom kernel)
This example may have been misinterpreted.
The kernel should be a function(x, y) in the R language which gives the value, at a spatial location (x,y), of the kernel centred at the origin (0,0). Generally the kernel takes its largest values when (x,y) is close to (0,0), and drops to zero when (x,y) is far from (0,0).
The function wt defined in your example has values close to 1 along the diagonal line x = y, and drops to zero rapidly away from the diagonal.
That is unusual. It means that a data point at location (a,b) will be 'smoothed' along the infinite line through the data point with unit slope, with equation y = x + b-a, rather than being smoothed over a region close to (a,b) as it normally would.
The example point pattern PPP consists of points along the diagonal y=x.
The smoothed value at a data point is the weighted average of the mark values at all data points, with weights proportional to the kernel value. In your example, the kernel value for each pair of data points, wt(x1-x2, y1-y2), is equal to 1 because all the data and query points lie on the same line with slope 1.
The kernel weights are all equal in this example, so the smoothed values should all be equal to the average mark value, if leaveoneout=FALSE, and if leaveoneout=TRUE then the smoothed value at data point i is the average of the mark values at the data points excluding point i.
I want to select 5 Points in each polygon based on random sampling method. And required 5 points co-ordinates(Lat,Long) in each polygon for identify which crop is grawn.
Any ideas for do this using geopandas?
Many thanks.
My suggestion involves sampling random x and y coordinates within the shape's bounding box and then checking whether the sampled point is actually within the shape. If the sampled point is within the shape then return it, otherwise repeat until a point within the shape is found. For sampling, we can use the uniform distribution, such that all points in the shape have the same probability of being sampled. Here is the function:
from shapely.geometry import Point
def random_point_in_shp(shp):
within = False
while not within:
x = np.random.uniform(shp.bounds[0], shp.bounds[2])
y = np.random.uniform(shp.bounds[1], shp.bounds[3])
within = shp.contains(Point(x, y))
return Point(x,y)
and here's an example how to apply this function to an example GeoDataFrame called geo_df to get 5 random points for each entry:
for num in range(5):
geo_df['Point{}'.format(num)] = geo_df['geometry'].apply(random_point_in_shp)
There might be more efficient ways to do this, but depending on your application the algorithm could be sufficiently fast. With my test file, which contains ~2300 entries, generating five random points for each entry took around 15 seconds on my machine.
I have a quadrotor which flies around and knows its x, y, z positions and angular displacement along the x, y, z axis. It captures a constant stream of images which are converted into depth maps (we can estimate the distance between each pixel and the camera).
How can one program an algorithm which converts this information into a 3D model of the environment? That is, how can we generate a virtual 3D map from this information?
Example: below is a picture that illustrates what the quadrotor captures (top) and what the image is converted into to feed into a 3D mapping algorithm (bottom)
Let's suppose this image was taken from a camera with x, y, z coordinates (10, 5, 1) in some units and angular displacement of 90, 0, 0 degrees about the x, y, z axes. What I want to do is take a bunch of these photo-coordinate tuples and convert them into a single 3D map of the area.
Edit 1 on 7/30: One obvious solution is to use the angle of the quadrotor wrt to x, y, and z axes with the distance map to figure out the Cartesian coordinates of any obstructions with trig. I figure I could probably write an algorithm which uses this approach with a probabilistic method to make a crude 3D map, possibly vectorizing it to make it faster.
However, I would like to know if there is any fundamentally different and hopefully faster approach to solving this?
Simply convert your data to Cartesian and store the result ... As you have known topology (spatial relation between data points) of the input data then this can be done to map directly to mesh/surface instead of to PCL (which would require triangulation or convex hull etc ...).
Your images suggest you have known topology (neighboring pixels are neighboring also in 3D ...) so you can construct mesh 3D surface directly:
align both RGB and Depth 2D maps.
In case this is not already done see:
Align already captured rgb and depth images
convert to Cartesian coordinate system.
First we compute the position of each pixel in camera local space:
so each pixel (x,y) in RGB map we find out the Depth distance to camera focal point and compute the 3D position relative to the camera focal point.For that we can use triangle similarity so:
x = camera_focus.x + (pixel.x-camera_focus.x)*depth(pixel.x,pixel.y)/focal_length
y = camera_focus.y + (pixel.y-camera_focus.y)*depth(pixel.x,pixel.y)/focal_length
z = camera_focus.z + depth(pixel.x,pixel.y)
where pixel is pixel 2D position, depth(x,y) is coresponding depth, and focal_length=znear is the fixed camera parameter (determining FOV). the camera_focus is the camera focal point position. Its usual that camera focal point is in the middle of the camera image and znear distant to the image (projection plane).
As this is taken from moving device you need to convert this into some global coordinate system (using your camera positon and orientation in space). For that are the best:
Understanding 4x4 homogenous transform matrices
construct mesh
as your input data are already spatially sorted we can construct QUAD grid directly. Simply for each pixel take its neighbors and form QUADS. So if 2D position in your data (x,y) is converted into 3D (x,y,z) with approach described in previous bullet we can write iot in form of function that returns 3D position:
(x,y,z) = 3D(x,y)
Then I can form QUADS like this:
QUAD( 3D(x,y),3D(x+1,y),3D(x+1,y+1),3D(x,y+1) )
we can use for loops:
for (x=0;x<xs-1;x++)
for (y=0;y<ys-1;y++)
QUAD( 3D(x,y),3D(x+1,y),3D(x+1,y+1),3D(x,y+1) )
where xs,ys is the resolution of your maps.
In case you do not know camera properties you can set the focal_length to any reasonable constant (resulting in fish eye effects and or scaled output) or infer it from input data like:
Transformation of 3D objects related to vanishing points and horizon line
Here's the set up: I have a data frame, df, with columns labeled A,B,...,K. Each entry of column A is unique and will make up one of the two sets of vertices, call it X, in a bipartite graph, G. The entries of columns B,...,K (not all unique) make up the other set of vertices, call it Y, in the bipartite graph. We draw an edge from vertex y in Y to vertex x in X if y is in the same row as x.
Using this answer from another post, I have the following code which creates a bipartite graph with vertex sets given by the entries of column A (positioned on the right) and B (positioned on the left)
G = nx.Graph()
G.add_nodes_from(df['A'], bipartite=0)
G.add_nodes_from(df['B'], bipartite=1)
G.add_weighted_edges_from(
[(row['B'], row['A'], 1) for idx, row in df.iterrows()],
weight='weight')
pos = {node:[0, i] for i,node in enumerate(df['B'])}
pos.update({node:[1, i] for i,node in enumerate(df['A'])})
nx.draw(G, pos, with_labels = True)
plt.show()
I'm seeking advice/help with a few problems:
The number of vertices is large enough so that the vertices appear very bunched up. Is there a way of spreading out the vertices in each of the two vertex sets?
As I mentioned, this code makes a bipartite graph connecting some entries of B with some entries of A (again, based on row matching). How can I do this for each of the other columns (i.e. connecting elements of C,...,K with A in the same way)? I know there is a way to union graphs together with union(G1,G2) but I imagine there's a better way to achieve this.
I'd like to create some kind of edge coloring based on the degree of vertices in Y. I imagine the coloring will be implemented using the G.degree(), but I'm not sure how that works.
Please let me know if you have any suggestions for my problems. Thanks in advance!
I'm trying to fill in a structured grid with an analytical field, but despite reading the vtk docs, I haven't found out how to actually set scalar values at the grid points or the set the spacing/origin info of the grid. Starting from the code below, how do I
associate spatial information with the grid (ie cell 0,0,0 is at coordinates 0,0,0, the spacing is dx in every direction)
associate scalar values with each grid point. To start, I just need one, but eventually I'd like to store 3 pieces of data at each point (not a vector, 3 distinct scalars).
grid = vtk.vtkStructuredGrid()
numPoints = int((maxGrid - minGrid)/dx)
grid.SetDimensions(numPoints, numPoints, numPoints)
In VTK there are 3 types of "structured" grids, vtkImageData (vtkUniformGrid derives from this), vtkRectilinearGrid, and vtkStructuredGrid. They are all structured in the sense that the topology is set. vtkImageData has constant spacing between points and is axis aligned, vtkRectilinearGrid is axis aligned but can vary the spacing in each axis direction, and vtkStructuredGrid has arbitrarily located points (cells may not be valid though).
For what you want to do you should do:
from vtk import *
dx = 2.0
grid = vtkImageData()
grid.SetOrigin(0, 0, 0) # default values
grid.SetSpacing(dx, dx, dx)
grid.SetDimensions(5, 8, 10) # number of points in each direction
# print grid.GetNumberOfPoints()
# print grid.GetNumberOfCells()
array = vtkDoubleArray()
array.SetNumberOfComponents(1) # this is 3 for a vector
array.SetNumberOfTuples(grid.GetNumberOfPoints())
for i in range(grid.GetNumberOfPoints()):
array.SetValue(i, 1)
grid.GetPointData().AddArray(array)
# print grid.GetPointData().GetNumberOfArrays()
array.SetName("unit array")