代码之家  ›  专栏  ›  技术社区  ›  UseR10085 dieghernan

ggRGB无法使用RStoolbox R包绘制蒙版图像

  •  1
  • UseR10085 dieghernan  · 技术社区  · 6 月前

    ggRGB无法绘制蒙版图像。这是一个最小的、可重复的例子

    library(terra)
    library(ggplot2)
    library(RStoolbox)
    
    lsat
    
    plotRGB(lsat,
            r = 3,
            g = 2,
            b = 1,
            stretch = 'hist')
    
    m <- draw(x="polygon", n = 5)
    
    lsat.masked <- crop(lsat, m, mask = T)
    
    ggplot() + ggRGB(img = lsat.masked,
                     r = 3,
                     g = 2,
                     b = 1,
                     stretch = 'hist',
                     ggLayer = T)
    

    enter image description here

    它返回以下错误

    网格错误。调用.graphics(C_raster、x$raster、x$x、x$y、x$width、x$height): 无法分配大小为67108864 Tb的内存块 此外:警告信息: 在矩阵(z,nrow=nrow(rr),ncol=ncol(rr)和byrow=TRUE)中: 数据长度[5888]不是行数[88]的子倍数或倍数

    1 回复  |  直到 6 月前
        1
  •  4
  •   UseR10085 dieghernan    6 月前

    这是一个不完整的答案,因为我在 ggRGB ,但您可以考虑使用 tidyterra 相反,请参阅reprex:

    library(terra)
    #> terra 1.8.5
    library(ggplot2)
    library(RStoolbox)
    #> This is version 1.0.0 of RStoolbox
    
    lsat
    
    plotRGB(lsat, r = 3, g = 2, b = 1, stretch = "hist")
    
    
    # SpatVector as standalone object
    
    m <- structure(list(geom = "POLYGON ((620947.959184 -412745.345369, 621312.951334 -414249.11303, 623254.709576 -414526.507064, 623897.095761 -413154.136578, 621152.354788 -411767.166405, 620947.959184 -412745.345369))"),
      class = "data.frame",
      row.names = c(NA, -1L)
    )
    
    # To SpatVector with the right CRS
    m <- vect(m$geom)
    crs(m) <- crs(lsat)
    
    
    plot(m, add = TRUE, col = "red")
    

    lsat.masked <- crop(lsat, m, mask = T)
    
    plotRGB(lsat.masked, r = 3, g = 2, b = 1, stretch = "hist")
    

    ggplot() +
      ggRGB(
        img = lsat.masked,
        r = 3,
        g = 2,
        b = 1,
        stretch = "hist",
        ggLayer = T
      )
    #> Warning in matrix(z, nrow = nrow(rr), ncol = ncol(rr), byrow = TRUE): data
    #> length [5793] is not a sub-multiple or multiple of the number of rows [92]
    #> Error in grid.Call.graphics(C_raster, x$raster, x$x, x$y, x$width, x$height, : cannot allocate memory block of size 67108864 Tb
    

    蒂蒂泰拉 您只需要在绘图功能之外执行拉伸,然后应用 geom_spatraster_rgb :

    # Alternative with tidyterra
    library(tidyterra)
    #> 
    #> Adjuntando el paquete: 'tidyterra'
    #> The following object is masked from 'package:stats':
    #> 
    #>     filter
    
    # Strecth as standalone fun, equivalent to plotRGB(..., stretch = "hist")
    
    lsat.masked_st <- stretch(lsat.masked, histeq = TRUE, scale = 255)
    
    ggplot() +
      geom_spatraster_rgb(data = lsat.masked_st, r = 3, g = 2, b = 1) +
      geom_spatvector(data = m, color = "red", fill = NA, linewidth = 3)
    

    plot with tidyterra

    创建于2025年1月5日 reprex v2.1.1

    推荐文章