Importing projected GeoTIFF and transforming to latitude and longitude coordinates in R - r

While I am not new to R, I am new to visualizing spatial data in it rather than ArcGIS.
I am attempting to import a GeoTIFF image from a public-access GIS website that is already projected in Mercator (image can be found here). Using the raster package in R, I can successfully import the GeoTIFF into R and plot it (see below).
> library(raster)
> mb <- raster("/Maps/mb_srelief10m/mb_srelief10m.tif")
> mb
class : RasterLayer
dimensions : 8060, 7220, 58193200 (nrow, ncol, ncell)
resolution : 10, 10 (x, y)
extent : -48598.54, 23601.46, 3850014, 3930614 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=merc +lon_0=-70.31666666666668 +lat_ts=41.65 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs +ellps=GRS80 +towgs84=0,0,0
data source : C:\Users\Connor\Documents\ArcGIS\Maps\mb_srelief10m\mb_srelief10m.tif
names : mb_srelief10m
values : 0, 255 (min, max)
attributes :
ID COUNT BinValues Value
from: 0 1460797 0 0
to : 51 14795988 255 255
As you can see, the x- and y-axis labels represent the NAD83 values from the raster file (red boxes in image). Yet, when I attempt to use the crop function to use only a portion of this raster file, I cannot select the appropriate area because my user-defined extent object is in latitude and longitude coordinates. I understand I can use the drawExtent function to manually select the area but I want to automate this process.
My question is:
How do I transform the raster file so that my axes are in latitude and longitude and I can crop the file using latitude and longitude coordinates?
If this post would be more appropriate elsewhere, please let me know and I will remove the file. Thank you!

Related

Convert HDF4 to raster; with longitude/latitude grids are available in another HDF file

I am trying to convent HDF4 files (representing daily Sea Ice Concentration) to raster object in R. However, the HDF files themselves do not contain the longitude/latitude grids or projection information, and such information should be extracted from another hdf file.
The website on data format says:
Data Format
Sea ice concentration maps with two different color scales are available as PNG image. The NIC color scale uses the same colors as the National Ice Center, the "visual" color scale uses white and shades of grey.
There is one file per day per region per color scale.
Sea ice concentration data are available as HDF4 files: There is one file per day per region. Each file contains one two-dimensional array of the sea ice concentration in a polar stereographic grid.
The longitude and latitude coordinates of each pixel in a the HDF4 file are saved in extra files, one file per region for each available resolution.
They are found here: https://seaice.uni-bremen.de/data/grid_coordinates/, sorted by hemisphere and grid resolution (see also the README file https://seaice.uni-bremen.de/data/grid_coordinates/README).
GEOTIFF files use the NIC color scale and were tested to work with QGIS. Ice concentrations are scaled between 0 and 100, land and missing values are set to 120 (older files: SIC: 0-200, land/NaN: 255).
I tried to use R to load this map using this code:
> require(raster)
> CurrTemp <- tempfile()
> download.file(url = "https://seaice.uni-bremen.de/data/amsre/asi_daygrid_swath/s6250/2003/feb/Antarctic/asi-s6250-20030214-v5.hdf", destfile = CurrTemp, mode = "wb", quiet = T)
> Map1 <- readAll(raster(CurrTemp))
> plot(Map1)
> Map1
class : RasterLayer
dimensions : 1328, 1264, 1678592 (nrow, ncol, ncell)
resolution : 1, 1 (x, y)
extent : 0, 1264, 0, 1328 (xmin, xmax, ymin, ymax)
coord. ref. : NA
data source : in memory
names : file43fc5b4e68de
values : 0, 100 (min, max)
The map is loaded into R as raster object but with wrong coordinates and with no projection. According to this page, coordinates should be extracted from another hdf file.
Could you please let me know how to convert these hdf files into raster obejcts with correct coordinates and projection.
Thanks.
I used one of the geotiff files that they also make available to find the extent and crs.
library(raster)
raster('asi-AMSR2-s6250-20180922-v5.tif')
#class : RasterLayer
#dimensions : 1328, 1264, 1678592 (nrow, ncol, ncell)
#resolution : 6250, 6250 (x, y)
#extent : -3950000, 3950000, -3950000, 4350000 (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=stere +lat_0=-90 +lat_ts=-70 +lon_0=0 +k=1 +x_0=0 +y_0=0 +a=6378273 +b=6356889.449 +units=m +no_defs
#data source : asi-AMSR2-s6250-20180922-v5.tif
#names : asi.AMSR2.s6250.20180922.v5
#values : 0, 255 (min, max)
Now I know I can do
library(raster)
CurrTemp <- tempfile()
download.file(url = "https://seaice.uni-bremen.de/data/amsre/asi_daygrid_swath/s6250/2003/feb/Antarctic/asi-s6250-20030214-v5.hdf", destfile = CurrTemp, mode = "wb", quiet = T)
r <- raster(CurrTemp)
extent(r) <- c(-3950000, 3950000, -3950000, 4350000)
crs(r) <- "+proj=stere +lat_0=-90 +lat_ts=-70 +lon_0=0 +k=1 +x_0=0 +y_0=0 +a=6378273 +b=6356889.449 +units=m +no_defs "
# writeRaster(r, 'my_asi-s6250-20030214-v5.tif')
The "other hdf" file has longitude / latitude values for the cells, but that is not what you are after as the data do not have a lon/lat coordinate reference system.

