Read Single Band From Raster in Matlab

Piece of work With Multi-Band Rasters

Overview

Teaching: twoscore min
Exercises: 20 min

Questions

  • How tin can I visualize private and multiple bands in a raster object?

Objectives

  • Identify a single vs. a multi-ring raster file.

  • Import multi-band rasters into R using the raster bundle.

  • Plot multi-band colour image rasters in R using the ggplot package.

Things You'll Demand To Complete This Episode

See the lesson homepage for detailed information almost the software, data, and other prerequisites you volition need to work through the examples in this episode.

We introduced multi-band raster data in an earlier lesson. This episode explores how to import and plot a multi-ring raster in R.

Getting Started with Multi-Ring Data in R

In this episode, the multi-band information that we are working with is imagery collected using the NEON Airborne Observation Platform high resolution camera over the NEON Harvard Forest field site. Each RGB prototype is a 3-band raster. The same steps would apply to working with a multi-spectral prototype with iv or more bands - similar Landsat imagery.

If we read a RasterStack object into R using the raster() function, information technology only reads in the first band.

                          RGB_band1_HARV                                          <-                                          raster              (              "data/NEON-DS-Airborne-Remote-Sensing/HARV/RGB_Imagery/HARV_RGB_Ortho.tif"              )                                                  

We need to convert this data to a data frame in social club to plot it with ggplot.

                          RGB_band1_HARV_df                                          <-                                          as.data.frame              (              RGB_band1_HARV              ,                                          xy                                          =                                          True              )                                                  
                          ggplot              ()                                          +                                          geom_raster              (              data                                          =                                          RGB_band1_HARV_df              ,                                          aes              (              x                                          =                                          ten              ,                                          y                                          =                                          y              ,                                          blastoff                                          =                                          HARV_RGB_Ortho              ))                                          +                                          coord_quickmap              ()                                                  

plot of chunk harv-rgb-band1

Claiming

View the attributes of this ring. What are its dimensions, CRS, resolution, min and max values, and ring number?

Solution

                grade      : RasterLayer  band       : 1  (of  3  bands) dimensions : 2317, 3073, 7120141  (nrow, ncol, ncell) resolution : 0.25, 0.25  (10, y) extent     : 731998.5, 732766.eight, 4712956, 4713536  (xmin, xmax, ymin, ymax) crs        : +proj=utm +zone=18 +datum=WGS84 +units=k +no_defs  source     : HARV_RGB_Ortho.tif  names      : HARV_RGB_Ortho  values     : 0, 255  (min, max)                              

Notice that when we await at the attributes of this band, nosotros see: band: 1 (of 3 bands)

This is R telling us that this item raster object has more bands (3) associated with it.

Data Tip

The number of bands associated with a raster object can also be determined using the nbands() function: syntax is nbands(RGB_band1_HARV).

Paradigm Raster Data Values

Equally we saw in the previous exercise, this raster contains values between 0 and 255. These values represent degrees of brightness associated with the image band. In the case of a RGB image (red, greenish and blue), band 1 is the ruby band. When we plot the red ring, larger numbers (towards 255) stand for pixels with more red in them (a potent carmine reflection). Smaller numbers (towards 0) represent pixels with less red in them (less cherry-red was reflected). To plot an RGB image, we mix red + green + blue values into one single color to create a full color image - like to the color image a digital camera creates.

Import A Specific Band

We can use the raster() function to import specific bands in our raster object by specifying which band nosotros want with ring = Northward (North represents the band number we want to piece of work with). To import the light-green band, we would use ring = 2.

                          RGB_band2_HARV                                          <-                                          raster              (              "information/NEON-DS-Airborne-Remote-Sensing/HARV/RGB_Imagery/HARV_RGB_Ortho.tif"              ,                                          band                                          =                                          2              )                                                  

Nosotros can convert this data to a data frame and plot the same style nosotros plotted the red band:

                          RGB_band2_HARV_df                                          <-                                          every bit.data.frame              (              RGB_band2_HARV              ,                                          xy                                          =                                          Truthful              )                                                  
                          ggplot              ()                                          +                                          geom_raster              (              data                                          =                                          RGB_band2_HARV_df              ,                                          aes              (              ten                                          =                                          x              ,                                          y                                          =                                          y              ,                                          alpha                                          =                                          HARV_RGB_Ortho              ))                                          +                                          coord_equal              ()                                                  

plot of chunk rgb-harv-band2

