Snappy Get ESRI Shapefile Polygon From Pixels

I’ve recently downloaded some Sentinel2 products. I’ve loaded these products into SNAP Desktop where I got the NDVI of the product then imported an ESRI Shapefile over the product, which was again saved as a separate .dim file. I have the option to either save the polygons as individual masks or all as the one mask where the attribute for mask/layer naming is a unique code that identifies the various polygons which make up the ESRI Shapefile. Using Snappy in Python I want to try and run through each pixel of the newly created .dim file, get the NDVI value (which I’ve already done) and get the unique code that associates the pixel coordinates to specific polygons in the ESRI Shapefile.

I was wondering if I should choose the option to save the polygons as individual masks or not and how one would go about getting the unique code associated with a specific polygon given the x, y coordinates?

If anyone knows how to complete this, advice would be greatly appreciated as I’ve been researching various methods such as using the Vector Data and Masks to try and find a solution.

I’ve attached two images, one of the polygons not split into separate masks and one where they are.

You have several options I guess.

As you want to handle the region differently you should go with the second option and import the region separately.

If they are imported they appear as vector data and as masks.

In python you can iterate over them.

After loading the product, you can do:

product = readProduct(...)
mask_names =product.getMaskGroup.getNodeNames()

Then you can set the mask name as valid expression of the band you are interested in.

band = product.getBand('the_band_name')

Now you can iterate over the band data and ask if the data is valid.

if band.isPixelValid(x, y):
    # do something
  # handle the invalid case

That’s roughly how it can be done

1 Like

Hi marpet,

Thank you for getting back to me and apologies for my delayed response. I actually completed the task in the meantime.

What I did was save polygons as individual masks. From here I selected all masks then applied Band Maths to them. Since all polygons had different numerical values, I was able to return the polygon value using Band Maths for each pixel.

I just wanted to let anyone else who may be having this issue to know how I completed it, though I’m sure marpet, your solution is much better.

Thanks again for the help.