File: st_histogram.sql

package info (click to toggle)
postgis 3.3.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 87,748 kB
  • sloc: ansic: 158,671; sql: 91,546; xml: 54,004; cpp: 12,339; sh: 5,187; perl: 5,100; makefile: 3,085; python: 1,205; yacc: 447; lex: 151; javascript: 6
file content (357 lines) | stat: -rw-r--r-- 13,592 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
----------------------------------------------------------------------
--
--
-- Copyright (c) 2009-2010 Pierre Racine <pierre.racine@sbf.ulaval.ca>
--
----------------------------------------------------------------------
-- NOTE: The ST_Histogram() function is already implemented in C. This plpgsql script is provided only as an example.
-- Defining the plpgsql function below might overwrite the current C implementation and brake other functions dependent on it.
-- Use with caution.
----------------------------------------------------------------------
-- _ST_Values(rast raster, band int)
-- Return all rast pixels values which center are in a geometry
-- Values are returned as groups of identical adjacent values (value, count)
-- in order to reduce the number of row returned.
----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION _ST_Values(rast raster, band int, geom geometry, OUT val float8, OUT count int)
    RETURNS SETOF record AS
    $$
    DECLARE
        geomintersect geometry;
        m int[];
        x integer := 0;
        y integer := 0;
        curval float8;
    BEGIN
        m := ST_GeomExtent2RasterCoord(rast, geom);
        -- Get the intersection between with the geometry.
        geomintersect := ST_Intersection(geom, ST_ConvexHull(rast));

        -- If the intersection is empty, return false
        IF m[1] IS NULL AND m[2] IS NULL AND m[3] IS NULL AND m[4] IS NULL THEN
            RETURN;
        END IF;

        count := 0;
        val := ST_Value(rast, band, m[1], m[2]);
        FOR x IN m[1]..m[3] LOOP
            FOR y IN m[2]..m[4] LOOP
                -- Check first if the pixel intersects with the geometry. Many won't.
                IF ST_Intersects(geom, ST_Centroid(ST_PixelAsPolygon(rast, x, y))) THEN
                    curval = ST_Value(rast, band, x, y);
                    IF NOT curval IS NULL THEN
                        IF curval = val THEN
                            count := count + 1;
                        ELSE
                            RETURN NEXT;
                            val := curval;
                            count := 1;
                        END IF;
                    END IF;
                END IF;
            END LOOP;
        END LOOP;
        RETURN NEXT;
        RETURN;
    END;
    $$
    LANGUAGE 'plpgsql' IMMUTABLE STRICT;

----------------------------------------------------------------------
-- _ST_Values(rast raster, band int)
-- Return all rast pixels values
-- Values are returned as groups of identical adjacent values (value, count)
-- in order to reduce the number of row returned.
----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION _ST_Values(rast raster, band int, OUT val float8, OUT count int)
    RETURNS SETOF record AS
    $$
    DECLARE
        x int;
        y int;
        width int := ST_Width(rast);
        height int := ST_Height(rast);
        curval float8;
    BEGIN
        count := 0;
        val := ST_Value(rast, band, 1, 1);
        FOR x IN 1..width LOOP
            FOR y IN 1..height LOOP
                curval = ST_Value(rast, band, x, y);
                IF NOT curval IS NULL THEN
                    IF curval = val THEN
                        count := count + 1;
                    ELSE
                        RETURN NEXT;
                        val := curval;
                        count := 1;
                    END IF;
                END IF;
            END LOOP;
        END LOOP;
        RETURN NEXT;
        RETURN;
    END;
    $$
    LANGUAGE 'plpgsql';

----------------------------------------------------------------------
-- ST_Histogram(rast raster, band int) group
-- Return a set of (val, count) rows forming the value histogram for a raster
----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION ST_Histogram(rast raster, band int, OUT val double precision, OUT count bigint)
RETURNS SETOF record
    AS $$
    SELECT (vc).val val, sum((vc).count)::bigint count
    FROM (SELECT _ST_Values($1, $2) vc) foo GROUP BY (vc).val;
    $$
    LANGUAGE SQL;

CREATE OR REPLACE FUNCTION ST_Histogram(rast raster, OUT val double precision, OUT count bigint)
RETURNS SETOF record
    AS $$
    SELECT (vc).val val, sum((vc).count)::bigint count
    FROM (SELECT _ST_Values($1, 1) vc) foo GROUP BY (vc).val;
    $$
    LANGUAGE SQL;

