Search code examples
numpygeolocationlatitude-longitudepyproj

Convert x,y to latitiude and longitude


If I have a map image where:

  • The latitude and longitude of the upper left corner (x=0, y=0) are known
  • The width and height of the image is known
  • Zoom (z-axis) is known.

Can we compute the latitude and longitude for other coordinates in the image? For example, in the following image if I want to compute the lat/lon values for the white ploygon (where the coordinates (x,y) are known)

enter image description here


Solution

  • So given the information and the shape of the image, (see previous question):

    import numpy as np
    
    top_left = np.array((32.0055597, 35.9265418))
    bottom_right = np.array((33.0055597, 36.9265418))
    
    delta = bottom_right - top_left
    
    shape = (454, 394)[::-1] # convert from ij to xy coords
    
    pixel_sizes = delta / shape
    
    pixel_sizes * (80, 200) + top_left
    >>> array([32.20860539, 36.36707043])
    

    Gives the (x, y) or (longtiude, latitude) of your given point.

    This approach can be generalised given a set of points using numpy as:

    coords * pixel_sizes + top_left # coords is (N, 2) array
    

    If coords is a tuple of arrays it can be converted to an (N,2) array using np.column_stack.