1

I am trying to crop a satellite image with geographical coordinate from a CVS file. I have never cropped an image using coordinates from CSV file. I tried searching a lot but I can only find cropping using a shapefile. Can someone guide me or give me a link of tutorial or something where they have cropped using a CSV file. I really don't know where to look.

1 Answer 1

1

As you tagged your question also as geopandas and rasterIO: find below a solution with pandas and rasterIO. QGIS should be also possible, there you can try to make a QgsVectorLayer from your CSV and then it would be the same like shapefile, because the class is the same. Here the rasterIO solution: it takes a CSV with the following structure:
id,x,y
1,0,0
1,0,50
1,50,50
1,50,0
1,0,0

you can put more Polygons into it with different ids. The code is like this one:

import pandas as pd
from shapely.geometry import Polygon
import rasterio
import rasterio.mask
from matplotlib import pyplot
from rasterio.plot import show

polygons = []
df = pd.read_csv('polys.csv')
for id, p in df.groupby('id'): 
    poly = Polygon(zip(p.x,p.y)) #
    polygons.append(poly)

with rasterio.open("LC.tif") as src:
    out_image, out_transform = rasterio.mask.mask(src, polygons, crop=True)
    out_meta = src.meta
    out_meta.update({"driver": "GTiff",
         "height": out_image.shape[1],
         "width": out_image.shape[2],
         "transform": out_transform})

    with rasterio.open("LC_masked.tif", "w", **out_meta) as dest:
        dest.write(out_image)

#showing the results
src=rasterio.open("LC.tif")
masked = rasterio.open("LC_masked.tif")
fig, (ax1, ax2) = pyplot.subplots(1,2, figsize=(21,7))   
show((src, 1), ax=ax1, title='Original')
show((masked, 1), ax=ax2, title='Masked')
pyplot.show()

enter image description here

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.