Challenge: Making Sense of Single Band Images

Compare the plots of ring 1 (red) and ring 2 (green). Is the forested area darker or lighter in band 2 (the light-green band) compared to ring 1 (the cherry-red band)?

Solution

We'd expect a brighter value for the forest in ring two (green) than in band 1 (red) because the leaves on trees of most oftentimes appear "greenish" - good for you leaves reverberate MORE green light than red low-cal.

Raster Stacks in R

Next, we will work with all three image bands (red, green and blue) equally an R RasterStack object. Nosotros will then plot a 3-band composite, or full colour, image.

To bring in all bands of a multi-band raster, nosotros use thestack() office.

                          RGB_stack_HARV                                          <-                                          stack              (              "data/NEON-DS-Airborne-Remote-Sensing/HARV/RGB_Imagery/HARV_RGB_Ortho.tif"              )                                                  

Let's preview the attributes of our stack object:

            form      : RasterStack  dimensions : 2317, 3073, 7120141, 3  (nrow, ncol, ncell, nlayers) resolution : 0.25, 0.25  (x, y) extent     : 731998.five, 732766.8, 4712956, 4713536  (xmin, xmax, ymin, ymax) crs        : +proj=utm +zone=18 +datum=WGS84 +units=thousand +no_defs  names      : HARV_RGB_Ortho.1, HARV_RGB_Ortho.2, HARV_RGB_Ortho.3  min values :                0,                0,                0  max values :              255,              255,              255                      

We tin can view the attributes of each ring in the stack in a single output:

            [[1]] class      : RasterLayer  band       : 1  (of  three  bands) dimensions : 2317, 3073, 7120141  (nrow, ncol, ncell) resolution : 0.25, 0.25  (10, y) extent     : 731998.5, 732766.8, 4712956, 4713536  (xmin, xmax, ymin, ymax) crs        : +proj=utm +zone=18 +datum=WGS84 +units=1000 +no_defs  source     : HARV_RGB_Ortho.tif  names      : HARV_RGB_Ortho.1  values     : 0, 255  (min, max)   [[two]] class      : RasterLayer  band       : ii  (of  3  bands) dimensions : 2317, 3073, 7120141  (nrow, ncol, ncell) resolution : 0.25, 0.25  (x, y) extent     : 731998.5, 732766.viii, 4712956, 4713536  (xmin, xmax, ymin, ymax) crs        : +proj=utm +zone=xviii +datum=WGS84 +units=k +no_defs  source     : HARV_RGB_Ortho.tif  names      : HARV_RGB_Ortho.2  values     : 0, 255  (min, max)   [[three]] form      : RasterLayer  band       : iii  (of  iii  bands) dimensions : 2317, 3073, 7120141  (nrow, ncol, ncell) resolution : 0.25, 0.25  (x, y) extent     : 731998.five, 732766.viii, 4712956, 4713536  (xmin, xmax, ymin, ymax) crs        : +proj=utm +zone=18 +datum=WGS84 +units=m +no_defs  source     : HARV_RGB_Ortho.tif  names      : HARV_RGB_Ortho.3  values     : 0, 255  (min, max)                      

If nosotros take hundreds of bands, nosotros can specify which band nosotros'd like to view attributes for using an index value:

            course      : RasterLayer  band       : 2  (of  iii  bands) dimensions : 2317, 3073, 7120141  (nrow, ncol, ncell) resolution : 0.25, 0.25  (x, y) extent     : 731998.5, 732766.eight, 4712956, 4713536  (xmin, xmax, ymin, ymax) crs        : +proj=utm +zone=xviii +datum=WGS84 +units=chiliad +no_defs  source     : HARV_RGB_Ortho.tif  names      : HARV_RGB_Ortho.2  values     : 0, 255  (min, max)                      

We tin can also use the ggplot functions to plot the data in any layer of our RasterStack object. Recall, we need to convert to a data frame offset.

                          RGB_stack_HARV_df                                          <-                                          as.data.frame              (              RGB_stack_HARV              ,                                          xy                                          =                                          True              )                                                  

Each band in our RasterStack gets its own cavalcade in the data frame. Thus we have:

            'data.frame':	7120141 obs. of  5 variables:  $ ten               : num  731999 731999 731999 731999 732000 ...  $ y               : num  4713535 4713535 4713535 4713535 4713535 ...  $ HARV_RGB_Ortho.ane: num  0 2 6 0 sixteen 0 0 6 one 5 ...  $ HARV_RGB_Ortho.2: num  1 0 nine 0 5 0 4 ii i 0 ...  $ HARV_RGB_Ortho.3: num  0 10 1 0 17 0 four 0 0 7 ...                      

