from magick-image to rasterBrick - r

I have an image that must be processed with the package magick. So the output belongs to class magick-image. I need to transform it to a class rasterBrick for further processing.
How can I transform an object magick-image to rasterBrick? I need to avoid saving and loading an intermediate temp file.
library(magick)
library(raster)
# load sample image
i <- image_read("https://i.picsum.photos/id/10/2500/1667.jpg?hmac=J04WWC_ebchx3WwzbM-Z4_KC_LeLBWr5LZMaAkWkF68")
# does not work
r <- raster::raster(i)
# workaround that I must avoid
image_write(i,"temp_image.jpg")
t <- brick("temp_image.jpg")
t

You can do this:
library(terra)
r <- as.raster(i) |> as.matrix() |> rast()
r
#class : SpatRaster
#dimensions : 1667, 2500, 3 (nrow, ncol, nlyr)
#resolution : 1, 1 (x, y)
#extent : 0, 2500, 0, 1667 (xmin, xmax, ymin, ymax)
#coord. ref. :
#source : memory
#colors RGB : 1, 2, 3
#names : red, green, blue
#min values : 0, 8, 0
#max values : 252, 250, 248
plot(r)
You may want to stick with terra, but if you want to go back to a RasterBrick, you can add
library(raster)
b <- brick(r)

Related

how to get cell dimensions from rasterized ```SpatialPolygonsDataFrame```?

I have SpatialPolygonsDataFrame class in R, which I want to rasterize. I rasterize the the polygon using this code below:
> p <- shapefile('MadaGranary')
> p
class : SpatialPolygonsDataFrame
features : 1
extent : 100.1269, 100.5313, 5.793798, 6.446769 (xmin, xmax, ymin, ymax)
crs : +proj=longlat +datum=WGS84 +no_defs
variables : 1
names : id
value : 1
> crs(p) <- NULL
> # Define RasterLayer object
> r.raster <- raster(extent(p), res = 100)
> #rasterize
> p.r <- rasterize(p, r.raster)
> print(p.r)
class : RasterLayer
dimensions : 1, 1, 1 (nrow, ncol, ncell)
resolution : 100, 100 (x, y)
extent : 100.1269, 200.1269, -93.55323, 6.446769 (xmin, xmax, ymin, ymax)
crs : +proj=longlat +datum=WGS84 +no_defs
source : memory
names : layer
values : NA, NA (min, max)
attributes :
ID id
1 1
Unfortunately, this chunk of code has assigned cell dimensions to dimensions : 1, 1, 1 (nrow, ncol, ncell), and its very important for me to get the actual values of ncols and nrows.
And when I print p.r, I need to get the values of dimensions : (nrow, ncol, ncell) in the console so that I will be able to save all attributes in order to use it another analysis later.
attention:The resolutionoutput that I need to get should be real values representing ncols and nrow in the new raster, but not just dimensions : 1, 1, 1 (nrow, ncol, ncell) as shown in my code.
Can any one help please??
If you want to set nrow and ncol then you do so (and not set the resolution, which expresses the size of each cell). Here is an example:
library(raster)
#Loading required package: sp
e <- extent(0,1,0,1)
r <- raster(e, nrow=100, ncol=100)
r
#class : RasterLayer
#dimensions : 100, 100, 10000 (nrow, ncol, ncell)
#resolution : 0.01, 0.01 (x, y)
#extent : 0, 1, 0, 1 (xmin, xmax, ymin, ymax)
#crs : NA

oneHotEncode a rasterlayer in R

I have a categorical raster layer that I need to one-hot encode, as I'm using neural networks to run a species distribution model (for a class) and it only works on continuous predictors. I've already run the model with the one-hot encoded data itself, but in order to predict onto a map, the raster itself needs to be one-Hot encoded in the same way.
In the RStoolbox package, oneHotEncode() should do what I need it to do, but I can't get it to work
nn.raster<-oneHotEncode(newraster$NLCD_2016_Land_Cover_oreg, classes=values, background = 0, foreground = 1, na.rm = FALSE)
Error message:
Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) :
cannot use this function. Perhaps add '...' or 'na.rm' to the function arguments?
Has anybody used this function and can help me troubleshoot? I think the problem is coming from the class's argument. My categories are numerical (from the national land cover raster), which is why they show up as "values" in the raster info. Do I need to do something to reclassify them? I think I'm naming them wrong but I'm not sure how.
After giving a quick look at RStoolbox::oneHotEncode, I am under the impression that it does what raster::layerize also does.
library(raster)
r <- raster(nrow=20, ncol=20)
values(r) <- c(rep(NA, 50), rep(1:5, 70))
r
#class : RasterLayer
#dimensions : 20, 20, 400 (nrow, ncol, ncell)
#resolution : 18, 9 (x, y)
#extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
#crs : +proj=longlat +datum=WGS84 +no_defs
#source : memory
#names : layer
#values : 1, 5 (min, max)
b <- layerize(r)
b
#class : RasterBrick
#dimensions : 20, 20, 400, 5 (nrow, ncol, ncell, nlayers)
#resolution : 18, 9 (x, y)
#extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
#crs : +proj=longlat +datum=WGS84 +no_defs
#source : memory
#names : X1, X2, X3, X4, X5
#min values : 0, 0, 0, 0, 0
#max values : 1, 1, 1, 1, 1
Which is equivalent to terra::separate
library(terra)
r <- rast(nrow=5, ncol=5)
values(r) <- rep(c(1:4, NA), each=5)
b <- separate(r)

Extracting depth data from raster using lat and Lon

