On 21/08/11 23:06, Benson Kenduiywo wrote:
Hi! I would like to divide a 401 by 401 image into 20 equal blocks and then 
re-plot the image with the segments randomly distributed in it.
How can I do this?

For a 401 x 401 pixellation --- I don't know. If you use a 400 x 400 pixellation,
then the class "im" in the spatstat package can be used via the attached
function "shuffleIm()". The number of pixels in each dimension must be divisible by the number of blocks into which that dimension is subdivided. E.g. if you create your 20 blocks by making 4 divisions in the x-direction and 5 divisions in the y-direction then the number of pixels in the x-direction must be divisible by 4 and the number in the y-direction must be divisible by 5. Since 401 is prime
it's kind of hard to do any kind of subdividing with a 401 x 401 image.

Note that if X is an object of class "im" with a 401 x 401 pixellation, you can
convert it to one with a 400 x 400 pixellation via

    X <- as.im(X,dimyx=400)

This makes the pixel values of the new image equal to the values of the old
image at the closest pixel centre. This shouldn't (???) cause too much distortion.
Said he, optimistically.  (In the one experiment that I did, the images were
visually indistinguishable.)

If you have a 400 x 400 pixel image, say "X", of class "im" then

    Y <- shuffleIm(X,nx=4,ny=5)

gives you a new image in which the matrix of pixel values has been subdivided into a 5 x 4 array of 80 x 100 submatrices and these submatrices randomly shuffled. (Note that the rows of the matrix of pixel values in an object of class "im" correspond to the ***y*** direction and the columns correspond to the ***x*** direction.
See fortune("conventions") for a comment. :-) )

Hope this does what you want.

    cheers,

        Rolf Turner
shuffleIm <- function (X,nx,ny) {
verifyclass(X,"im")
ddd <- dim(X)
if(ddd[1]%%ny != 0) stop("Argument \"ny\" must divide first dimension of 
image.\n")
if(ddd[2]%%nx != 0) stop("Argument \"nx\" must divide second dimension of 
image.\n")
ky <- ddd[1]/ny
kx <- ddd[2]/nx
n  <- nx*ny
ind <- sample(1:n,n)
V <- matrix(NA,ddd[1],ddd[2])
for(k in 1:n) {
        j  <- k%%nx
        if(j==0) j <- nx
        i  <- (k-j)/nx + 1
        j1 <- (j-1)*kx + 1:kx
        i1 <- (i-1)*ky + 1:ky
        kr <- ind[k]
        j  <- kr%%nx
        if(j==0) j <- nx
        i  <- (kr-j)/nx + 1
        j2 <- (j-1)*kx + 1:kx
        i2 <- (i-1)*ky + 1:ky
        V[i1,j1] <- X$v[i2,j2]
}
X$v <- V
X}
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to