I would like to crop an image of 256x256 pixels into many small images of 64x64 pixels.
I use the function:
crop(raster,extent(xmin,xmax,ymin,ymax))
I got images of 64x64 pixels as I want but there is a white border, means the cropped image is "compressed" into a 64x64 pixels.
It comes from this warning message but I do not know how to avoid it.
Warning message:
In couldBeLonLat(x) : CRS is NA. Assuming it is longitude/latitude
Here my code:
#load picture
setwd("C:/Users/PC/Desktop/R/Image test/New folder/")
img_path <- "Test6.jpg"
raster <- brick(img_path, package="raster", full.names=TRUE)
size = 64
gap <- 8
#number of time to paste image
number_im_h <- dim(raster)[2]/gap-(size/gap)+1
number_im_v <- dim(raster)[1]/gap-(size/gap)+1
r_list <- list()
ind <-0
for(k in 1:number_im_h){
for(j in 1:number_im_v){
ind <- ind+1
r_list[[ind]] <- crop(raster,extent(as.numeric(j-1)*gap,as.numeric(j-1)*gap+size,as.numeric(k-1)*gap,as.numeric(k-1)*gap+size))
setwd("C:/Users/PC/Desktop/R/Image test/cropped")
slice <- r_list[[ind]]
jpeg(filename=paste0("image_",ind,".jpg"), width=size,height=size,units="px")
plotRGB(slice)
dev.off()
}
}
How to solve it ?
Here is a slightly rewritten version, a bit simpler and showing how the warning should go away. For better help you should provide an example dataset (image)
library(raster)
raster <- brick("Test6.jpg")
# set the crs so that plot knows the data are not lonlat
crs(raster) <- "+proj=utm +zone=1 +datum=WGS84"
size = 64
gap <- 8
n_h <- ncol(raster)/gap - (size/gap)+1
n_v <- nrow(raster)/gap - (size/gap)+1
r_list <- list()
path <- "C:/Users/PC/Desktop/R/Image test/cropped"
ind <- 0
for(k in 1:n_h){
for(j in 1:n_v){
ind <- ind+1
e <- extent((j-1)*gap, (j-1)*gap+size, (k-1)*gap, (k-1)*gap+size)
r_list[[ind]] <- crop(raster, e)
f <- file.path(path, paste0("image_",ind,".jpg"))
jpeg(filename=f, width=size, height=size, units="px")
plotRGB(r_list[[ind]])
dev.off()
}
}