R: How is it possible to export from R an image from a raster layer while maintaining image resolution?

I have been attempting to export a geographic raster layer which is projected in terms of the Lambert Conformal Conic projection (with a resolution of 1000 m by 1000 m) as an image file (e.g. as an *.eps) after having plotted it with some overlaid points (which is straightforward enough), but upon opening the image after export, it is clear that it has a resolution of a lesser quality than the aforementioned.
I've been using the 24 Bioclimate layers downloadable from: https://sites.ualberta.ca/~ahamann/data/climatewna.html. Here is an example of one of those layers (which was saved as a *.tif), and its resolution:
Below is the section of the script I have been running which is of relevance:
> projection <- raster("prediction.grd")
> projection
class : RasterLayer
dimensions : 3132, 2359, 7388388 (nrow, ncol, ncell)
resolution : 1000, 1000 (x, y)
extent : -3594000, -1235000, 4703000, 7835000 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=lcc +lat_1=49 +lat_2=77 +lat_0=0 +lon_0=-95 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0
data source : C:\Users\User\Documents\Project\prediction.grd
names : layer
values : 7.006775e-12, 0.001495079 (min, max)
> plot(projection, col = colorPalette(14, "jc"), colNA = 'black', axes = FALSE);
> points(train_locality_points, col='white', pch=15, cex=0.2)
Following the running of this code, I've gone about exporting the plot generated via the 'export' dropdown menu of R Studio to save it as an image with an extension that can be viewed outside of R instead of as a file with its original extension or something similar. I can open the image which is saved, but it evidently is not of the same quality as what the resolution of the layer is stated as above.
The image below is one I've saved in the way just described. To illustrate the trouble I've been having, Vancouver Island ( i.e. the large one with many white dots clustered at its southern end) is about 500 kilometres in length, which should correspond to about 500 pixels in the image if the resolution were 1 km by 1 km as the raster layer is. In this image the length of the island is represented by about a fifth of that number (...yes, I counted).
Any help as to how this issue could be remedied I would greatly appreciate. Thank-you for taking the time to read through and consider this question.
To get an image with same resolution as RasterLayer r, you can do
png('file.png', height=nrow(r), width=ncol(r))
plot(r, maxpixels=ncell(r))
dev.off()

Sentinel-2 R gdal raster

