---
title: "Detrending images with `detrendr`"
author: "Rory Nolan"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{detrendr}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

Detrend image series.

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, comment = "#>", 
                      fig.width = 7, fig.height = 6)
```

First let's load the library: 
```{r load}
library(detrendr)
```

## An image in need of detrending
The package contains a sample image series which can be found at  
`system.file("extdata", "bleached.tif", package = "detrendr")`. It's 500 frames of diffusing fluorescent particles which are bleaching over the course of the acquisition. We can see they're bleaching by displaying every 99th frame.

```{r visualize bleaching, fig.height=2.6, fig.width=7}
library(magrittr)
path <- system.file("extdata", "bleached.tif", package = "detrendr")
img <- ijtiff::read_tif(path, msg = FALSE)
every100th <- purrr::map(seq(1, dim(img)[4], by = 99), ~ img[, , 1, .]) %>% 
  purrr::reduce(~ cbind(.x, max(img), .y))
ijtiff::display(every100th)
```

### Detrending
We see that the intensity is much lower for the last frame, this is because the image series has been bleached. We can correct for this. 

```{r detrend, fig.height=2.6, fig.width=7}
system.time(corrected_exp <- img_detrend_exp(img, "auto", purpose = "FFS",
                                             parallel = 2))["elapsed"]
every100th <- purrr::map(seq(1, dim(img)[4], by = 99), 
                         ~ corrected_exp[, , 1, .]) %>% 
  purrr::reduce(~ cbind(.x, max(img), .y))
ijtiff::display(every100th)
```

So we see that the corrected series does not have this drop-off in intensity. 

Above we used *exponential filtering* detrending, but we could also use *boxcar* or *polynomial*. 
```{r boxcar and polynom}
system.time(corrected_boxcar <- img_detrend_boxcar(img, "auto", purpose = "FFS",
                                  parallel = 2))["elapsed"]
system.time(corrected_polynom <- img_detrend_polynom(img, "auto", 
                                   purpose = "FFS",
                                   parallel = 2))["elapsed"]
```

Let's check the mean brightness of each:
```{r compare brightnesses}
mean(brightness_pillars(corrected_exp))
mean(brightness_pillars(corrected_boxcar))
mean(brightness_pillars(corrected_polynom))
```

So we see that different methods give different results.