----------------------------------------------------------------------
-- ST_Histogram(rast raster, band int, geom geometry) group
-- Return a set of (val, count) rows forming the value histogram for the area of a raster covered by a polygon geometry.
-- Pixels are selected only when their center intersects the polygon
----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION ST_Histogram(rast raster, band int, geom geometry, OUT val double precision, OUT count bigint)
RETURNS SETOF record
    AS $$
    SELECT (vc).val val, sum((vc).count)::bigint count
    FROM (SELECT _ST_Values($1, $2, $3) vc) foo GROUP BY (vc).val;
    $$
    LANGUAGE SQL;

CREATE OR REPLACE FUNCTION ST_Histogram(rast raster, geom geometry, OUT val double precision, OUT count bigint)
RETURNS SETOF record
    AS $$
    SELECT (vc).val val, sum((vc).count)::bigint count
    FROM (SELECT _ST_Values($1, 1, $2) vc) foo GROUP BY (vc).val;
    $$
    LANGUAGE SQL;

----------------------------------------------------------------------
-- This variant might be faster (not using an intermediate _ST_Values function)
----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION ST_Histogram2(rast raster, band int, OUT val double precision, OUT count bigint)
RETURNS SETOF record
    AS $$
    SELECT val, count(*) count
    FROM (SELECT ST_Value($1, $2, x, y) val FROM generate_series(1, ST_Width($1)) x , generate_series(1, ST_Height($1)) y) foo
    GROUP BY val;
    $$
    LANGUAGE SQL IMMUTABLE;

SELECT (hist).val val, sum((hist).count) count
FROM (SELECT ST_Histogram2(rast, 1) hist FROM srtm_22_03_tiled_10x10) foo
GROUP BY val
ORDER BY count DESC

----------------------------------------------------------------------
-- Other variant (not grouping in the function) (not using an intermediate _ST_Values function)
----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION ST_Histogram3(rast raster, band int, OUT val double precision)
RETURNS SETOF double precision
    AS $$
    SELECT ST_Value($1, $2, x, y) val FROM generate_series(1, ST_Width($1)) x , generate_series(1, ST_Height($1)) y;
    $$
    LANGUAGE SQL IMMUTABLE;

SELECT val, count(*) count
FROM (SELECT ST_Histogram3(rast, 1) val FROM srtm_22_03_tiled_10x10) foo
GROUP BY val
ORDER BY count DESC

SELECT ST_Histogram3(rast, 1) val, count(*) count FROM srtm_22_03_tiled_10x10
GROUP BY val
ORDER BY count DESC

----------------------------------------------------------------------
-- This might actually be the fasters query to get the histogram
----------------------------------------------------------------------
SELECT val, count(*) count
FROM (SELECT ST_Value(rast, 1, x, y) val
      FROM generate_series(1, 10) x, generate_series(1, 10) y, srtm_22_03_tiled_10x10
     ) foo
GROUP BY val
ORDER BY count DESC

----------------------------------------------------------------------
-- Example 1: Query returning the histogram for a raster tile (one at a time)
----------------------------------------------------------------------

-------------------------------
-- The subquery gets the histogram for each tile
-- The main query split the resulting records in their two components (val & count)
-------------------------------
SELECT rid,
       (hist).val,
       (hist).count
FROM (SELECT rid,
             ST_Histogram(rast) hist
      FROM srtm_22_03_tiled_25x25
      WHERE rid = 234
     ) foo
ORDER BY (hist).count DESC

----------------------------------------------------------------------
-- Example 2: Query returning the complete histogram for a tiled raster coverage
-  (might be very long)
----------------------------------------------------------------------

-------------------------------
-- The subquery gets the histogram for each tile
-- The main query split the resulting records in their two
-- components (val & count) and sum the count over all the tiles
-------------------------------
SELECT (hist).val,
       SUM((hist).count) count
FROM (SELECT rid,
             ST_Histogram(rast) hist
      FROM srtm_22_03_tiled_25x25
     ) foo
GROUP BY (hist).val
ORDER BY count DESC

----------------------------------------------------------------------
-- Example 3: Query returning the mean pixel value for each tile of a
-- tiled raster (might be very long)
----------------------------------------------------------------------

-------------------------------
-- The subquery gets the histogram for each tile
-- The main query split the resulting records in their two
-- components (val & count) computing a mean value per tile at the same time
-------------------------------
SELECT rid,
       geom,
       round(((SUM((hist).val * (hist).count)) / SUM((hist).count))::numeric, 2) meanval
