R: Clip a shapefile boundary out of a generated image - r

I generated an image of ordinary kriged predictions. I have a shapefile of a boundary line and I'd like to crop the ordinary kriged predictions in the shape of that shapefile.
This is the code I use to generate the image:
image(OK.pred,loc=grid,axes=F,useRaster=TRUE). I just want to clip an object out of the image -- when I plot them, they overlay perfectly.
It's almost identical to the issue here, https://gis.stackexchange.com/questions/167170/is-it-possible-to-clip-a-shapefile-to-an-image-in-r, but I'm relatively new to R and got totally lost with the netcdf file part.
I found a bunch of code on how to clip rasters, but I just can't figure out how to even save an image into a variable let alone transform it to a raster in order to clip it. Any help would be much appreciated!
OK.pred<-krige.conv(gambling.geo,coords = gambling.geo$coords, data=gambling.geo$data, locations=grid,krige=krige.control(obj.model=gambling.vario.wls))
ordinarykrig = image(OK.pred,loc=grid,axes=F,useRaster=TRUE)
Macau <- readOGR("MAC_adm0.shp")
x <- crop(?...)

Taken from http://leg.ufpr.br/geoR/tutorials/kc2sp.R:
You need to convert the kriging output to a Spatial object before you can pass it to mask(). The following should do it:
OK.pred<-krige.conv(gambling.geo,coords = gambling.geo$coords, data=gambling.geo$data, locations=grid,krige=krige.control(obj.model=gambling.vario.wls))
GT.s <- points2grid(SpatialPoints(as.matrix(grid)))
reorder <- as.vector(matrix(1:nrow(grid), nc=slot(GT.s, "cells.dim")[2])[,slot(GT.s, "cells.dim")[2]:1])
SGDF.s <- SpatialGridDataFrame(grid=GT.s, data=as.data.frame(OK.pred[1:2])[reorder,])
r<-raster(SGDF.s)
x<-mask(r, Macau)

Related

Spatial operations with curvilinear data in program stars for R

I'm new to the package stars for R and am trying to do basic spatial operations with curvilinear data. I am using netCDF climate data. I am able to read the netcdf into r along with a shapefile I would like to use to specify the area in which I want to conduct analyses. I have tried to crop the file directly using st_crop() but receive the following error:
Warning message:
In st_crop.stars(test, wrst) : crop only crops regular grids
I then tried to warp the stars object using code like this:
warp <- test %>% st_set_crs(3338) %>% st_warp(st_as_stars(st_bbox(), dx = 2))
but I get this error:
Error in colrow_from_xy(pts, x, NA_outside = TRUE) :
colrow_from_xy not supported for curvilinear objects
Do I need to 'flatten' my curvilinear grid in order to conduct analyses in a given region? If so, how do I do that? Or, conversely, if I am able to conduct operations like st_crop() or the equivalent of raster operations calc() or stackApply() using a curvilinear grid, can someone point me in the right direction? Thanks so much.
Well I figured it out and it was quite simple. I was able to subset the stars object using the shapefile with this simple code: test[wrst]. No warping or resampling necessary.

R grid arrange tiff microscopy RGB

I have a RGB tiff files (from cellProfiler) which I want to import to R, label and arrange - as part of a high throughput analysis. The closest I get is using:
library(tiff)
library(raster)
imageTiff <- tiff::readTIFF(imagePath[i])
rasterTiff <- raster::as.raster(imageTiff)
raster::plot(rasterTiff)
raster::plot plots the image nicely but I can't catch the output and use it with gridExtra or add labels.
In addition I tried rasterVis with levelPlot and multiple other ways importing the tiff and then converting them to grob or ggplots.
However, I can't get anything to work and would like to ask if R is even suited at all for that task?
Thank you very much for your help!
Okay, I think that is the most straight forward way and possible also the most obvious one.
I import JPEG or TIFF files with jpeg::readJPEG or tiff::readTIFF respectively. Both transform the images to a raster format which is compatible with rasterGrid() and following grid.arrange etc.
library(jpeg)
library(tiff)
library(grid)
imageJPEG <- grid::rasterGrob(jpeg::readJPEG("test.jpeg"))
imageTIFF <- grid::rasterGrob(tiff::readTIFF("test.tiff"))
grid.arrange(imageJPEG , imageJPEG , imageJPEG)
grid.arrange(imageTIFF , imageTIFF, imageTIFF)
For my purpose that is perfect since tasterGrob does not alter the raster matrix values. Labeling might be a bit tricky but overall it is a grid/grob problem from here on.

