Error(s) in re-building vignettes:
--- re-building 'README.Rmd' using rmarkdown
<!-- badges: start -->
[![R-CMD-check](https://github.com/ailich/GLCMTextures/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/ailich/GLCMTextures/actions/workflows/R-CMD-check.yaml)
[![CRAN](https://www.r-pkg.org/badges/version/GLCMTextures)](https://cran.r-project.org/package=GLCMTextures)
 [![License: GPLv3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
[![DOI](https://zenodo.org/badge/299630902.svg)](https://zenodo.org/badge/latestdoi/299630902)
<!-- badges: end -->
Please cite as

Ilich, Alexander R. 2020. "GLCMTextures.", https://doi.org/10.5281/zenodo.4310186. https://github.com/ailich/GLCMTextures.

# GLCMTextures

## Purpose

This R package calculates the most common gray-level co-occurrence matrix (GLCM) texture metrics used for spatial analysis (Hall-Beyer 2017). It interfaces with C++ via the Rcpp and RcppArmadillo packages for increased speed.

Texture metrics are calculated using a symmetric gray level co-occurence matrix (GLCM), meaning that each pixel is counted as a focal and neighboring pixel. For more details on how a symmetric GLCM is constructed, I highly recommend checking out Dr. Mryka Hall-Beyer's [GLCM texture tutorial](https://prism.ucalgary.ca/bitstream/handle/1880/51900/texture%20tutorial%20v%203_0%20180206.pdf).

## Motivation

When comparing results across different software that calculate GLCM texture metrics, there are inconsistencies among results. This package is meant to provide a clearly documented implementation of GLCM texture metrics that gives the user control over key parameters to make it clear to the user exactly what they are calculating. As such, the formulas for each texture metric are provided, different shifts can be specified, the user can decide how to handle NA values, and the user gets control over how and if the data should be quantized.

## Install and Load Package

The package can be installed from CRAN using `install.packages("GLCMTextures")` or the development version can be installed from github using the code `remotes::install_github("ailich/GLCMTextures")`. If you are using Windows, you may need to install Rtools using the instructions found [here](https://cran.r-project.org/bin/windows/Rtools/)). To install from github you must already have the remotes package installed, which can be installed using `install.packages("remotes")`

This package relies on the `terra` package for handling of spatial raster data.


## Specifying the Relationship Between Focal and Neighbor Pixels

The convention for specifying the direction of the neighboring pixel (the shift) is shown in the image below. The blue pixel in the center is treated as the focal pixel in the example. Shifts are specified as `c(x_shift, y_shift)`. So, a shift of `c(1,0)` refers to a the neighboring pixel being 1 to the right and 0 upwards of the focal pixel. Since a symmetric GLCM is created, this means each pixel is counted as both a focal and a neighboring pixel, so it also tabulates the shift in the opposite direction `c(-1,0)`, which is the dotted blue line. Therefore, these two shifts will produce equivalent results. Although neighboring pixels are typically considered as those one away in a given direction, the shift value can be specified as any integer value.

![GLCM Shift](../man/figures/GLCM_Shift.png)

## Available Metrics
There are 8 metrics than can be calculated by this package that can be divided into 3 groups: the contrast group, the orderliness group, and the descriptive statistics group (Hall-Beyer 2017). The formulas provided below are from Hall-Beyer (2017).

N = Number of rows or columns in the GLCM (Equal to the number of gray levels)

i = row indices of the GLCM matrix (equal to gray level of reference cell)

j = column indices of the GLCM matrix (equal to gray level of neighboring cell)

P~i,j~ = Probability (relative frequency) of neighboring cells having gray levels i & j

### Contrast Group
$$\text{GLCM Contrast} = \sum_{i,j=0}^{N-1} {P_{i,j}(i-j)^2}$$

$$\text{GLCM Dissimilarity} = \sum_{i,j=0}^{N-1} {P_{i,j}|i-j|}$$

$$\text{GLCM Homogeneity} = \sum_{i,j=0}^{N-1} \frac{P_{i,j}}{1+(i-j)^2}$$

### Orderliness Group
$$\text{GLCM Angular Second Moment (ASM)} = \sum_{i,j=0}^{N-1} {P_{i,j}^2}$$

$$\text{GLCM Entropy} = \sum_{i,j=0}^{N-1} {P_{i,j}[-ln(P_{i,j})]} \text{ where } 0*ln(0)=0$$

### Descriptive Statistics Group
$$\text{GLCM Mean} (\mu) = \sum_{i,j=0}^{N-1} i(P_{i,j})$$

$$\text{GLCM Variance} (\sigma^2) = \sum_{i,j=0}^{N-1} P_{i,j}(i-\mu)^2$$

$$\text{GLCM Correlation} = \sum_{i,j=0}^{N-1} {P_{i,j} \frac{(i-\mu)(j-\mu)}{\sigma^2}}$$

## Tutorial

Load packages


``` r
library(GLCMTextures) #Load GLCMTextures package
```

See package help page


``` r
help(package="GLCMTextures")
```

### Test Matrix

Before conducting texture calculations on entire raster data sets, we will work with a small matrix.


``` r
test_matrix<- matrix(data=c(2,0,1,3,0,0,0,3,2), nrow = 3, ncol=3)
print(test_matrix)
#>      [,1] [,2] [,3]
#> [1,]    2    3    0
#> [2,]    0    0    3
#> [3,]    1    0    2
```

This test matrix has 3 rows and 3 columns and contains values from 0-3 (4 gray levels).

We can use the`make_glcm` function to create a normalized symmetric GLCM.

A GLCM is a tabulation of counts and has the dimensions of the number of gray levels. The GLCM is initialized with all zeros and then we add as we tabulate counts.

**Initialzed GLCM**


```
#>      [,1] [,2] [,3] [,4]
#> [1,]    0    0    0    0
#> [2,]    0    0    0    0
#> [3,]    0    0    0    0
#> [4,]    0    0    0    0
```

The row and column number refers to the gray value of the focal and neighboring pixel (Since gray levels start at a value of 0, the row/column number is 1 larger than the corresponding gray level).We will use a shift of `c(1,0)` meaning that the neighboring pixels is the pixel directly to the right of the focal pixel. We start in the top left corner and we can see that we have a 2 as the focal value and a 3 as the neighboring value directly to the right, so we add 1 to the corresponding position in the GLCM which is row 3 (2+1)/column 4(3+1). Since we would like to create a symmetric GLCM where each pixel is treated as both a focal and neighbor value, we also add to row 4/column 3.


```
#>      [,1] [,2] [,3] [,4]
#> [1,]    0    0    0    0
#> [2,]    0    0    0    0
#> [3,]    0    0    0    1
#> [4,]    0    0    1    0
```

We then continue this process throughout the whole image, moving right to the next focal pixel, and down to start the next row when a given row is completed. The resulting GLCM is a square matrix of counts that is symmetric about the diagonal. 

``` r
horizontal_glcm<- make_glcm(test_matrix, n_levels = 4, shift = c(1,0), normalize = FALSE)
horizontal_glcm
#>      [,1] [,2] [,3] [,4]
#> [1,]    2    1    1    2
#> [2,]    1    0    0    0
#> [3,]    1    0    0    1
#> [4,]    2    0    1    0
```


Once we have finished tabulating all the counts we "normailize" the GLCM by dividing the each element by the sum of all the counts to get relative frequencies or probabilities that a given pixel of value i occurs next to a pixel of value j. The values in a normalized GLCM will therefore sum to 1.


``` r
horizontal_glcm<- horizontal_glcm/sum(horizontal_glcm)
horizontal_glcm
#>            [,1]       [,2]       [,3]       [,4]
#> [1,] 0.16666667 0.08333333 0.08333333 0.16666667
#> [2,] 0.08333333 0.00000000 0.00000000 0.00000000
#> [3,] 0.08333333 0.00000000 0.00000000 0.08333333
#> [4,] 0.16666667 0.00000000 0.08333333 0.00000000
```
This could be accomplished in one line of code by setting the argument `normalize=TRUE` which is the default.

``` r
make_glcm(test_matrix, n_levels = 4, shift = c(1,0), normalize = TRUE)
#>            [,1]       [,2]       [,3]       [,4]
#> [1,] 0.16666667 0.08333333 0.08333333 0.16666667
#> [2,] 0.08333333 0.00000000 0.00000000 0.00000000
#> [3,] 0.08333333 0.00000000 0.00000000 0.08333333
#> [4,] 0.16666667 0.00000000 0.08333333 0.00000000
```

You may have noticed that pixels in the last column of the test matrix did not have a neighboring pixel to the right, so you would not tabulate any counts in those cases; however, this is precisely why we tabulate a symmetrical GLCM as these pixels do have neighbors to the left. Also, note that although the original matrix was 3x3, the GLCM is 4x4 because the size of the GLCM corresponds to the number of gray levels, not the size of the input matrix.

Once the GLCM has been constructed, we can use this to calculate texture metrics using the`glcm_metrics` function to calculate the GLCM texture metrics.


``` r
glcm_metrics(horizontal_glcm)
#>      glcm_contrast glcm_dissimilarity   glcm_homogeneity           glcm_ASM 
#>           4.000000           1.666667           0.400000           0.125000 
#>       glcm_entropy          glcm_mean      glcm_variance   glcm_correlation 
#>           2.138333           1.166667           1.638889          -0.220339
```

### Raster Data

Now we can move from calculating a single value of a given texture metric to calculating raster surfaces of texture metrics.




















Quitting from ./../man/fragments/README_Frag.Rmd:140-143 [elevation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<error/rlang_error>
Error:
! [rast] empty srs
---
Backtrace:
    ▆
 1. ├─terra::rast(...)
 2. └─terra::rast(...)
 3.   └─terra (local) .local(x, ...)
 4.     ├─terra::rast(nrows = nrow(x), ncols = ncol(x), crs = crs, extent = extent)
 5.     └─terra::rast(nrows = nrow(x), ncols = ncol(x), crs = crs, extent = extent)
 6.       └─terra (local) .local(x = x, ...)
 7.         └─terra:::new_rast(...)
 8.           └─terra:::messages(r, "rast")
 9.             └─terra:::error(f, x@pntr$getError())
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Quitting from README.Rmd:23-24 [unnamed-chunk-2]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<error/rlang_error>
Error:
! [rast] empty srs
---
Backtrace:
    ▆
 1. ├─terra::rast(...)
 2. └─terra::rast(...)
 3.   └─terra (local) .local(x, ...)
 4.     ├─terra::rast(nrows = nrow(x), ncols = ncol(x), crs = crs, extent = extent)
 5.     └─terra::rast(nrows = nrow(x), ncols = ncol(x), crs = crs, extent = extent)
 6.       └─terra (local) .local(x = x, ...)
 7.         └─terra:::new_rast(...)
 8.           └─terra:::messages(r, "rast")
 9.             └─terra:::error(f, x@pntr$getError())
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Error: processing vignette 'README.Rmd' failed with diagnostics:
[rast] empty srs
--- failed re-building 'README.Rmd'

SUMMARY: processing the following file failed:
  'README.Rmd'

Error: Vignette re-building failed.
Execution halted