如何删除添加到使用writeGDAL创建的PNG图像的填充

时间:2017-06-12 14:14:49

标签: r png raster

我使用writeGDAL导出PNG格式的栅格数据,以用作Google地图上的图像叠加层。因此,图像需要具有正确的宽高比,并且必须完全符合光栅范围。

当我导出UTM投影栅格时,结果符合预期,但在我投射到LatLong系统后,生成的PNG在光栅区域周围有填充。

我需要做些什么才能摆脱这种填充?

UTM image without padding LatLong image with padding (black)

下面是示例代码,它会创建2个图像来演示问题。

library(raster)
library(rgdal)

r <- raster(xmn=742273.5, xmx=742702.5, ymn=6812515.5, ymx=6812995.5, ncols=144, nrows=161)
r <- setValues(r, 1:ncell(r))
projection(r) <- CRS('+proj=utm +zone=35 +south +datum=WGS84 +units=m +no_defs')
pr <- projectRaster(r, crs='+proj=longlat +datum=WGS84 +no_defs')

#Coerce to SpatialPixelsDataFrame and prepare for writeGDAL
rSpdf <- as(r, 'SpatialPixelsDataFrame')
prSpdf <- as(pr, 'SpatialPixelsDataFrame')
rSpdf$colors <- as.numeric(cut(rSpdf$layer, breaks = 255))
prSpdf$colors <- as.numeric(cut(prSpdf$layer, breaks = 255))
colorTable <- list(colorRampPalette(c('red', 'yellow', 'green4'))(256))

#Export in PNG format using writeGDAL
writeGDAL(rSpdf[, 'colors'], 'utm.png', drivername = 'PNG', type = 'Byte', mvFlag = 0, colorTables = colorTable)
writeGDAL(prSpdf[, 'colors'], 'geo.png', drivername = 'PNG', type = 'Byte', mvFlag = 0, colorTables = colorTable)

#Optionally, the rasters can be exported to view in a spatial package (eg SAGA-GIS)
#writeRaster(r, filename='utm.tif', format="GTiff", overwrite=TRUE)
#writeRaster(pr, filename='geo.tif', format="GTiff", overwrite=TRUE)

1 个答案:

答案 0 :(得分:1)

通过将投影栅格转换为点,然后将点强制转换为SpatialPixelsDataFrame(而不是强制栅格),将删除填充。

PNG without padding

library(raster)
library(rgdal)

r <- raster(xmn=742273.5, xmx=742702.5, ymn=6812515.5, ymx=6812995.5, ncols=144, nrows=161)
r <- setValues(r, 1:ncell(r))
projection(r) <- CRS('+proj=utm +zone=35 +south +datum=WGS84 +units=m +no_defs')
pr <- projectRaster(r, crs='+proj=longlat +datum=WGS84 +no_defs')

points <- rasterToPoints(pr, spatial = TRUE)
prSpdf <- as(points, 'SpatialPixelsDataFrame')

prSpdf$colors <- as.numeric(cut(prSpdf$layer, breaks = 10))
colorTable <- list(colorRampPalette(c('red', 'yellow', 'green4'))(11))

writeGDAL(prSpdf[, 'colors'], 'geo.png', drivername = 'PNG', type = 'Byte', mvFlag = 0, colorTables = colorTable)