I have this image loaded in QGIS, with two possible values for the pixels: 1 = orange, 2 = blueimage_loaded_in_qgis

For simplification, assume it represents a province of a country.

I want to extract just the part of the image included inside the limits of the province. Regardless the value of the pixels. I guess I should use a mask for that, but I don't want to mask pixels based on their values. I want to mask the pixels based on their location (inside or outside the limits of the province).

The image is not from a real province. So, I don't know the limits (in that case, I could spatially intersect the raster with the known limits).

One approach would be vectorize this image to get the limits of the fake province as a geometry. That would make things easy. But I'm not sure about how to face that task.

So, suggestions are welcome. Many thanks in advance.


The morphological operations of expanding and shrinking provide ways to remove the small "islands" of blue dots inside the country. Region grouping gives fine control over these operations. Together they will usually do what you want. In this case, region grouping alone does the trick.

Consider this complex example (of which a small portion is shown):


The RegionGroup operation identifies each connected component (of red or white) and assigns it a unique identifier. This figure distinguishes identifiers by color, with yellow corresponding to the "outside" region:


Use this to convert the outside area (white in the original) to NoData (Null) values. This is often called a "Set Null" operation. As a result, all outside cells are Null (still shown as white), the original "country" cells are still red, and their interior non-red cells still have values (gray).


Selecting the non-null cells provides the desired result:


As a visual confirmation, here is the original map overlaid to show that the "coastlines" have been properly respected:


Here, the white cells are still Null, making this final grid perfect for masking any future operations.

  • Wow! That looks exactly what I'm looking for. With which tool are you able to do it? QGIS? I assume that, but I can't see the option in QGIS 2.0. – Jorge Arévalo Nov 1 '13 at 22:09
  • Use GRASS: it has all these capabilities. – whuber Nov 1 '13 at 22:37
  • I'm a novice in GRASS, but this looks like similar: grass.osgeo.org/grass64/manuals/r.clump.html – Jorge Arévalo Nov 1 '13 at 22:47
  • Yes, that's the one. (This operation has a long history: the earliest account I have of it is Dana Tomlin's from the late 80's where he calls it "focal insularity.") – whuber Nov 1 '13 at 22:53
  • Well, I guess it's time to learn how to use GRASS. BTW, many thanks! – Jorge Arévalo Nov 1 '13 at 22:55

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.