"Error: inherits(obj, "Spatial") is not TRUE" - raster

I would like to create contour lines (50%, 75%, 95%) from following raster object (r1) which can be transferred to ArcGIS. But I always getting error message: "Error: inherits(obj, "Spatial") is not TRUE".
contour1 <- contour(r1, levels=c(.5, .75, .95), add=TRUE)
library(rgdal)
writeOGR(contour1, ".", paste("r1"), driver="ESRI Shapefile")
################
class : RasterLayer
dimensions : 703, 524, 368372 (nrow, ncol, ncell)
resolution : 10000, 10000 (x, y)
extent : -2839438, 2400562, -3450852, 3579148 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=aeqd +ellps=WGS84 +lon_0=89.5525 +lat_0=43.234
data source : in memory
names : layer
values : 1e-07, 2.888137 (min, max)

Try following:
library(sp)
library(maptools)
l = quantile(r1[], c(.05, .5, .95))
sl = ContourLines2SLDF(contourLines(as.image.SpatialGridDataFrame(as(r1, "SpatialGridDataFrame")), levels = l))
library(rgdal)
writeOGR(sl, ".", paste("r1"), driver="ESRI Shapefile")

Related

mapview: transparent na.color when displaying raster files

When I plot aerial photographs in mapview a black rectangle is displayed around the picture, which I believe contains NA values and which I would like to remove. Due to the lack of easily available example data I have uploaded my actual geotif here (password: 1_sillyQuestion).
test_image <- terra::rast("yourpath\\test-image.tif") %>%
satellite::brick()
viewRGB(test_image,
r = 1,
g = 2,
b = 3,
quantiles = NULL)
Using data provided with the plainview package, I am able to remove the grey area surrounding the raster (which I think is analogous to my issue) by setting the na.color argument to "transparent".
Border present:
mapview::viewRGB(plainview::poppendorf, 4, 3, 2)
Border removed:
mapview::viewRGB(plainview::poppendorf, 4, 3, 2, na.color = "transparent")
Unfortunately this doesn't produce any changes, when applied to my problem:
viewRGB(gtiff_small,
r = 1,
g = 2,
b = 3,
quantiles = NULL,
na.color = "transparent")
Any suggestions about how to remove the black rectangle around my aerial image will be much appreciated!
na.color has no effect here because there aren't any NAs in the data. Your image is an RGB image where the black pixels are encoded as rgb(0, 0, 0) - black. The right thing to do is to specify a NA value upon the creation of the image (GDAL has an option to do this IIRC). Below is a solution that replaces all rgb(0, 0, 0) pixels with NA. But be careful, this will also set any real black pixels to NA (that's why it should really be done upon image creation).
library(mapview)
library(leaflet)
library(raster)
#> Loading required package: sp
test_image <- terra::rast("/home/tim/Downloads/test-image.tif") %>%
raster::brick() %>%
subset(c(1, 2, 3))
# set all values with 0 to NA
vals = values(test_image)
idx = which(rowSums(vals) == 0)
vals[idx, ] = cbind(NA, NA, NA)
test_image = setValues(test_image, vals)
viewRGB(test_image,
r = 1,
g = 2,
b = 3,
na.color = "transparent",
quantiles = NULL)
#> Warning in rasterCheckSize(x, maxpixels = maxpixels): maximum number of pixels for Raster* viewing is 5e+05 ;
#> the supplied Raster* has 19132224
#> ... decreasing Raster* resolution to 5e+05 pixels
#> to view full resolution set 'maxpixels = 19132224 '
#> Warning in showSRID(uprojargs, format = "PROJ", multiline = "NO", prefer_proj =
#> prefer_proj): Discarded ellps WGS 84 in Proj4 definition: +proj=merc +a=6378137
#> +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=#null
#> +wktext +no_defs +type=crs
#> Warning in showSRID(uprojargs, format = "PROJ", multiline = "NO", prefer_proj =
#> prefer_proj): Discarded datum World Geodetic System 1984 in Proj4 definition
#> Warning in raster::projectRaster(x, raster::projectExtent(x, crs =
#> sp::CRS(epsg3857)), : input and ouput crs are the same
test_image
#> class : RasterBrick
#> dimensions : 4016, 4764, 19132224, 3 (nrow, ncol, ncell, nlayers)
#> resolution : 0.1, 0.1 (x, y)
#> extent : 1277489, 1277966, 6087025, 6087427 (xmin, xmax, ymin, ymax)
#> crs : +proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=#null +wktext +no_defs
#> source : memory
#> names : test.image_1, test.image_2, test.image_3
#> min values : 0, 1, 0
#> max values : 255, 255, 255
Created on 2022-08-11 by the reprex package (v2.0.1)

