Selecting only pixels of particular range of values with ST_Reclass

This raster question comes up quite a bit on PostGIS mailing lists and stack overflow and the best answer often involves the often forgotten ST_Reclass function that has existed since PostGIS 2.0. People often resort to the much slower though more flexible ST_MapAlgebra or dumping out their rasters as Pixel valued polygons they then filter with WHERE val > 90, where ST_Reclass does the same thing but orders of magnitude faster.

The question goes something like this

I have this raster measuring contaminent levels of ammonia in the pixel values in band 1, and I want to rank contamination by 0 low, 1 medium, 2 high. Then I want to find the area of this contamination or do some other crazy geometric thing to it.

The basic strategy is to reduce your raster into a simpler one that contains 0s, 1s, 2s where 0 ends up being marked as nodata. Then you mark off 0 (or whatever number you choose) as nodata. In the end you end up with a fairly simple raster that is easy to vectorize or keep as raster and do stats on.

So for example here we use ST_Reclass to reclassify all pixel values >= 0 and <= 90 as 0, >90 < 100 as 1, and 100 to 1000 as 2. The last argument makes value of 0 represent nodata.

1SELECT ST_Reclass(rast, 1,
2	'[0-90]:0,(90-100):1,[100-1000):2',
3		'4BUI', 0) As rast
4    FROM  sometable
5    WHERE filename = '123.tif';

Will give you a new set of rasters that have pixel values of 1,2 and nodata.

Now the next part of the question goes, how do you do geometric operations on this new set, like for example computing the centroid in this case of each toxic level area

 1WITH cgeoms AS ( SELECT ST_DumpAsPolygons(
 2	ST_Reclass(rast, 1,
 3	'[0-90]:0,(90-100):1,[100-1000):2',
 4		'4BUI', 0), 1
 5	) AS gval
 6    FROM  sometable
 7    WHERE filename = '123.tif' )
 8SELECT ST_Centroid(
 9	ST_Union( (gval).geom ) ) As geom,
10	(gval).val
11FROM cgeoms
12GROUP BY (gval).val;

There are also many stats you can do with functions such as ST_Histogram and ST_ValueCount so you do not have to resort to vectorizing your raster to do basic stats on it.