WMS - Getting data clipped to a polygon

Hello,

I’m getting started accessing the OGC API through Python to download Sentinel data.
I would like to know if it is possible to make a request for data clipped to a polygon instead of a rectangular bounding box.

It’s possible to do in the EO browser, but I haven’t found a way to do it directly from the API.

I can of course download get the image cut to the bounding box, and then clip it, but being able to directly download only the data I need would save me some computer ressources, and possibly some processing units.

Thank you in advance for your help.

Hello,

The way I set a polygon in my Python OGC requests is by using the custom_url_params argument in my request. You can find more information here.

You will still need to set a bounding box, but you can add your polygon as an optional parameter. Here is a code snippet in Python:

# Set bounding box
bbox_loc = BBox(bbox=[7.3994, 43.7190, 7.4531, 43.7564], crs=CRS.WGS84)

# Polygon WKT (pasted polygon WKT, you can import a file using shapely for example)
geometryWKT = "POLYGON((7.41877555847168 43.72459139811755,7.410106658935547 43.7294293330051,7.414312362670898 43.732158252099964,7.413797378540039 43.734700996616425,7.423152923583985 43.74102638042922,7.432508468627931 43.735693257872555,7.41877555847168 43.72459139811755))"

# WMS request 
request = WmsRequest(data_source=DataSource.SENTINEL2_L1C,
layer='1_TRUE_COLOR',
data_folder=data_folder,
bbox=bbox_loc,
time='latest', 
width=512,
config=config,
custom_url_params={CustomUrlParam.GEOMETRY: geometryWKT}
 )

When making a request for data clipped to a polygon, it’s a good idea to activate the transparency for the areas outside the polygon in the Evalscript that you are calling. Here I am requesting the layer 1_TRUE_COLOR from my dashboard, which has the following evalscript:

//VERSION=3
function setup() {
  return {
    input: ["B02", "B03", "B04", "dataMask"],
    output: { bands: 4 }
  };
}

function evaluatePixel(sample) {
  return [2.5 * sample.B04, 2.5 * sample.B03, 2.5 * sample.B02, sample.dataMask];
}

2 Likes

Thank you very much for taking the time to write such a comprehensive answer, this is exactly what I was looking for, and you explained it very clearly. I hope I can get enough experience to one day give this kind of contribution to the forum.

1 Like