Skip to content

Instantly share code, notes, and snippets.

@boshek
Last active September 26, 2018 19:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save boshek/38121b9c14792df9522f0b7daea03446 to your computer and use it in GitHub Desktop.
Save boshek/38121b9c14792df9522f0b7daea03446 to your computer and use it in GitHub Desktop.
Comapring POSTGIS rasterization with fasterize
library(sf)
library(dplyr)
library(fasterize)
shape <- "MULTIPOLYGON (((1126095 1246073, 1126221 1246053, 1126358 1246059, 1126383 1245909, 1126457 1245800, 1126605 1245831, 1126756 1245812, 1126812 1245652, 1126805 1245526, 1126841 1245377, 1126859 1245227, 1126868 1245077, 1126881 1244927, 1126949 1244805, 1126954 1244667, 1126806 1244635, 1126658 1244602, 1126508 1244591, 1126358 1244591, 1126283 1244701, 1126248 1244825, 1126256 1244951, 1126219 1245100, 1126197 1245249, 1126175 1245374, 1126145 1245498, 1126114 1245622, 1126025 1245743, 1125919 1245839, 1125803 1245897, 1125638 1245928, 1125547 1246037, 1125693 1246143, 1125842 1246150, 1126095 1246073)))"
tictoc::tic()
## Actually connect to the database
conn <- DBI::dbConnect(RPostgreSQL::PostgreSQL(),
host = "localhost",
dbname = "postgis_in_action",
user = "postgres")
DBI::dbSendQuery(conn, "CREATE SCHEMA raster_fun;")
DBI::dbSendQuery(conn, glue::glue("CREATE TABLE raster_fun.fooraster(rast) AS
SELECT ST_AsRaster(
ST_Buffer(
ST_GeomFromText(
'{shape}', 3005
), 50)
,5000,5000);", shape = shape))
out_of_postigs <- rpostgis::pgGetRast(conn, c("raster_fun","fooraster"))
DBI::dbSendQuery(conn, "DROP SCHEMA raster_fun CASCADE;")
DBI::dbDisconnect(conn)
tictoc::toc()
tictoc::tic()
poly <- st_sf(st_as_sfc(shape, crs = 3005)) %>%
st_buffer(dist = 50)
r <- raster(poly, nrow = 5000, ncol = 5000)
out_of_fasterize <- fasterize(poly, r)
tictoc::toc()
par(mfrow=c(2,1))
plot(out_of_postigs, main = "postgis")
plot(out_of_fasterize, main = "fasterize")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment