Thanks to @Logan, here is my own code and now it works:
import gdal
import osr
import matplotlib.pyplot as plt
from numpy import arange, array, nonzero, in1d, abs, linspace, sqrt, pi
# Conver Degree to Kilometer (Thanks to Obspy!)
def d2k(degrees, radius=6371):
return degrees * (2.0 * radius * pi / 360.0)
# Find Nearest point in array
def find_nearest(array,value):
idx = (abs(array-value)).argmin()
return idx
def plot_cross_elv(raster=None, A=None, B=None, np=1000):
# Read raster data
ds = gdal.Open(raster, 0)
rb = ds.ReadAsArray()
# Get start/end point of the map in lon/lat
coords = ds.GetGeoTransform()
# Get lon/lat and elevation
lon = array([coords[0]+coords[1]*i for i in range(rb.shape[1])])
lat = array([coords[3]+coords[5]*i for i in range(rb.shape[0])])
elv = rb.flatten()
# Make pairs of (lon,lat)
points = array([array([x,y]) for y in lat for x in lon])
# Define Profile using lon/lat
ABx = linspace(A[0],B[0],np)
ABy = linspace(A[1],B[1],np)
profile = array([array([x,y]) for x,y in zip(ABx, ABy)])
# Find Nearest points of profile in Map and Prepare for plot
cross_dis = []
cross_elv = []
for p in profile:
lon_ind = find_nearest(lon,p[0])
lat_ind = find_nearest(lat,p[1])
x = lon[lon_ind]
y = lat[lat_ind]
d = sqrt(d2k(A[0]-x)**2+d2k(A[1]-y)**2)
h = rb[lat_ind][lon_ind]
cross_dis.append(d)
cross_elv.append(h)
ax = plt.subplot(111)
ax.plot(cross_dis,cross_elv,linewidth=2,color='k')
ax.set_xlabel('Distance [km]')
ax.set_ylabel('Elevation [m]')
ax.fill_between(cross_dis, 0, cross_elv, color='bisque')
ax.set_xlim(min(cross_dis), max(cross_dis))
ax.locator_params(axis='x',nbins=6)
ax.locator_params(axis='y',nbins=6)
plt.show()
# RUN
plot_cross_elv(raster='cliped.tif', A=(50.0, 35.0), B=(52.0, 36.5), np=1000)