2

I recently posted an answer to Zonal stats for complete pixels qgis that required clipping a raster in a way that excludes pixels that fall partially outside the mask layer. Here's an illustration: enter image description here

The best method I could figure out is as follows:

  1. Polygonize the raster.
  2. Use Select by location tool to select features in Vectorized layer that fall within the polygon layer.
  3. Clip raster by mask layer using the selected features of the Vectorized layer as the mask layer. Don't crop the extent.

But this method seems like a lot of steps, and polygonizing a large raster can take a long time.

Is there a better method of clipping a raster and excluding cells that overlap the edge of the mask?

By "better" I mean fewer steps and/or requiring less processing time.

2

I'm not aware of a better way to do this using QGIS. I wrote the exactextractr package for R out of a need to solve problems like this, where the nature of polygon/raster cell intersections is important. It is much, much faster than creating a polygon for each cell and doing an intersection calculation. If you can use R, maybe it will be of use to you. Here is an example:

library(sf)
library(raster)
library(exactextractr)

countries <- st_read('ne_50m_admin_0_countries.shp')
elev <- raster('gmted2010_05deg.tif')

mexico <- countries[countries$NAME=='Mexico', ]

# Get a list with one mask for each input feature.
# Each cell of the mask will have a value from 0 to 1
# indicating the portion of the cell that is within the
# feature.
# We have only one input feature, so grab the first
# element.
mask <- partial_mask(elev, mexico)[[1]]
# Set values in the mask to NA where less than 100% of
# the cell area is within the polygon
mask[mask < 1] <- NA

plot(st_geometry(mexico))
plot(mask*elev, add=TRUE)

This produces the following output:

map of mexico showing only raster cells 100% within the boundary

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.