Goal
In this post, we’ll learn how to create a multi-band raster from an existing raster in PostGIS.
Purpose
This technique is useful for more than the simulation I discussed in the first and second posts in this series. It allows us to combine the data of many rasters into a single raster, which can make the data a little easier to work with.
In this post, I’ll demonstrate how I created the initial raster I used in my post on writing multi-band ST_MapAlgebra
callback functions.
Getting Started
What I wanted when I set out was a raster made up of two 8-bit Unsigned Integer bands: the first with all cell values set to 5 and the second with values all ranging between 1 and 5 roughly based on a normal distribution.
In practice, we rarely modify existing raster tables when doing analysis or data management (but you can). We typically create new ones. Bearing this in mind, it didn’t make sense to begin with a two band raster. Especially considering that we can’t initialize a raster band with an existing value. We have to modify the cells with an ST_MapAlgebra
callback, and ST_MapAlgebra
only returns single band rasters.
Using Map Algebra
So, we begin with a single band raster:
|
|
With our single band raster created, let’s see what we can do about adding another. As I said above, we’ll need an ST_MapAlgebra
callback function to do the job. Here’s what that function looks like:
|
|
When we created our starter
raster, we added a band to the empty raster in the torast
position of the ST_AddBand
function (see docs, Varaiant 5).
This time, we’ll specify starter
as the torast
(instead of an empty raster) and we’ll specify the results of our ST_MapAlgebra
callback function as the fromrast
. We also stipulate that this new band should be band two, although this isn’t strictly necessary as omitting the band value will automatically append the new band to the end of the raster’s band list.
|
|
Just like that, you’ve got a new two band raster! This technique is quite useful if you want to perform an operation on a few bands of a raster, then store the result in the same raster in a new band.
Using Existing Rasters
Of course, you can do the same sort of thing using only existing rasters. Perhaps you need to combine several rasters about climate into a single one to use in a model. You can do so like this:
|
|
I hope this post was useful to you. To learn more about ST_MapAlgebra
and its callbacks, make sure to check out my Raster Math Series.