python - Distance for each intersected points of a line in increased order in 2D coordinate -
i calculating distance between a(x0,y0) , b(x1,y1) points in 2d (x,y).
i have following code represents intersected points of each cell in given 2 boundary points, a(x0,y0) , b(x1,y1).
def intersected_points(x0, x1, y0, y1): # slope m = (y1 - y0 )/( x1 - x0) # boundary of selected points x_ceil = ceil( min (x0, x1 )) x_floor = floor( max(x0, x1)) y_ceil = ceil( min(y0, y1)) y_floor = floor( max(y0, y1)) # calculate intersected x coordinate ax = [] x in arange(x_ceil, x_floor + 1, 1): ax.append([ x, m * ( x - x0 ) + y0 ]) # calculate intersected y coordinate y in arange(y_ceil, y_floor + 1, 1): ax.append([ ( y - y0 ) * ( 1./m ) + x0, y ]) return ax
sample values:
intersected_points(1.5, 4.4, 0.5, 4.1);
output:
[ [2.0, 1.1206896551724137], [3.0, 2.3620689655172411], [4.0, 3.6034482758620685], [1.9027777777777779, 1.0], [2.7083333333333335, 2.0], [3.5138888888888893, 3.0], [4.3194444444444446, 4.0] ]
the output got mixed , unsorted values, so, each cell coordinates, line crosses. but, result want should (including boundary points): (x0,y0), intersected points, (x1,y1) x0, y0 - intial, x1,y1 - final point. other values intersected line coordinates!
here's modified version of code. uses numpy bit more, , includes end points in sorted array of points.
import numpy np def intersected_points(x0, x1, y0, y1): # slope m = (y1 - y0) / (x1 - x0) # boundary of selected points x_ceil = np.ceil(min(x0, x1)) x_floor = np.floor(max(x0, x1)) y_ceil = np.ceil(min(y0, y1)) y_floor = np.floor(max(y0, y1)) # calculate intersected x coordinate x = np.arange(x_ceil, x_floor + 1) y = m * (x - x0) + y0 ax = zip(x, y) # calculate intersected y coordinate y = np.arange(y_ceil, y_floor + 1) x = (y - y0) / m + x0 ax.extend(zip(x, y)) ax.append((x0, y0)) ax.append((x1, y1)) ax.sort() return np.array(ax) if __name__ == "__main__": import matplotlib.pyplot plt x0, y0 = 1.5, 0.5 x1, y1 = 4.4, 4.1 points = intersected_points(x0, x1, y0, y1) print points rect = plt.rectangle((x0, y0), x1 - x0, y1 - y0, facecolor="#60ff60", alpha=0.2) plt.gca().add_patch(rect) plt.plot([x0, x1], [y0, y1], 'b-') plt.plot(points[:, 0], points[:, 1], 'bo') plt.grid(true) plt.xticks(np.arange(np.floor(x0), np.ceil(x1))) plt.yticks(np.arange(np.floor(y0), np.ceil(y1))) plt.show()
it prints:
[[ 1.5 0.5 ] [ 1.90277778 1. ] [ 2. 1.12068966] [ 2.70833333 2. ] [ 3. 2.36206897] [ 3.51388889 3. ] [ 4. 3.60344828] [ 4.31944444 4. ] [ 4.4 4.1 ]]
and generates plot:
Comments
Post a Comment