FROM (SELECT rid,
             rast::geometry geom,
             ST_Histogram(rast) hist
      FROM srtm_22_03_tiled_25x25
     ) foo
GROUP BY rid, geom
ORDER BY rid;

----------------------------------------------------------------------
-- Example 4: Query returning the most frequent pixel value for each tile
-- of a tiled raster (might be very long)
-- This example requires an aggregate function tracking the value
-- associated with the maximum count
----------------------------------------------------------------------
CREATE TYPE dblIntSet AS (
    maxval double precision,
    val int
);

CREATE OR REPLACE FUNCTION maxFromDblIntSet(dblIntSet, dblIntSet) RETURNS dblIntSet AS
$$ SELECT CASE WHEN $1.maxval>$2.maxval THEN $1 ELSE $2 END $$
LANGUAGE sql;

CREATE OR REPLACE FUNCTION valFromDblIntSet(dblIntSet) RETURNS int AS
$$ SELECT $1.val $$
LANGUAGE sql;

CREATE AGGREGATE maxFromDblIntSet (
    BASETYPE = dblIntSet,
    SFUNC = maxFromDblIntSet,
    STYPE = dblIntSet,
    INITCOND = '(0,0)',
    FINALFUNC = valFromDblIntSet
);

-------------------------------
-- Actual query
-- The subquery gets the histogram for each tile
-- The main query split the resulting records in their two
-- components (val & count) and compute the maximum count and its associated value
-------------------------------
SELECT rid,
       geom,
       maxFromDblIntSet(ROW((hist).count, (hist).val::int)) mostfreqval,
       MAX((hist).count) count
FROM (SELECT rid,
             rast::geometry geom,
             ST_Histogram(rast) hist
      FROM srtm_22_03_tiled_25x25
     ) foo
GROUP BY rid, geom
ORDER BY rid

----------------------------------------------------------------------
-- Example 5: Query returning the most frequent pixel value per polygon from a raster
-- Do not use when the raster is big, in this case it should be tiled and
-- the next example (6) should be used instead
----------------------------------------------------------------------
SELECT polyid,
       geom,
       maxFromDblIntSet(ROW((hist).count, (hist).val::int)) mostfreqval,
       MAX((hist).count) count
FROM (
      SELECT polyid,
             geom,
             ST_Histogram(rast, geom) hist
      FROM srtm_22_03, mypolygons
      WHERE ST_Intersects(rast, geom)
     ) foo
GROUP BY polyid, geom

----------------------------------------------------------------------
-- Example 6: Query returning the most frequent pixel value per polygon on a tiled raster coverage
----------------------------------------------------------------------

-------------------------------
-- The first subquery gets the histogram for each tile
-- The second subquery split the resulting records in their two
-- components (val & count) and sum the count for each polygon-value couple
-- The main query compute the maximum count and its associated value
-------------------------------
SELECT polyid,
       geom,
       maxFromDblIntSet(ROW(count, val)) mostfreqval,
       MAX(count) count
FROM (SELECT polyid,
             geom, (hist).val::int val,
             SUM((hist).count) count
      FROM (SELECT polyid,
                   geom,
                   ST_Histogram(rast, geom) hist
            FROM srtm_22_03_tiled_25x25, mypolygons
            WHERE ST_Intersects(rast, geom)
           ) foo
      GROUP BY polyid, geom, (hist).val
     ) bar
GROUP BY polyid, geom

----------------------------------------------------------------------
-- Example 7: Query returning the mean pixel value per polygon on a tiled raster coverage
----------------------------------------------------------------------

-------------------------------
-- The first subquery gets the histogram for each tile
-- The second subquery split the resulting records in their two
-- components (val & count) and sum the count for each polygon-value couple
-- The main query compute the mean pixel value
-------------------------------
SELECT polyid,
       geom,
       round((SUM(val * count) / SUM(count))::numeric, 2) meanval
FROM (SELECT polyid,
             geom, (hist).val::int val,
             SUM((hist).count) count
      FROM (SELECT polyid,
                   geom,
                   ST_Histogram(rast, geom) hist
            FROM srtm_22_03_tiled_25x25, mypolygons
            WHERE ST_Intersects(rast, geom)
           ) foo
      GROUP BY polyid, geom, (hist).val
     ) bar
GROUP BY polyid, geom