【问题标题】:R raster - counting black pixels within an extentR光栅 - 计算范围内的黑色像素
【发布时间】:2015-05-06 01:12:19
【问题描述】:

我的问题基于this。该页面上的答案解决了我当时面临的问题。我的新问题是 -

下面的代码在我的图像上绘制了两个正方形。对于每个正方形,我想计算其中有多少黑色像素。

我最初的问题答案表明我可以使用flat <- sum(x * c(0.2989, 0.5870, 0.1140)) 将 RGB 展平。在这种情况下,我想计算颜色值低于 25 的像素。

我尝试利用之前帖子中建议的答案,但无法弄清楚如何在某个范围内查看。

library(raster)
r1 <- brick(system.file("external/rlogo.grd", package="raster"))
x <- crop(r1, extent(0,50,0,50))
plotRGB(x)
plot(extent(c(0,20,0,20)), lwd=2, col="red", add=TRUE)
plot(extent(c(21,35,0,10)), lwd=2, col="Green", add=TRUE)

【问题讨论】:

    标签: r image image-processing raster


    【解决方案1】:
    library(raster)
    r1 <- brick(system.file("external/rlogo.grd", package="raster"))
    x <- crop(r1, extent(0,50,0,50))
    flat <- sum(x * c(0.2989, 0.5870, 0.1140))
    plot(flat, col=gray(seq(0,1,0.1)))
    e1 <- extent(c(0,20,0,20))
    e2 <- extent(c(21,35,0,10))
    plot(e1, col='red', add=TRUE)
    plot(e2, col='blue', add=TRUE)
    
    
    # I am using a cut-off of 100 to get some cells below that threshold.
    sum(extract(flat, e1) < 100)
    sum(extract(flat, e2) < 100)
    
    # for _very_ large files/extents this could be done to avoid RAM limitations
    x <- crop(flat, e2)
    y <- reclassify(x, matrix(c(-Inf, 100, 1, 100, Inf, 0), byrow=TRUE)) 
    freq(y, value=1)
    

    【讨论】:

    • 以灰度绘制图像背后有什么目的 - plot(flat, col=gray(seq(0,1,0.1)))?我用 plot(flat) 替换了那个命令,最后两个命令仍然得到相同的答案..
    • 绘图仅用于绘图目的。我用灰度来说明你所说的“黑色像素”
    • 感谢您的确认。
    猜你喜欢
    • 2022-10-07
    • 2015-07-06
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    • 2019-01-23
    • 2013-10-13
    相关资源
    最近更新 更多