R Markdown

Load package & example

library(imager)
img <- load.example("parrots")

Check the dimension & save width and height

dim(img)
## [1] 768 512   1   3
width <- dim(img)[1]
height <- dim(img)[2]
plot(img)

Define function: make.vr

This function can make a variable outside of the function

make.vr <- function( x, name ){
  assign( name, x, envir = .GlobalEnv)
}

Split canvas 5 by 5

Using par function, split the canvas and make variables which contains the each of the sub-image. Then, draw the pictures into the splitted canvas.

par(mfrow=c(5,5), mar = c(0.1,0.1,0.1,0.1))
for (j in 1:5){
  for (i in 1:5){
    vr.name <- paste0("sub", j, i)
    imsub(img, (width/5)*(i-1) < x & x <  i * (width/5),
          (height/5)*(j-1) < y & y <  j * (height/5)) %>%
      make.vr(name = vr.name) %>%
      # save.image( file = paste0(vr.name,".jpg")) %>%
      plot(main = vr.name,
           axes = FALSE,
           xaxt="n", yaxt="n", 
           xlab = "", ylab = "", ann = FALSE )    
  }
}

# Back to normal canvas
par(mfrow = c(1,1))

Check the variable list

“sub11” means that this file is the sub-image of the parrot positioned at the first row and first coloum.

ls()
##  [1] "cx"       "cy"       "cz"       "depth"    "height"   "i"       
##  [7] "img"      "j"        "make.vr"  "spectrum" "sub11"    "sub12"   
## [13] "sub13"    "sub14"    "sub15"    "sub21"    "sub22"    "sub23"   
## [19] "sub24"    "sub25"    "sub31"    "sub32"    "sub33"    "sub34"   
## [25] "sub35"    "sub41"    "sub42"    "sub43"    "sub44"    "sub45"   
## [31] "sub51"    "sub52"    "sub53"    "sub54"    "sub55"    "vr.name" 
## [37] "width"    "x"        "y"

check the “sub31” file.

plot(sub31)