# Thresholding Images

This is a package for thresholding images. Let’s load it and some friends.

library(autothresholdr)
library(ijtiff)
library(magrittr)

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

img <- read_tif(system.file("extdata", "fiji_eg.tif",
package = "autothresholdr"))
#> Reading fiji_eg.tif: a 130x130 pixel image of unsigned integer type with 1 channel and 1 frame . . .
#>  Done.
dim(img)
#> [1] 130 130   1   1
display(img[, , 1, 1])  # first channel, first frame

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

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. http://imagej.net/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, auto_thresh_mask() gets the mask (an array with a TRUE for elements exceeding the threshold and FALSE elsewhere) and auto_thresh_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 Huang thresholding.

auto_thresh(img, "huang")
#> [1] 23
#> attr(,"ignore_black")
#> [1] FALSE
#> attr(,"ignore_white")
#> [1] FALSE
#> attr(,"ignore_na")
#> [1] FALSE
#> attr(,"autothresh_method")
#> [1] "Huang"
#> attr(,"class")
#> [1] "th"      "integer"
auto_thresh_mask(img, "huang") %>% {display(.[, , 1, 1])}

auto_thresh_apply_mask(img, "huang") %>% {display(.[, , 1, 1])}

In this last image, the NA pixels are white

## Stacks of Images

We can do the same thing with an image stack.

img <- read_tif(system.file("extdata", "50.tif",
package = "autothresholdr"))
#> Reading 50.tif: a 100x100 pixel image of unsigned integer type with 1 channel and 50 frames . . .
#>  Done.
dim(img)
#> [1] 100 100   1  50
display(img[, , 1, 1])

mean_stack_thresh(img, "tri") %>% {display(.[, , 1, 1])}

med_stack_thresh(img, "tri") %>% {display(.[, , 1, 1])}

These are indeed (on close inspection) slightly different.