I am trying to get the maximum depth (max_depth) for a given lat and lot using this gebco (tiff file attached) and it keeps coming up with NA. In the past, this has worked so im not sure what is going wrong. The site is used to also extract temperature and nutrient data from WOCE files and that works. Is there something that I am missing in my code?
library(raster)
bathy <- raster("gebco0.5.tif")
site <- cbind(125, -49)
extract(bathy, site)
# [,1]
# [1,] NA
show(bathy)
#class : RasterLayer
#dimensions : 360, 720, 259200 (nrow, ncol, ncell)
#resolution : 1, 1 (x, y)
#extent : 0, 720, 0, 360 (xmin, xmax, ymin, ymax)
#crs : NA
#source : gebco0.5.tif
#names : gebco0.5
There is no attached file, but your code looks good, and this works
r <- raster("https://i.stack.imgur.com/g8WSo.png")
extent(r) <- c(-180,180,-90,90)
site <- cbind(125, -49)
extract(r, site)
# 0
My guess is that the extent of bathy is not what you expect. Can you show(bathy) to us?
Now that we have show(bathy) we can see that you have an unexpected extent for lon/lat data: 0, 720, 0, 360 (xmin, xmax, ymin, ymax) . Such that you get
r <- raster("https://i.stack.imgur.com/g8WSo.png")
site <- cbind(125, -49)
extract(r, site)
# [,1]
#[1,] NA
From what I can see, it appears that you need to do:
extent(r) <- c(-180, 180, -90, 90)
And then things should work (as I already showed above). And if you know whereabouts "site" is, you can visually check that with
plot(r)
points(site)

Why is my raster stack displaying all of the individual raster images instead of a merged raster image?

I am attempting to plot an image composed of a stack of raster images. Using reproducible data:
library(raster)
b <- brick(system.file("external/rlogo.grd", package = "raster"))
b
#class : RasterBrick
#dimensions : 77, 101, 7777, 3 (nrow, ncol, ncell, nlayers)
#resolution : 1, 1 (x, y)
#extent : 0, 101, 0, 77 (xmin, xmax, ymin, ymax)
#crs : +proj=merc +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
#source : /Library/Frameworks/R.framework/Versions/4.0/Resources/library/raster/external/rlogo.grd
#names : red, green, blue
#min values : 0, 0, 0
#max values : 255, 255, 255
library(rasterVis)
levelplot(b)
This produces a image of the 3 raster layers side by side
What I want to do is plot it so that the image displays the "R" logo only once with the 'red', 'green' and 'blue' layers stacked on top of each other by using their mean values.
Can anyone please help achieve this? Thank you!
To get the mean value of a RasterStack (or RasterBrick)
library(raster)
b <- brick(system.file("external/rlogo.grd", package = "raster"))
bm <- mean(b)
plot(bm)

Error while extracting netcdf files into raster

I have many NCDF files in a folder. I try to extract them into raster brick using raster and ncdf4 packages. If I separately extract each NCDF file it works. However, I try to extract all files using for loop then it gives me error.
R<-list.files("D:/Results/TimeSeries/NETCDF/")
r<-brick(paste0("D:/Results/TimeSeries/NETCDF/",R[[1]]),varname="T_min")
for(i in 2:length(R)){
r1<-brick(paste0("D:/Results/TimeSeries/NETCDF/",R[[i]]),varname="T_min")
r<-brick(r,r1)
}
Error in as.integer(nl) : cannot coerce type 'S4' to vector of type
'integer'
If I look at r and r1 separately they seem to have same extent and both are raster brick type:
> r
class : RasterBrick
dimensions : 81, 81, 6561, 122 (nrow, ncol, ncell, nlayers)
resolution : 1, 1 (x, y)
extent : 0.5, 81.5, 0.5, 81.5 (xmin, xmax, ymin, ymax)
coord. ref. : NA
data source : D:\Results\TimeSeries\NETCDF\timeseries_1km_2026.nc
names : X0026.05.02, X0026.05.03, X0026.05.04, X0026.05.05, X0026.05.06, X0026.05.07, X0026.05.08, X0026.05.09, X0026.05.10, X0026.05.11, X0026.05.12, X0026.05.13, X0026.05.14, X0026.05.15, X0026.05.16, ...
Date : 0026-05-02, 0026-08-31 (min, max)
varname : T_min
> r1
class : RasterBrick
dimensions : 81, 81, 6561, 122 (nrow, ncol, ncell, nlayers)
resolution : 1, 1 (x, y)
extent : 0.5, 81.5, 0.5, 81.5 (xmin, xmax, ymin, ymax)
coord. ref. : NA
data source : D:\Results\TimeSeries\NETCDF\timeseries_1km_2027.nc
names : X0027.05.02, X0027.05.03, X0027.05.04, X0027.05.05, X0027.05.06, X0027.05.07, X0027.05.08, X0027.05.09, X0027.05.10, X0027.05.11, X0027.05.12, X0027.05.13, X0027.05.14, X0027.05.15, X0027.05.16, ...
Date : 0027-05-02, 0027-08-31 (min, max)
varname : T_min
Please help.
There is no need to loop, raster is vectorized, try
p <- "D:/Results/TimeSeries/NETCDF"
R <- list.files(p, pattern = "nc$")
r <- raster::stack(file.path(p, R), varname = "T_min")
If you did need to loop, I'd do it like this:
r <- raster::stack(lapply(file.path(p, R), raster::raster, varname = "T_min"))
Edit: replace raster::raster with raster::stack.
Also note the use of file.path, and the facilities available within list.files. (Pasting text for file paths can be problematic, and is more complicated than using available functions).

Resources