How to add european countries borders to a Raster in R?

I have this raster file:
fdiff_north:
class : RasterLayer
dimensions : 5500, 12000, 6.6e+07 (nrow, ncol, ncell)
resolution : 100, 100 (x, y)
extent : 4e+06, 5200000, 2250000, 2800000 (xmin, xmax, ymin, ymax)
crs : +proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs
source : memory
names : layer
values : -1, 1 (min, max)
to get a plot:
cl <- colorRampPalette(c("red","white","blue"))(100)
plot(fdiff_north, col=cl)
I need boundaries to make the plot more usable.
I also tried to change the crs of my raster:
rfdiff_north:
class : RasterLayer
dimensions : 12571, 6151, 77324221 (nrow, ncol, ncell)
resolution : 9e-04, 0.00128 (x, y)
extent : 42.7836, 48.3195, 5.672145, 21.76303 (xmin, xmax, ymin, ymax)
crs : +proj=longlat +datum=WGS84 +no_defs
source : r_tmp_2022-02-07_151752_9872_54603.grd
names : layer
values : -1.466443, 1.366832 (min, max)
I want to add european countries boundaries to my raster, but I can't get it. I've tried with many different functions but I achieved no results. Can you help me to do that ?
The boundaries of European countries you can get from spMaps or any other source (OpenStreetMap data for example)
# devtools::install_github("rte-antares-rpackage/spMaps", ref = "master")
library(spMaps)
eu <- getEuropeCountries(mergeCountry = FALSE)
Trying to create similar (in size and CRS) raster:
library(terra)
#> terra 1.5.17
x <- rast(nrows=5500, ncols = 12000, nlyrs = 1,
xmin = 4e+06, xmax = 5200000, ymin = 2250000, ymax = 2800000,
crs = "+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs",
resolution = 100)
x <- setValues(x,runif(ncell(x)))
x
#> class : SpatRaster
#> dimensions : 5500, 12000, 1 (nrow, ncol, nlyr)
#> resolution : 100, 100 (x, y)
#> extent : 4e+06, 5200000, 2250000, 2800000 (xmin, xmax, ymin, ymax)
#> coord. ref. : +proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs
#> source : memory
#> name : lyr.1
#> min value : 4.889444e-09
#> max value : 1
Now it's time to convert SpatialPolygons to SimpleFeature and transform the coordinates to yours CRS:
library(sf)
eu <- st_as_sf(eu)
plot(x)
plot(st_transform(eu$geometry,
crs = "+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs"),
add = TRUE)
Created on 2022-02-09 by the reprex package (v2.0.1)
You can crop boundaries to your raster bbox with st_crop()
Regards,
Grzegorz

downloading satellite map for a specific region - R

I have run sum analysis on points summarized within a SpatialPointsDataFrame:
> trjct_pts
class : SpatialPointsDataFrame
features : 104559
extent : 696621.4, 696688.7, 167659.2, 167739.8 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 +k_0=1 +x_0=2600000 +y_0=1200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs
variables : 1
names : Intensity_kJ
min values : 161.951
max values : 1192.526
Which I have used to create 2 rasters:
library(raster)
rockfall_count <- raster (xmn = 696583.6, xmx = 696799.6, ymn = 167579.6, ymx = 167789.6, res = 2,
crs = "+proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 +k_0=1 +x_0=2600000 +y_0=1200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs")
rockfall_intensity <- raster (xmn = 696583.6, xmx = 696799.6, ymn = 167579.6, ymx = 167789.6, res = 2,
crs = "+proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 +k_0=1 +x_0=2600000 +y_0=1200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs")
# count unique ID per raster
rockfall_count <- rasterize(trjct_points_coords, rockfall_count, fun = "count", by = ID)
rockfall_count
plot(rockfall_count,col=brewer.pal(9,"YlOrRd"))
# average kinetic energy per raster cell
rockfall_intensity <- rasterize(trjct[, c('x', 'y')], rockfall_intensity, trjct$Etot, fun = mean)
plot(rockfall_intensity, col=brewer.pal(9,"YlOrRd"))
For nice illustration, I would like to download the corresponding satellite image. I have tried the following:
library(rgdal)
longlatcoor<-spTransform(trjct_pts,CRS("+proj=longlat"))
coordinates(longlatcoor)
longlatcoor
library(ggmap)
library(ggplot2)
# Set a range
lat <- c(-13.4003, -13.39943)
lon <- c(35.419, 35.41961)
# Get a map
map <- get_map(location = c(lon = mean(lon), lat = mean(lat)), zoom = 14,
maptype = "satellite", source = "google")
ggmap(map)
#limit lon and lat.
tschamut <- ggmap(map)+
scale_x_continuous(limits = c(-13.4003, -13.39943), expand = c(0, 0)) +
scale_y_continuous(limits = c(35.419, 35.41961), expand = c(0, 0))
tschamut
However, R crashes everytime i try to run this code, so i suspect something is seriously wrong with it. I derived the number used in the code from the bounding box:
> longlatcoor
class : SpatialPointsDataFrame
features : 104559
extent : -13.4003, -13.39943, 35.419, 35.41961 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +ellps=WGS84
variables : 1
names : Intensity_kJ
min values : 161.951
max values : 1192.526
How can I import the aerial photograph into R ?

