R raster recognizing black color raster image

半腔热情 提交于 2019-12-30 11:49:18

问题


The code below produces two boxes on my image. I am planning to analyze pixels within those boxes further.

I want to put a condition that if along an edge of a box, there is a black color (or a similar color such as grey) pixel then don't proceed. How can i specify such condition?

In below example, in the case of the red square I don't want to proceed further as it has black pixels at the top right hand corner. While I would like to proceed in the case of green square as it doesn't have a black color pixel along it's edge.

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)

回答1:


That is not very well defined as in this case color is made of RGB values. But here is a general solution that you could adapt. I 'flatten' these to a single channel by taking the average, and then test for the smallest value being below a threshold (white is 255, 255, 255 in RGB, black is 0,0,0) at the boundary

proceed <- function(f, e, threshold) {
    lns <- as(as(e, 'SpatialPolygons'), 'SpatialLines')
    v <- unlist(extract(f, lns))
    ifelse( min(v, na.rm=TRUE) < threshold, FALSE, TRUE)
}

# flat <- mean(x) # not sophisticated see
# http://stackoverflow.com/questions/687261/converting-rgb-to-grayscale-intensity
flat <- sum(x * c(0.2989, 0.5870, 0.1140))
proceed(flat, extent(c(0,20,0,20)), 100)
proceed(flat, extent(c(21,35,0,10)), 100)

(much improved after seeing jbaums' solution; which is now gone)



来源:https://stackoverflow.com/questions/29907919/r-raster-recognizing-black-color-raster-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!