简体   繁体   English

如何从 R 中的多边形值中删除光栅图像的像素

[英]How to remove pixels of a raster image from polygon values in R

I have a question to process an image.我有一个处理图像的问题。 I clipped some polygons from my raster, and then extracted the band values:我从栅格中剪裁了一些多边形,然后提取了波段值:

library(raster)
library(sf)

#Read raster
EX1<-raster::stack("ueg.tif")

#Plot raster
plotRGB(EX1, r = 1, g = 2, b = 3)

#Read shapefile
cxs <- sf::st_read("polygons_cx.shp")

#Clip polygon in raster
rr <- mask(EX1, cxs)

#Extract values RGB
ex <- raster::extract(rr, cxs, sp=T)

I would like to remove the pixel values from polygons 26 and 19 from the image (as they represent a color that I am using as a control in the analysis).我想从图像中删除多边形 26 和 19 的像素值(因为它们代表我在分析中用作控件的颜色)。 But I'm not sure how I would do that... I thought of something like transforming these values in NA and then applying a new mask, but I don't know how, could anyone give any tips?但我不知道我会怎么做......我想到了一些类似在 NA 中转换这些值然后应用新掩码的方法,但我不知道怎么做,有人可以提供任何提示吗?

ex[c(26,19)] <- NA

Without a reproducible example I'm not sure if ex is a single layer raster or a stack of several.如果没有可重现的示例,我不确定ex是单层栅格还是多层栅格。 But the basic principle is to replace values that match the values you want to replace with NA .但基本原则是替换与您要替换的值匹配的值NA Its an extension of the same thing in base R vectors:它是基本 R 向量中相同事物的扩展:

> Z = c(1,2,3,4,5)
> Z[Z %in% c(2,5)] = -999
> Z
[1]    1 -999    3    4 -999

Test with a tiny 3x3 raster, made from a matrix:使用由矩阵制成的微小 3x3 栅格进行测试:

> m = matrix(c(1,2,3,26,26,5,NA,19,9), 3,3)
> m
     [,1] [,2] [,3]
[1,]    1   26   NA
[2,]    2   26   19
[3,]    3    5    9
> ex = raster(m)
> as.matrix(ex)
     [,1] [,2] [,3]
[1,]    1   26   NA
[2,]    2   26   19
[3,]    3    5    9

and replace all 26s and 19s with NA :并用NA替换所有 26s 和 19s:

> ex[ex %in% c(26, 19)]  = NA

see what we got:看看我们得到了什么:

> as.matrix(ex)
     [,1] [,2] [,3]
[1,]    1   NA   NA
[2,]    2   NA   NA
[3,]    3    5    9
> 

This also seems to work okay if ex is a stack.如果ex是堆栈,这似乎也可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM