问题
I have the function drawRect
which will draw a rectangle on a n x m x 3
matrix (one layer for each color channel).
It takes in 2 main parameters: the rectangle params c(xleft, xright, ytop, ybottom)
and the image matrix im
drawRect <- function(rect, im, color=2){
int = 255
im[rect[3]:rect[4],rect[1],color] = int
im[rect[3]:rect[4],rect[2],color] = int
im[rect[3],rect[1]:rect[2],color] = int
im[rect[4],rect[1]:rect[2],color] = int
return(im)
}
The function works as its supposed to. However, I am trying to draw ~2000 rectangles on a 3400 x 5200 x 3
image and this is where it becomes EXTREMELY slow.
I have a 2000 x 4
matrix of rectangle parameters which looks something like:
#xleft xright ytop ybottom
313 413 143 243
413 513 143 243
513 613 143 243
613 713 143 243
713 813 143 243
811 911 143 243
...
Any ideas on how to speed this up?...
Note my images are read in using the readJPEG
function of the jpeg
package and are written to a file using the writeJPEG
function.
Edit: I've tried passing in the matrix of rectangle params and using an apply function to avoid multiple calls of the function, but still no significant improvement.
drawRect2 <- function(rects, im, color=2, int = 255){
x=apply(rects, 1, function(rect){
im[rect[3]:rect[4],rect[1],color] = int
im[rect[3]:rect[4],rect[2],color] = int
im[rect[3],rect[1]:rect[2],color] = int
im[rect[4],rect[1]:rect[2],color] = int
})
return(im)
}
回答1:
I don't know if there is a vectorized version of rect
but you can use poylygon
which is vectorized . You need just to add NA between rectangles. This answer is inspired from the excellent answer here.
cuts <- function(x)
{
n <- length(x) %/% 4
map <- rep(c(rep(TRUE,4),FALSE), n)
result <- rep(NA, n*5)
result[map] <- x
result
}
n <- 2000
xbottom <- runif(n)
ybottom <- runif(n)
xtop <- xbottom+runif(n)
ytop <- ybottom+runif(n)
x <- cbind(xbottom,xbottom,xtop,xtop)
y <- cbind(ybottom,ytop,ytop,ybottom)
cols <- heat.colors(n)[order(x[,1])]
plot(0, xlim=c(min(x),max(x)), ylim=c(min(y),max(y)))
polygon(x=cuts(t(x)), y=cuts(t(y)), col=cols)
This will creates the 2000 rectangles instantaneously.

来源:https://stackoverflow.com/questions/15627674/efficiency-of-drawing-rectangles-on-image-matrix-in-r