为像素指定新值

2024-04-28 08:27:51 发布

您现在位置:Python中文网/ 问答频道 /正文

对于任何光栅数据集,我想为最大像素值分配1,为一行中的其他值分配0。在

我试了很多方法,但到目前为止还没有找到解决办法。在

下面是一个示例代码:

library(dplyr)
library(raster)
library(rgdal)
ras=raster("D:/Rtool/DATA/DigitalTerrainModel/SJER2013_DTM.tif")

这个光栅有5060 col and 4299 row。我想要的是给rowMax赋值"1",为其他的赋值"0"。在

我试过了:

^{pr2}$

但是,对于整个光栅高程值,我只有一个最大值,这不是我想要的。在

在python上,我使用了df.eq(df.max(1), 0).astype(int),那么如何在R上做同样的操作呢?在


Tags: 数据方法代码示例df光栅library像素
2条回答

数据准备

# Load packages
library(raster)

## Create example raster layer

# create an empty raster layer
r <- raster(ncol = 10, nrow = 10)
# assign values to cells
values(r) <- 1:ncell(r)
# Inspect the raster layer
plot(r)

解决方案1:此解决方案使用rasterdplyr包中的函数。在

^{pr2}$

解决方案2:这只使用raster

# Initialize an empty list to store the results of each row
raster_list <- list()

# A for loop to crop the image and assign 0 or 1 to see if it is the maximum of that row

for (i in 1:nrow(r)){
  # Get the extent of each row
  temp_ext <- extent(r, r1 = i, r2 = i, c1 = 1, c2 = ncol(r))
  # Crop the raster for only one row
  temp_r <- crop(r, temp_ext)
  # Get the maximum of one row
  temp_max <- max(values(temp_r), na.rm = TRUE)
  # Use raster algebra
  temp_r[temp_r != temp_max] <- 0
  temp_r[temp_r == temp_max] <- 1

  # Save the results to the raster_list
  raster_list <- c(raster_list, temp_r)

}

# Merge all rasters
m <- do.call(merge, raster_list)

# Examine the result
plot(m)

希望这有帮助。在

# create fake raster
fakeRaster <- raster(matrix(ncol = 10, nrow = 10))

# place values 1 to number of cells; so the right most value
# of each row should be the highest
values(fakeRaster) <- 1:ncell(fakeRaster)

# introduce higher values somewhere; test points
values(fakeRaster)[75] <- 300
values(fakeRaster)[1] <- 300
values(fakeRaster)[100] <- 300
values(fakeRaster)[81] <- 300
values(fakeRaster)[45] <- 300

# extract values as matrix
dataRaster <- values(fakeRaster, format = "matrix")

# get every row; evalute if equal to max, if yes give 1, if no give 0
# then transpose the output
dataRaster <- t(apply(dataRaster, 1, FUN = function(x) ifelse(x == max(x, na.rm = T), 1, 0) ))

# reassign value to raster
values(fakeRaster) <- dataRaster

顺便说一句,当你这样做的时候:

^{pr2}$

最后得到一个向量(我想),这给了你问题。您也可以尝试我在上面示例中使用的值(光栅,format=“matrix”)。在

相关问题 更多 >