How to plot spatial points (vector) on a raster file (landsat img) in R

I want to plot spatial points (sp) on a landsat compository, plotting landsat works and plotting the sp as well, but it does not work together. I am quite sure that I somehow don't get the overwriting of the projection/coordinate system, but don't know what I am doing wrong. Googleing didn't help, so I ask you.
Here is the code:
coords_glaciers <- data.frame(x = prec_year$latitude, y = prec_year$longitude)
head(coords_glaciers)
x y
1 30.69800 95.10474
2 30.69628 95.09544
3 30.69173 95.04394
4 30.68793 95.08615
5 30.68799 95.20155
6 30.68472 95.21425
pts_glaciers <- SpatialPoints(coords = coords_glaciers)
pts_glaciers
class : SpatialPoints
features : 865
extent : 29.50121, 30.82512, 94.24684, 96.19304 (xmin, xmax, ymin, ymax)
coord. ref. : NA
proj <- projection(landsat)
proj
[1] "+proj=utm +zone=46 +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs"
pts_glaciers <- SpatialPoints(coords = coords_glaciers, proj4string = CRS(proj))
pts_glaciers
class : SpatialPoints
features : 865
extent : 29.50121, 30.82512, 94.24684, 96.19304 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=46 +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs
plotRGB(landsat, r=5, g=4,b=3)
plot(pts_glaciers, add =TRUE)
I think the solution is:
coords_glaciers <- data.frame(x = prec_year$longitude, y = prec_year$latitude)
coordinates(coords_glaciers) <- c("x","y")
proj4string(coords_glaciers) <- CRS("+proj=longlat +datum=WGS84")
pts_glaciers <- spTransform(coords_glaciers, CRS("+proj=utm +zone=46 +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs"))

Projecting a SpatialLines object from lat/lon to utm

I created a great-circle trajectory of lat/lon using the geosphere package:
flightTraj = greatCircle( c( originAptLon, originAptLat ), c( destinAptLon, destinAptLat ), n = nPts, sp = TRUE )
Its properties are:
class : SpatialLines
features : 1
extent : -180, 180, -52.74719, 52.74719 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +ellps=WGS84
I want to project to a UTM zone 14 cartography with WGS84 ellipsoid. I tried:
projectedTrajectories <- CRS("+proj=utm +zone=14 +datum=WGS84 +units=km +no_defs") %>%
spTransform( flightTraj, . )
But, the console displayed:
non finite transformation detected:
V1 lat
Error in .spTransform_Line(input[[i]], to_args = to_args, from_args = from_args, :
failure in Lines 1 Line 1 points
In addition: Warning message:
In .spTransform_Line(input[[i]], to_args = to_args, from_args = from_args, :
6 projected point(s) not finite
Any help, please.
"All's well that ends well..."
distOrigDest = distGeo( c( originAptLon, originAptLat ), c( destinAptLon, destinAptLat ), a = earthRadius, f = earthFlattening ) / km2m
nPts = 20 * floor( distOrigDest / cellCentroidDist )
flightTraj = gcIntermediate( c( originAptLon, originAptLat ), c( destinAptLon, destinAptLat ), n = nPts, sp = TRUE )
flightTraj = spTransform( flightTraj, "+proj=utm +zone=14 +datum=WGS84 +units=km" )
plot( flightTraj, col= "blue", add = TRUE, lwd = 2 )

Resources