从 R 中的 .tif 中提取颜色

Extracting colors from .tif in R

我正在尝试修改 .tif 中的颜色。我上传了一个文件 here.

通读并快速查看,似乎所有信息都在那里。

library(dplyr);library(ggplot2)
library(raster)
pic <- raster::brick(x="SUB_IMG_8020 (1)_A_36x36.tif")
pic
class      : RasterBrick 
dimensions : 619, 1060, 656140, 3  (nrow, ncol, ncell, nlayers)
resolution : 1, 1  (x, y)
extent     : 0, 1060, 0, 619  (xmin, xmax, ymin, ymax)
crs        : NA 
source     : SUB_IMG_8020 (1)_A_36x36.tif 
names      : SUB_IMG_8020_.1._A_36x36.1, SUB_IMG_8020_.1._A_36x36.2,     SUB_IMG_8020_.1._A_36x36.3 
min values :                          0,                          0,                          0 
max values :                        255,                        255,                        255 

plotRGB(pic)

到目前为止一切顺利。现在我想手动更改颜色,因此,我将对象转换为 data.frame 以便使用 ggplot2。然而,在这个过程中的某个地方,我正在丢失信息。有谁知道如何解决这个问题?

test_spdf <- as(pic, "SpatialPixelsDataFrame")
#extract colors
test_df <- as.data.frame(test_spdf) %>% 
   mutate(cols = rgb(SUB_IMG_8020_.1._A_36x36.1,   
                SUB_IMG_8020_.1._A_36x36.2, 
                SUB_IMG_8020_.1._A_36x36.3, 
                maxColorValue = 255)) %>%
   dplyr::select(x, y, cols) %>% arrange(x) %>%
   tibble::rowid_to_column("nr")


ggplot(test_df, aes(x=x, y=y)) +  
  geom_raster(aes(fill=cols))+
  theme_void()+
  theme(legend.position="none")+
  coord_fixed()

这符合预期。但是当指定 scale_fill_manual 时,我得到一个看起来很奇怪的图,这表明提取颜色时出了点问题:

 ggplot(test_df, aes(x=x, y=y)) +  
  geom_raster(aes(fill=cols))+
  scale_fill_manual(values=c(test_df$cols))+
  theme_void()+
  theme(legend.position="none")+
  coord_fixed()

如何正确访问似乎存在的颜色(plotRGB 的输出)。谢谢!

这是使用 scale_fill_identity() 而不是 scale_fill_manual 的好地方。否则,填充颜色的分配顺序将与您预期的顺序不同。

ggplot(test_df, aes(x=x, y=y)) +  
  geom_raster(aes(fill=cols))+
  theme_void()+
  theme(legend.position="none")+
  scale_fill_identity() +     # SWEET SWEET COLOR ASSIGNMENT MAGIC
  coord_fixed()

您的 scale_fill_manual 方法不起作用的原因是 ggplot 首先确定分配给填充美学的值列表,并按字母顺序创建组。所以十六进制代码“#290000”[在我们可以在这里看到的 JPEG 中]定义了第一组将接收填充颜色的点,“#320500”第二组,依此类推。当您使用 scale_fill_manual 时,ggplot 会获取您提供的颜色矢量并将它们依次分配给每个组。以数据框的原始顺序为它提供完整的颜色列表将导致颜色混乱,因为它们的顺序(和长度)与 scale_fill_manual 所期望的不同。如果您想在此处使用 scale_fill_manual,您可以先获取(按字母顺序排序的)颜色列表,然后将其作为填充值列表提供。

library(dplyr)
test_df %>% 
  arrange(cols) %>%        # sort alphabetically
  distinct(cols) %>%       # drop dupes
  pull(cols) -> col_list   # extract column as vector and save to col_list

ggplot(test_df, aes(x=x, y=y)) +  
  geom_raster(aes(fill=cols))+
  theme_void()+
  theme(legend.position="none")+
  scale_fill_manual(values=c(col_list))+
  coord_fixed()