I have a situation that is very similar to the issue described here. However, the accepted answer does not work for me.
I am essentially attempting to create polygons from contour lines generated using ST_Contour.
Here is my query:
WITH inputs AS (
SELECT 10 AS resample_factor
),
bbox AS (
SELECT
ST_Transform(
ST_MakeEnvelope(
-93.1585693359375,
46.71915170604123,
-92.24121093750001,
47.28109232255293,
4326
),
3857
) AS geom
),
-- clip raster to AOI
clip_rast AS (
SELECT
ST_Union(
ST_Clip(rast, 1, geom, TRUE)
) as rast
FROM _l_d30_cc_2060_standage_orig_cog
JOIN bbox ON ST_Intersects(rast, geom)
),
-- Resample raster
resampled_rast AS (
SELECT ST_Resample(
rast,
(ST_PixelWidth(rast) * resample_factor),
(ST_PixelHeight(rast) * resample_factor),
algorithm => 'Cubic'
) AS rast
FROM clip_rast, inputs
),
-- Generate contours
contours AS (
SELECT (ST_Contour(
rast,
bandnumber => 1,
level_interval => 10
)).*
FROM resampled_rast
),
rast_outline AS (
SELECT ST_ExteriorRing(ST_ConcaveHull(
(ST_DumpAsPolygons(ST_Reclass(rast, 1,
'(0-1000):1',
'16BUI', -1))).geom, 0)) AS geom
-- SELECT ST_Polygon(rast) AS geom
FROM resampled_rast
),
-- Create lines from combination of raster boundary and contours
all_lines AS (
SELECT
value,
(ST_Dump(
ST_Node(
ST_Collect(
ro.geom,
c.geom
)
)
)).geom AS geom
FROM contours AS c, rast_outline AS ro
),
-- Convert lines to polygons
all_polys AS (
SELECT
value,
(ST_Dump(ST_Polygonize(geom))).geom AS geom
FROM all_lines
GROUP BY value
)
SELECT value, geom
FROM all_polys;
When I select all_polys, I see this in pgAdmin's geometry viewer (a single polygon):
However, when I select all_lines I see this:
This is the result I am after (if these were polygons instead of linestrings).
I tried running a negative buffer on the exterior rast_outline to ensure that the contour lines overlapped with it, but that didn't help.