Allow's create a histogram of the first band:

                          ggplot              ()                                          +                                          geom_histogram              (              data                                          =                                          RGB_stack_HARV_df              ,                                          aes              (              HARV_RGB_Ortho.1              ))                                                  
            `stat_bin()` using `bins = thirty`. Choice meliorate value with `binwidth`.                      

plot of chunk rgb-harv-hist-band1

And a raster plot of the second band:

                          ggplot              ()                                          +                                          geom_raster              (              data                                          =                                          RGB_stack_HARV_df              ,                                          aes              (              x                                          =                                          x              ,                                          y                                          =                                          y              ,                                          alpha                                          =                                          HARV_RGB_Ortho.ii              ))                                          +                                          coord_quickmap              ()                                                  

plot of chunk rgb-harv-plot-band2

Nosotros tin can admission whatsoever individual band in the same mode.

Create A Three Band Paradigm

To render a concluding iii band, colored paradigm in R, we use the plotRGB() function.

This part allows u.s. to:

  1. Identify what bands we want to render in the red, dark-green and blueish regions. The plotRGB() role defaults to a 1=red, two=dark-green, and three=blue band order. Notwithstanding, you can ascertain what bands you'd like to plot manually. Manual definition of bands is useful if you accept, for example a nigh-infrared band and want to create a color infrared image.
  2. Adjust the stretch of the paradigm to increase or decrease dissimilarity.

Let'south plot our 3-band image. Note that nosotros can apply the plotRGB() part directly with our RasterStack object (we don't need a dataframe every bit this role isn't part of the ggplot2 bundle).

                          plotRGB              (              RGB_stack_HARV              ,                                          r                                          =                                          1              ,                                          one thousand                                          =                                          ii              ,                                          b                                          =                                          iii              )                                                  

plot of chunk plot-rgb-image

The image above looks pretty good. We can explore whether applying a stretch to the image might ameliorate clarity and contrast using stretch="lin" or stretch="hist".

Image Stretch

When the range of pixel brightness values is closer to 0, a darker image is rendered by default. We tin can stretch the values to extend to the full 0-255 range of potential values to increase the visual contrast of the prototype.

Image Stretch light

When the range of pixel brightness values is closer to 255, a lighter epitome is rendered past default. We can stretch the values to extend to the full 0-255 range of potential values to increase the visual contrast of the image.

                          plotRGB              (              RGB_stack_HARV              ,                                          r                                          =                                          i              ,                                          g                                          =                                          two              ,                                          b                                          =                                          3              ,                                          scale                                          =                                          800              ,                                          stretch                                          =                                          "lin"              )                                                  

plot of chunk plot-rbg-image-linear

                          plotRGB              (              RGB_stack_HARV              ,                                          r                                          =                                          1              ,                                          g                                          =                                          two              ,                                          b                                          =                                          3              ,                                          scale                                          =                                          800              ,                                          stretch                                          =                                          "hist"              )                                                  

plot of chunk plot-rgb-image-hist

In this example, the stretch doesn't raise the contrast our image significantly given the distribution of reflectance (or brightness) values is distributed well between 0 and 255.

Claiming - NoData Values

Let's explore what happens with NoData values when working with RasterStack objects and using the plotRGB() role. We will utilize the HARV_Ortho_wNA.tif GeoTIFF file in the NEON-DS-Airborne-Remote-Sensing/HARVRGB_Imagery/ directory.

  1. View the files attributes. Are there NoData values assigned for this file?
  2. If so, what is the NoData Value?
  3. How many bands does it have?
  4. Load the multi-band raster file into R.
  5. Plot the object as a true colour image.
  6. What happened to the black edges in the data?
  7. What does this tell usa near the departure in the data structure between HARV_Ortho_wNA.tif and HARV_RGB_Ortho.tif (R object RGB_stack). How can you bank check?

Answers

