R:覆盖栅格图层的xy坐标



我有一个带有XY像素坐标的栅格,我想将其转换为经度和经度。

class       : RasterLayer 
dimensions  : 1617, 1596, 2580732  (nrow, ncol, ncell)
resolution  : 1, 1  (x, y)
extent      : 0, 1596, 0, 1617  (xmin, xmax, ymin, ymax)
coord. ref. : NA 
data source : C:janW1.png 
names       : janW1 
values      : 0, 255  (min, max)

我使用此处指定的公式计算了经度/经度坐标。

这导致了以下数据帧

heads(cords)
       lat       lon   x      y janW1
1 46.99401 -14.99122 0.5 1616.5     0
2 46.99401 -14.97367 1.5 1616.5     0
3 46.99401 -14.95611 2.5 1616.5     0
4 46.99401 -14.93856 3.5 1616.5     0
5 46.99401 -14.92100 4.5 1616.5     0
6 46.99401 -14.90345 5.5 1616.5     0

如何覆盖或创建具有经度/经度空间范围而不是影像坐标(XY 像素)的重复栅格?或者有没有更简单的方法将像素转换为纬度/纬度?

法典

library(raster)
test <- raster('janW1.png')
data_matrix <- rasterToPoints(test)
#  Calculate longitude.
lonfract = data_matrix[,"x"] / (1596 - 1)
lon = -15 + (lonfract * (13 - -15))
#  Calculate latitude.
latfract = 1.0 - (data_matrix[,"y"] / (1617 - 1))  
Ymin = log(tan ((pi/180.0) * (45.0 + (47 / 2.0))))
Ymax = log(tan ((pi/180.0) * (45.0 + (62.999108 / 2.0))))
Yint = Ymin + (latfract * (Ymax - Ymin))
lat = 2.0 * ((180.0/pi) * (atan (exp (Yint))) - 45.0)
# Make single dataframe with XY pixels and latlon coords.
latlon <- data.frame(lat,lon)
tmp <- data.frame(data_matrix)
cords <- cbind(latlon, tmp)

扬W1.png

更改栅格数据的投影并不像更改点(以及线、面)那么简单。这是因为,如果根据当前像元计算新坐标,则它们将不会位于常规栅格中。

您可以使用函数projectRaster(栅格包)来处理此问题。

library(raster)
test <- raster('janW1.png')
# In this case, you need to provide the correct crs to your data
# I am guessing. (this would be necessary for spatial data sets)
crs(test) <- '+proj=merc +datum=WGS84'
# you may also need to set the extent to actual coordinate values
# extent(test) <- c( , , ,) 
x <- projectRaster(test, crs='+proj=longlat +datum=WGS84') 

或者,您可以将计算的值插值到新栅格。有关示例,请参阅?raster::interpolate

您能否从头开始创建一个具有所需分辨率和空间范围的栅格,然后将值导入其中。 要创建栅格,您可以使用以下内容:

# Create a matrix of coordinates that define the limits of your raster
ex <- matrix(c(-20, -9.5, 20.5, 31.5), nrow = 2, ncol = 2, byrow = T)
# Turn those coordinates into an extent
ex <- extent(ex)
# Create a raster with the same dimensions as your original one
r <- raster(nrows = 1617, ncols = 1596)
# Set the extent of your raster
r <- setExtent(r, ex, keepres=F)

要将先前栅格中的值获取到刚刚创建的栅格中,可以使用:

test <- raster('janW1.png')
# Create vector of values from test
n <- values(test)
# Give values from test to r
values(r) <- n

我想我从您的代码中获得了正确的分辨率,但您需要将范围的四个坐标放在自己身上。 空白栅格的分辨率必须与原始栅格完全相同,否则将无法正常工作。 您创建的空白栅格会自动在 WGS84 中,因此您可能需要在输入数据后对其进行重新投影。

最新更新