Goal
In this post, we’ll learn how to create a single-band raster from scratch using PostGIS. This ability will be particularly useful as we begin exploring the relatively uncharted waters of the PostGIS Raster Module.
Purpose
Using ST_AddBand
and ST_MakeEmptyRaster
, we’ll create a single band, 8 bit unsigned integer raster. While it’s nothing fancy, it will help us better understand the mechanics of the Raster Module and it will also prove useful as a source of training data for the posts in the Raster Math Series.
Here, I’ll create a 250m resolution raster with a constant value. This method can easily create any other size and at whatever starting value the user may like. See the “All Together Now” section for some other common resolutions translated to decimal degrees.
Getting Started
First, lets create a table to hold the results of our operations.
|
|
Creating a Raster
Now, let’s go about constructing our raster. I’m creating my raster starting somewhere in the Colorado Rockies. You don’t need to do the same place or size, it’s completely up to you.
You can adjust where and how big your raster is by changing the upper left coordinates and the number of pixels wide and tall your raster should be. The upper left coordinate is the origin, so no raster cells will appear “upper” or “lefter” of it.
|
|
Et voilà! There you have it - a raster from scratch in PostGIS.
Now, If you did like me and left yourself with a massive raster, you may want to go ahead and tile it out to improve your query times. Additionally, this is a very common operation to perform on large rasers and it’s a good thing to be familiar with.
If you don’t want to tile your raster, you can go ahead and skip to the Adding Constraints section.
Tiling our New Raster
Tiling is a very common operation on large rasters. It allows you to build extremely fast spatial indexes on the data, vastly improving query times. For example, when I tried to load untiled large rasters into QGIS from PostGIS, it often crashes unless the data are tiled and indexed.
To tile your rasters, just do this:
Adding Constraints
There are a couple main reasons to add constraints to your raster tables after you’ve populated them. First, it improves query time by allowing the software to make certain assumptions about the geometry of your data. Second, it ensures that your data meet the standards PostGIS requires for various operations, such as alignment.
Add constraints by using the AddRasterConstraints
function. See the documentation for more details on which constraints you can add and what they do.
All Together Now
So, putting it all together, here’s what we’ve got:
There you have it!
Enjoy your new raster powers! I hope this was helpful to you.