Advanced cell color manipulation with masks in the RasterExpressionEvaluator

Liz Sanderson
Liz Sanderson
  • Updated


There are often occasions where we want to modify raster data, but only within certain boundaries. For example, we want to change the black pixels surrounding a non-rectangular image with white, but we don't want to affect any black pixels within the image.

To do this, we will generate a raster mask from the image boundary polygon, then use it to constrain the color replacement to the pixels outside of that boundary.

The attached sample workspace generates a simple image and boundary polygon. You can replace the creator transformers with your own image and polygon data.

The first step in the process is to create the mask by taking a copy of the image and forcing it to a single Uint8 band with all values set to 255. We do this in order to retain the resolution and location from the original image, using the RasterInterpretationCoercer and RasterCellValueReplacer. 

Next, we use a Clipper to clip the mask by the boundary polygon, while retaining the mask image extents. The Inside port will leave us with a mask that has the value 255 inside the boundary and 0 outside, while the Outside port will give us the reverse.

Finally, we use the RasterExpressionEvauator, in the two raster input mode, to do the actual color change. For each output band, we use the @if() function look for pixels in the original image with the color 0,0,0 AND pixels in the mask image with the value 0, to limit the change to pixels outside the boundary:

@if ((A[0]==0 && A[1]==0 && A[2]==0 && B[0]==0), 255, A[0])

This function is a little cryptic, so let's break it down. The @if() function take three values, separated by commas:

  • the text expression
  • value to return if test passes
  • value to return if test fails

Our passed return value is 255, while the failed return value is the original value of the pixel. In the test expression, we are testing whether the red, green and blue values of the original image (A) are all 0 AND whether the value of the mask image is 0. '&&' is the logical AND operator.

We are outputting an RGB image, so we need a copy of the expression for each of the output red, green and blue bands. The only difference in each copy is the failure output, which is set to the applicable input band.


The output image will have all the black areas outside the boundary set to white.

This is a simple illustration of how to use a mask. You can use it to do more complex operations, like dimming parts of the image outside areas of interest. In that case, you would simply modify the test expression to only test B[0]==0, and set the passed output to A[0]-50.

For more on this powerful transformer, see Simple Examples Using the RasterExpressionEvaluator Transformer

Was this article helpful?



Please sign in to leave a comment.