近期在使用PostGIS处理数据时,需要按照矢量范围对栅格数据进行统计分析,但是在默认的数据库函数中没有现成的函数,因此自己简单写了一个函数,用于数据分析,代码如下所示:
-- 栅格数据按照范围统计
create or replace function public.zonal_statistics(
rast raster,
geom geometry,
nband integer default 1
)
returns summarystats
as $$
declare
stats summarystats;
begin
-- 判断坐标是否一致
if ST_SRID(rast) == ST_SRID(geom) then
with clip_raster as (
select ST_Clip(rast,nband,geom,ST_MinPossibleValue(ST_BandPixelType(rast, nband))) as ras
where ST_Intersects(geom,raster)
)
select (ST_SummaryStats(r.ras)).* into stats from clip_raster as r;
else
raise EXCEPTION 'geom srid is not equal to raster srid!';
return null;
end if;
return stats;
end;
$$
language 'plpgsql'
immutable
strict
parallel safe;
comment on function public.zonal_statistics is '栅格数据按照区域统计(总数、最大值、最小值、标准差、平均值)';