Python – Georeferencing a JPEG Image with Known x,y Geocoordinates and CRS

gdalgeotiff-tiffpythonrasterio

I have an orthomosaic GeoTIFF generated by a big number of JPG images (StructureFromMotion algorithm) that are not georeferenced. With computer vision I find some points on the initial orthophoto.tif file that are actually the same points with the points in each JPG image I want to georeference. Given the CRS of the TIFF file is known, how can I georeference the JPG images since I have these {x, y, geocoord_x, geocoord_y} points?

enter image description here

Best Answer

You can add some ground control points (GCPs) and use GDAL to figure out the extent of the file and so on.

You should do this on a copy of your original file in case you screw things up, and I assume that you have your GCPs available somewhere (e.g. a Pandas dataframe, but whatever).

Below, I assume the spatial reference is XXXX, so that needs updating.

from osgeo import gdal, osr

def update_gcp(df, fname):
    """Update the file with GCPs stored in dataframe"""

    # Open file in update mode
    ds = gdal.Open(fname, gdal.GA_Update)
    # Set spatial reference for the file (if not there)
    sr = osr.SpatialReference()
    sr.ImportFromEPSG(XXXX) #XXX is the projection of your points

    # Now, let's say you have your ground control points in a pandas
    # dataframe. Basically:
    # 1. Map coordinates easting
    # 2. Map coordinates northing
    # 3. Map elevation
    # 4. Column
    # 5. Row

    gcps = [gdal.GCP(df.x_map, df.y_map, df.z, df.i_pix, df.j_pix),
            for j, row in df.iterrows()]

    # The following bit updates the dataset with the GCPs and projection
    # information
    ds.SetGCPs(gcps, sr.ExportToWkt())

    # Remember to close the file
    ds = None