---
title: "Thresholding Images"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Thresholding Images}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
if (utils::packageVersion("knitr") >= "1.20.15") {
  knitr::opts_chunk$set(
    collapse = TRUE,
    comment = "#>",
    fig.width = 7, fig.height = 6,
    tidy = "styler"
  )
} else {
  knitr::opts_chunk$set(
    collapse = TRUE,
    comment = "#>",
    fig.width = 7, fig.height = 6
  )
}
```

# Thresholding Images

Although this package is for thresholding anything at all, it has added functionality for thresholding images. This vignette is all about thresholding single-frame, grayscale images. There's [another vignette](https://rorynolan.github.io/autothresholdr/articles/thresholding-image-stacks.html) about thresholding stacks of grayscale images.

```{r load libraries, results='hide'}
library(autothresholdr)
```

We'll be using the image that comes with the package:

```{r the image}
img <- ijtiff::read_tif(system.file("extdata", "fiji_eg.tif",
  package = "autothresholdr"
))
dim(img)
ijtiff::display(img) # displays first channel, first frame
```

It's a picture of cells, the black part is where the cells are not. The threshold is supposed to tell us what is *dark* (not cell) and what is *bright* (cell). By playing around, we may discover that something like 20 might (for some purposes) be a good value.

```{r guess twenty}
ijtiff::display(img[, , 1, 1] > 20)
```

But what if we have many images and we don't want to *play around*, we want a method of calculating the threshold automatically. https://imagej.net/plugins/auto-threshold gives many such methods and they are provided to you in R via this package. Go to that webpage for a nice comparison of the methods.

The function `auto_thresh()` finds the threshold, `mask()` gets the mask (an array with a `TRUE` for elements exceeding the threshold and `FALSE` elsewhere) and `apply_mask()` applies the mask to the original image by setting the elements that don't exceed the threshold to `NA`.

Let's see each with "Triangle" thresholding.

```{r thresh mask apply}
auto_thresh(img, "tri")
ijtiff::display(mask(img, "tri"))
ijtiff::display(apply_mask(img, "tri"))
```

In this last image, the `NA` pixels are grey.