ane) Commencement we use the GDALinfo() part to view the information attributes.

                                  GDALinfo                  (                  "information/NEON-DS-Airborne-Remote-Sensing/HARV/RGB_Imagery/HARV_Ortho_wNA.tif"                  )                                                                  
                rows        2317  columns     3073  bands       three  lower left origin.ten        731998.v  lower left origin.y        4712956  res.x       0.25  res.y       0.25  ysign       -1  oblique.x   0  oblique.y   0  driver      GTiff  projection  +proj=utm +zone=eighteen +datum=WGS84 +units=grand +no_defs  file        information/NEON-DS-Airborne-Remote-Sensing/HARV/RGB_Imagery/HARV_Ortho_wNA.tif  apparent band summary:    GDType hasNoDataValue NoDataValue blockSize1 blockSize2 1 Float64           TRUE       -9999          1       3073 two Float64           Truthful       -9999          1       3073 3 Float64           Truthful       -9999          ane       3073 apparent band statistics:   Bmin Bmax     Bmean      Bsd 1    0  255 107.83651 xxx.01918 2    0  255 130.09595 32.00168 3    0  255  95.75979 xvi.57704 Metadata: AREA_OR_POINT=Area                              

ii) From the output above, we see that there are NoData values and they are assigned the value of -9999.

3) The data has three bands.

4) To read in the file, we will use the stack() office:

                                  HARV_NA                                                      <-                                                      stack                  (                  "data/NEON-DS-Airborne-Remote-Sensing/HARV/RGB_Imagery/HARV_Ortho_wNA.tif"                  )                                                                  

v) We can plot the data with the plotRGB() part:

                                  plotRGB                  (                  HARV_NA                  ,                                                      r                                                      =                                                      1                  ,                                                      g                                                      =                                                      2                  ,                                                      b                                                      =                                                      3                  )                                                                  

plot of chunk harv-na-rgb

6) The black edges are not plotted. seven) Both information sets take NoData values, however, in the RGB_stack the NoData value is not defined in the tiff tags, thus R renders them every bit black as the reflectance values are 0. The black edges in the other file are defined as -9999 and R renders them as NA.

                                  GDALinfo                  (                  "data/NEON-DS-Airborne-Remote-Sensing/HARV/RGB_Imagery/HARV_RGB_Ortho.tif"                  )                                                                  
                rows        2317  columns     3073  bands       iii  lower left origin.ten        731998.5  lower left origin.y        4712956  res.ten       0.25  res.y       0.25  ysign       -one  oblique.x   0  oblique.y   0  driver      GTiff  projection  +proj=utm +zone=xviii +datum=WGS84 +units=m +no_defs  file        data/NEON-DS-Airborne-Remote-Sensing/HARV/RGB_Imagery/HARV_RGB_Ortho.tif  apparent ring summary:    GDType hasNoDataValue NoDataValue blockSize1 blockSize2 ane Float64           True   -1.7e+308          1       3073 ii Float64           TRUE   -1.7e+308          1       3073 3 Float64           True   -1.7e+308          1       3073 apparent band statistics:   Bmin Bmax Bmean Bsd 1    0  255   NaN NaN 2    0  255   NaN NaN 3    0  255   NaN NaN Metadata: AREA_OR_POINT=Area                              

Data Tip

We can create a RasterStack from several, private single-band GeoTIFFs besides. We will do this in a subsequently episode, Raster Time Series Data in R.

RasterStack vs RasterBrick in R

The R RasterStack and RasterBrick object types tin can both shop multiple bands. Still, how they store each band is different. The bands in a RasterStack are stored as links to raster information that is located somewhere on our computer. A RasterBrick contains all of the objects stored within the actual R object. In most cases, nosotros can work with a RasterBrick in the aforementioned way we might work with a RasterStack. However a RasterBrick is often more efficient and faster to process - which is important when working with larger files.

More Resource

You can read the help for the brick() function by typing ?brick.

We can plow a RasterStack into a RasterBrick in R by using brick(StackName). Let'southward use the object.size() function to compare RasterStack and RasterBrick objects. First nosotros will check the size of our RasterStack object:

                          object.size              (              RGB_stack_HARV              )                                                  

Now we will create a RasterBrick object from our RasterStack data and view its size:

                          RGB_brick_HARV                                          <-                                          brick              (              RGB_stack_HARV              )                                          object.size              (              RGB_brick_HARV              )                                                  

Notice that in the RasterBrick, all of the bands are stored within the bodily object. Thus, the RasterBrick object size is much larger than the RasterStack object.

You utilise the plotRGB() part to plot a RasterBrick too:

plot of chunk plot-brick

Challenge: What Functions Can Be Used on an R Object of a particular course?