writeRaster function in R is automatically setting (unwanted) maximum value, can I set the max value to null?

I am running into a problem with the "writeRaster" function in the raster package in R. I am importing a raster (TIF) that I made in ArcGIS (a distance to feature raster).
My goal was to resample the distance raster to the correct resolution and extent, then "mask" it with the appropriate raster to crop it to the shape I require. When I check the results of the mask with the basic plot function, everything looks great and I can see that each pixel in the new masked raster has a distance value.
However, when I write this raster to a file using the writeRaster function, the resulting raster looks like "swiss cheese" and has missing values for any distance over 35km. After much reading, I cannot find any documentation to suggest that there is a way to modify the maximum value set by writeRaster---or that it should even be setting a max value. I have included my code and the basic plots below. A big thank you to anyone who attempts to help me with this!
#Read in distance to fresh water raster
distFW <- raster("D:/Academia/Arc Data/Grackle/NicaCR_90mlayers/dist_FW.tif")
[plot(distFW)][1]
#Resample this layer to the desired resolution and template
NiCR_DistFW<-as.integer(resample(distFW,NiCRrast.tmpl,method="ngb"))
#essentially the same as the first plot
[plot(NiCR_DistFW)][2]
#Mask the resampled raster to the desired shape
NiCR.DistFW.mask.utm <- mask(NiCR_DistFW,NiCR_Mask) #with CA countries cut out.
[plot(NiCR.DistFW.mask.utm)][3]
#write raster to file (this is where things get weird)
writeRaster(x=NiCR.DistFW.mask.utm, filename='DistFWmask2.tif', format='GTiff', datatype='INT2S') #a way to ensure INT2S
#read the newly written raster file in to R so we can review it
dFW <-raster("DistFWMask2.tif")
[plot(dFW)_writeRaster_result][4]
[1]: https://i.stack.imgur.com/v9RkK.jpg
[2]: https://i.stack.imgur.com/v2DG3.jpg
[3]: https://i.stack.imgur.com/cCwJe.jpg
[4]: https://i.stack.imgur.com/MjWj7.jpg
As you can see from plot 4, an undesirable max value has been set. I was the raster I write to file to look like the one in plot 3, not plot 4.
Thanks in advance for any advice.
Well friends, after taking an hour to detail my question I managed to figure out the answer myself. It had to do with setting the datatype.
INT2S has a maximum value of 32,767
by switching it to INT4S, I capture the full range of values in my raster.
Problem solved!

Creating a list/data.frame of images to graph with ggplot2

I have dataset (vg) with observations uniquely identified with an image's filename. I have a folder with these images, named the same way (e.g., 001.jpg ... 501.jpg). I would like to graph my data using the actual images as the "geom" in ggplot2.
I was able to figure out how to plot an image thanks to this answer. However, I am left with two issues: (1) plotting many images using a loop and (2) plotting the images on the graph based on the data in my dataset. I am presently concerned with reading the images into some sort of list or data frame. Here is what I have tried:
imgdir = "c:/mydir"
setwd(imgdir)
l = length(dir())
img <- graph.data.frame()
for (i in l) {
load = readJPEG(dir()[i], TRUE) %>%
rasterGrob(interpolate=TRUE)
img[1:length(load)] = load
img[1:length(load)] = dir()[i]
}
It's cute but it obviously does not work. Frankly, I do not understand how the object this creates functions. Ideally, I would have a dataframe with the filename and raster (is that what it is?), or even just load the image into my dataset. Then I would have to figure out how to give ggplot 700+ images to plot!
I am rather new to R and recognize this may not be possible the way I envision it. Thank you for your patience.

Defining polygon coordinates with a predefined image and plotting in R

Here is what I need: I have an image and want to plot on specific rectangle-shaped parts of it (e.g., imagine having a picture of a chessboard and wanting to fill every square with a different color). I would like to be able to easily specify the coordinates for these parts and take these coordinates into R for plotting.
I don't have any experience with making such plots. I've thought of simply inserting an image into a plot with rasterImage (), then plotting with polygon (), but the task of setting up the coordinates for the polygon function seemed too time consuming - hence the question above.
If you have any better ideas than using a set of coordinates for the polygon function, please share. Any leads or packages suggestions would also be helpful.
thank you. Marko.

Resources