I have a GeoTIFF file and I have extracted the lat long values of each pixel in the file. However, I am looking to extract lat long of specific regions in the GeoTIFF rather than all of it. Here is the sample of the screenshot of a GeoTIFF file that I used.

enter image description here

Here is the code to extract the lat long values from a GeoTIFF file,

import os
import pandas as pd
import urllib.request
import xarray as xr
import rioxarray
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import numpy as np
from rasterio.warp import transform

tiff_paths = glob.glob('*.tif')

df_list = []

for path in tiff_paths:
    da = xr.open_rasterio(path)\
    ny, nx = len(da['y']), len(da['x'])
    x, y = np.meshgrid(da['x'], da['y'])
    # Rasterio works with 1D arrays
    lon, lat = transform(da.crs, {'init': 'EPSG:4326'},
                             x.flatten(), y.flatten())
    lon = np.asarray(lon).reshape((ny, nx))
    lat = np.asarray(lat).reshape((ny, nx))
    da.coords['lon'] = (('y', 'x'), lon)
    da.coords['lat'] = (('y', 'x'), lat)
    l1 = lat.flatten()
    l2 = lon.flatten()
    df = pd.DataFrame({"Lat": l1, "Long": l2})

I'm interested in extracting specific lat long values in the GeoTIFF. For example, lat long of boundaries along roads and buildings. (Note that, I tried contour detection on the raster image using opencv, but the CRS of the raster GeoTIFF is getting erased.)

1 Answer 1


I think you should use rasterio's xy function. Here are some examples from the documentation.

First you have to retrieve the pixels coordinates you want to convert and then apply xy with the dataset transform.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.