We can view diverse functions (or methods) available to use on an R object with methods(class=class(objectNameHere)). Utilise this to figure out:

  1. What methods can be used on the RGB_stack_HARV object?
  2. What methods tin can be used on a unmarried band within RGB_stack_HARV?
  3. Why do you think there is a difference?

Answers

1) Nosotros can encounter a listing of all of the methods available for our RasterStack object:

                                  methods                  (                  grade                  =                  class                  (                  RGB_stack_HARV                  ))                                                                  
                                  [1] !                     !=                    [                       [four] [[                    [[<-                  [<-                     [7] %in%                  ==                    $                      [10] $<-                   addLayer              adjacent               [13] aggregate             all.equal             breathing                [16] approxNA              area                  Arith                  [19] as.array              as.character          as.data.frame          [22] every bit.integer            as.list               as.logical             [25] as.matrix             as.vector             atan2                  [28] bbox                  boxplot               brick                  [31] calc                  cellFromRowCol        cellFromRowColCombine  [34] cellFromXY            cellStats             clamp                  [37] click                 coerce                colFromCell            [40] colFromX              colSums               Compare                [43] coordinates           corLocal              couldBeLonLat          [46] comprehend                 crop                  crosstab               [49] crs<-                 cut                   cv                     [52] density               dim                   dim<-                  [55] disaggregate          dropLayer             extend                 [58] extent                excerpt               flip                   [61] freq                  getValues             getValuesBlock         [64] getValuesFocal        hasValues             head                   [67] hist                  epitome                 init                   [70] inMemory              interpolate           intersect              [73] is.factor             is.finite             is.infinite            [76] is.na                 is.nan                isLonLat               [79] KML                   labels                length                 [82] levels                levels<-              log                    [85] Logic                 mask                  match                  [88] Math                  Math2                 maxValue               [91] hateful                  merge                 metadata               [94] minValue              modal                 mosaic                 [97] names                 names<-               ncell                 [100] ncol                  ncol<-                nlayers               [103] nrow                  nrow<-                origin                [106] origin<-              overlay               pairs                 [109] persp                 plot                  plotRGB               [112] predict               print                 proj4string           [115] proj4string<-         quantile              raster                [118] rasterize             ratify                readAll               [121] readStart             readStop              reclassify            [124] rectify               res                   res<-                 [127] resample              rotate                rowColFromCell        [130] rowFromCell           rowFromY              rowSums               [133] sampleRandom          sampleRegular         calibration                 [136] select                setMinMax             setValues             [139] shift                 prove                  spplot                [142] stack                 stackSelect           stretch               [145] subs                  subset                Summary               [148] summary               t                     tail                  [151] text                  trim                  unique                [154] unstack               values                values<-              [157] weighted.hateful         which.max             which.min             [160] whiches.max           whiches.min           wkt                   [163] writeRaster           xFromCell             xFromCol              [166] xmax                  xmax<-                xmin                  [169] xmin<-                xres                  xyFromCell            [172] yFromCell             yFromRow              ymax                  [175] ymax<-                ymin                  ymin<-                [178] yres                  zonal                 zoom                  see '?methods' for accessing help and source code                              

two) And compare that with the methods available for a unmarried ring:

                                  methods                  (                  class                  =                  class                  (                  RGB_stack_HARV                  [                  one                  ]))                                                                  
                Warning in .S3methods(generic.function, class, envir): 'course' is of length > 1; only the first element volition be used                              
                                  [1] [             [<-           anyDuplicated as_tibble     as.data.frame  [6] as.raster     demark          boxplot       brick         cellFromXY    [11] coerce        coordinates   determinant   distance      duplicated    [16] edit          extent        excerpt       head          initialize    [21] isSymmetric   Math          Math2         Ops           raster        [26] rasterize     relist        subset        summary       surfaceArea   [31] tail          trim          unique        values<-      weighted.mean [36] writeValues   see '?methods' for accessing aid and source code                              

3) There are far more things one could or desire to ask of a total stack than of a single band.

Key Points

  • A single raster file can incorporate multiple bands or layers.

  • Use the stack() function to load all bands in a multi-layer raster file into R.

  • Individual bands within a stack tin can be accessed, analyzed, and visualized using the same functions as single bands.

simpsontheeng.blogspot.com

Source: https://datacarpentry.org/r-raster-vector-geospatial/05-raster-multi-band-in-r/

0 Response to "Read Single Band From Raster in Matlab"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel