1

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)
user2543622
  • 5,760
  • 25
  • 91
  • 159

1 Answers1

2

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)

Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
  • We're dancing around each other a bit here ;). I like that you've wrapped into a function, so I'll delete. Any reason you're using `calc(x, mean)` instead of `mean`? (I might also suggest removing the `ifelse` - could change to `min(v, na.rm=TRUE) >= threshold`, or `all(v >= threshold, na.rm=TRUE)`). – jbaums Apr 28 '15 at 00:19
  • 1
    No. mean(x) would by clearer, so I have made that edit – Robert Hijmans Apr 28 '15 at 00:24
  • Out of curiosity, which cells' values are extracted if the `SpatialLines` fall along cell boundaries? – jbaums Apr 28 '15 at 00:28
  • 1
    It uses the cell below. `library(raster); r <- raster(nc=2, nr=2, xmn=0, xmx=2, ymn=0, ymx=2); values(r) <- 1:4; line <- spLines(rbind(c(0,1), c(2,1))); extract(r, line)` – Robert Hijmans Apr 28 '15 at 00:34
  • Guys, thanks for answering my questions over last few days...if black or similar color is not a good condition then would it be easier if i change my constraint to say that if pixels on an edge has more than 1 color then ignore the square to which that square belongs? – user2543622 Apr 28 '15 at 01:31