Dealing with geo coordinates

Location on maps are often provided in a Coordinate Reference System (CRS). In computer vision projects, however, we need to translate them to pixels. Plotting and transformations can be accomplished with the rasterio Python module.

Below I share a useful snippet showing how to convert CRS locations to pixel coordinates:

import matplotlib.pyplot as plt
import geopandas
import rasterio as rs
from rasterio.plot import show
import pandas as pd
from shapely.geometry import Point
from PIL import Image, ImageDraw

fig, axs = plt.subplots(1, 2)
# open the image and its annotations
img_path = "trees_counting_mount/polish_ortophoto/1_2000/images/66579_623608_8.135.12.19_cropped_2000.tif"
label_path = "trees_counting_mount/polish_ortophoto/1_2000/annotations/66579_623608_8.135.12.19_cropped_2000.csv"
raster =, crs="EPSG:2180")
label_df = pd.read_csv(label_path)

# extract selected points
geometry = list(map(Point, label_df[["x", "y"]].values))
idxs = [0, 100, 200]
Ps = [geometry[idx] for idx in idxs]

# plot points in two alternative ways!
ax = axs[0]
show(raster, ax=ax)
# variant 1: plot geo-coordinates with geopandas.GeoDataFrame
geo_df = geopandas.GeoDataFrame(None, geometry=Ps, crs="EPSG:2180")
ax = axs[1]
# variant 2: convert geo-coordinates to pixel locations
ys, xs = rs.transform.rowcol(raster.transform, [P.x for P in Ps], [P.y for P in Ps])
img =
img_draw = ImageDraw.Draw(img)

for x, y in zip(xs, ys):
  img_draw.ellipse( (x-150,y-150,x+150,y+150), fill="yellow")


plt.title("Points in geo-coordinates (left) and image pixel coordinates (right).")

Published by mskorski

Scientist, Consultant, Learning Enthusiast

Leave a comment

Your email address will not be published. Required fields are marked *