I would like to make a piece of code I have more efficient.
Right now I download Sentinel-2 data in jp2 format via the open acceshub. The jp2 files that I download have, for some reason, a wrong extent. Right now I correct this in the following way (in which file is the filename of the jp2):
r = raster(file)
extent(r) = new_extent
writeRaster(r, file)
This method, however, writes the entire raster (which takes ages) whereas I only changed a minor detail.
Is there a neat way using gdal or the raster package to do this more efficiently?
If I print the raster I see:
class : RasterLayer
dimensions : 1830, 1830, 3348900 (nrow, ncol, ncell)
resolution : 60, 60 (x, y)
extent : 499980, 609780, 6690240, 6800040 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=55 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0
data source : /home/daniel/R/farmhack/x.jp2
names : x
values : 0, 65535 (min, max)
I do not know what this extent means.

How to adjust two maps with different extent in R

Two maps with different extents
I am using R to process two maps (raster package). I have two maps with both WGS84 coordinates see figure.
But one layer is from -180 to 180 in longitude (the map on surface) another one is from 0 to 360 (the map on the bottom).
I need to adjust the bottom layer to -180 to 180 so that they can match. How can I do that?
I think I need to find all grid greater than 180 and then minus 360. But I cannot find the longitude vector and cannot modify it from the Raster data.
Description of the map is:
class : RasterLayer
dimensions : 94, 192, 18048 (nrow, ncol, ncell)
resolution : 1.865234, 1.883872 (x, y)
extent : 0, 358.125, -88.542, 88.542 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
data source : in memory
names : TMAX_2015_01_01
values : 220.9, 324.3 (min, max)
spTransform(ws_soil,CRS=CRS("+proj=longlat +ellps=WGS84 +pm=+360 +datum=WGS84 +no_defs"))
You need to play with "+pm=+360" or "+pm=-360"
Others told me a good function (raster::rotate)
Simply use CLIM_NEW<-rotate (CLIM_old). That will work.

Missing coordinates in raster reprojection from cylindrical equal area to lat/long using Raster function in R

I have a raster that I have reprojected from Cylindrical Equal-Area (Lambert) Central Meridian: -160. Datum: WGS 1984 (+proj=cea +lon_0=Central Meridian +lat_ts=Standard Parallel +x_0=False Easting +y_0=False Northing +ellps=WGS84) to latitude and longitude.
The original raster looks like this:
library(rasterVis)
levelplot(r)
Original raster without missing points
r
#class : RasterLayer
#dimensions : 64, 200, 12800 (nrow, ncol, ncell)
#resolution : 2e+05, 2e+05 (x, y)
#extent : -20037507, 19962493, -6363885, 6436115 (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=cea +lon_0=-160 +lat_ts=Standard Parallel +x_0=False Easting +y_0=False Northing +ellps=WGS84
#data source : N:\My documents\Data\Exposure\Reefs at risk\Global_Threats\Acidification\arag_380\w001001.adf
#names : w001001
#values : 1.025163, 4.11939 (min, max)
I have been able to use the projectRaster function from the Raster package by cutting the extent of the y-axis of the raster by 0.95 to the North and South. I was having a few problems reprojecting the raster without cutting the extent (see here: https://gis.stackexchange.com/questions/220589/error-using-projectraster-in-r-error-in-if-maxy-miny-missing-value-whe/220741#220741).
#Cut y-axis values because projectRaster failed using full extent
extent(r) <- c(xmin= -20037507, xmax= 19962493, ymin= 0.95*(-6363885), ymax= 0.95*(6436115))
# Define the new Proj.4 spatial reference
sr <- "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"
# Project Raster
projected_r <- projectRaster(r, crs = sr, method = 'bilinear')
The problem I am having is that there are missing data in the new, reprojected raster.
levelplot(projected_r)
reprojected raster with missing points
The missing coordinates are not located in the 5% North and Souththat I cut from the extent so I am not sure why these data are missing? Any help would be appreciated!

Resources