I am having trouble with solving line intersection problem. I would solve it using standard functions which may already exist in Python library. Let me explain it below: I have sets of lines A(x,y) and B(x,y) and one map as a matrix form, also with its resolution dx, dy which can be changed. I wanted to calculate all intersected points of line with the map depending on dx, dy value. I already did it, but two problems: 1) When some coordinate value (x or y) are zero, the program returns wrong answer. For example, distance is zero, but it is not zero in fact. 2) How can I optimize my code (using Python standard library), if possible.
Or is there standard Python library for that purpose???
import numpy as np
def intrsctd_pnts(map, dx, dy, A, B, line_number):
height, width = np.shape(map)
# slope of each line m = (B[:, 1] - A[:, 1]) / (B[:, 0] - A[:, 0]) b = A[:, 1] - m * A[:, 0]
distance =  i_pixel =  intersect_point =  for i in range(line_number): AB =  # calculate all intersected x coordinates x = np.arange(lx_floor[i], lx_ceil[i]+dx, dx) y = m[i] * x + b[i] AB = zip(x, y) # calculate all intersected y coordinates y = np.arange(ly_floor[i], ly_ceil[i]+dy, dy) x = (y - b[i]) / m[i] AB.extend(zip(x, y)) AB.append((A[i,0], A[i,1])) AB.append((B[i,0], B[i,1])) AB.sort() AB = np.asarray(AB) intersect_point.append(AB) # compute distance between two points dist_x = np.diff(AB[:,0]) dist_y = np.diff(AB[:,1]) distance.append( np.sqrt((dist_x)**2 + (dist_y)**2) )
# FIND pixel value where line intersects that pixel col = (np.floor( min(AB[:,0]) / dx)).astype(int) row = (np.floor( min(AB[:,1]) / dy)).astype(int)
# FIND pixel to which this lines belong i_pixel.append(col + width*row)