I have a table in postgis with a tiled raster and a table with polygons overlaying the raster. I want to get the number of pixels for each category (pixel value) that fall inside a specific polygon.
If I use the following query the result I am getting is wrong because, from what I understand, it hasn't unioned the tiles of the raster:
SELECT (pvc).value, SUM((pvc).count) As total
FROM (
SELECT ST_ValueCount(ST_Clip(myraster.rast, myvector.geom)) As pvc
FROM rastertable As myraster, vectortable As myvector
WHERE ST_Intersects(myraster.rast, myvector.geom) AND myvector.gid = 6
) As f
GROUP BY (pvc).value
ORDER BY (pvc).value;
With the following query the result I am getting is the right one, but it takes longer than it should, since it unions all the tiles before clipping
WITH
unionedraster AS (SELECT ST_Union(rast) As rast FROM rastertable)
SELECT (pvc).value, SUM((pvc).count) As total
FROM (
SELECT ST_ValueCount(ST_Clip(myraster.rast, myvector.geom)) As pvc
FROM unionedraster As myraster, vectortable As myvector
WHERE ST_Intersects(myraster.rast, myvector.geom) AND myvector.gid = 6
) As f
GROUP BY (pvc).value
ORDER BY (pvc).value;
I thought the following would work, but the results are the same with the first query (like no union took part).
SELECT (pvc).value, SUM((pvc).count) As total
FROM (
SELECT ST_ValueCount(ST_Union(ST_Clip(myraster.rast, myvector.geom))) As pvc
FROM rastertable As myraster, vectortable As myvector
WHERE ST_Intersects(myraster.rast, myvector.geom) AND myvector.gid = 6
) As f
GROUP BY (pvc).value
ORDER BY (pvc).value;
What is the correct way to do this?
Upon further investigation, it seems that the problem lies in the clipping of the raster tiles. I managed to export the result of the clipping as an image using this query:
COPY (
WITH clipraster As (
SELECT ST_Clip(myraster.rast, myvector.geom) As pvc
FROM rastertable As myraster, vectortable As myvector
WHERE ST_Intersects(myraster.rast, myvector.geom) AND myvector.gid = 6
)
SELECT encode(ST_AsPNG(
clipraster.pvc
), 'hex') AS png FROM clipraster
) TO 'clip.hex';
and the resulting image was the following
The blue line is the polygon to which the raster tiles should be clipped.
However, it is obvious that some of the tiles where not clipped.
Any idea to what is the problem?