This is a rundown of image dithering, I got all the code from Rasmus Bååth on R-Bloggers. Please refer to the link for code and the tutorial. the image I used can be found here. Credited to Daniel Monteiro on Unsplash.com

Connect with me on linkedin

library(imager)
## Warning: package 'imager' was built under R version 3.5.2
## Loading required package: magrittr
## 
## Attaching package: 'imager'
## The following object is masked from 'package:magrittr':
## 
##     add
## The following objects are masked from 'package:stats':
## 
##     convolve, spectrum
## The following object is masked from 'package:graphics':
## 
##     frame
## The following object is masked from 'package:base':
## 
##     save.image
bubble_gum <- load.image("daniel.jpg")
plot(bubble_gum)

bubble_gum_grey <- grayscale(rm.alpha(bubble_gum))
plot(bubble_gum_grey)

bubble_gum_threshold <- bubble_gum_grey > 0.5
plot(bubble_gum_threshold)

rand_matrix <- matrix(
  data = runif(length(bubble_gum_grey)),
  ncol = ncol(bubble_gum_grey), nrow=nrow(bubble_gum_grey))
rand_cimg <- as.cimg(rand_matrix)
plot(rand_cimg)

bubble_gum_rand <- bubble_gum_grey > rand_cimg
plot(bubble_gum_rand)

checker_pattern <- rbind(c(1/3, 2/3),
                         c(2/3, 1/3))
plot(as.cimg(checker_pattern))

rep_mat <- function(mat, nrow_out, ncol_out) {
  mat[rep(seq_len(nrow(mat)), length.out = nrow_out),
      rep(seq_len(ncol(mat)), length.out = ncol_out)]
}

checker_cimg <- as.cimg(rep_mat(checker_pattern, nrow(bubble_gum_grey), ncol(bubble_gum_grey)))
plot(checker_cimg)

bubble_gum_checker <- bubble_gum_grey > checker_cimg
plot(bubble_gum_checker)

gradient <- as.cimg( rep(seq(0, 1, 0.01), 101), x=101, y=101)
plot(gradient)

checker_cimg <- as.cimg(rep_mat(checker_pattern,
                                nrow(gradient), ncol(gradient)))

gradient_checker <- gradient > checker_cimg
plot(gradient_checker)

recursive_bayer_pattern <- function(n) {
  if(n <= 0) {
    return(matrix(0))
  }
  m <- recursive_bayer_pattern(n - 1)
  rbind(
    cbind(4 * m + 0, 4 * m + 2),
    cbind(4 * m + 3, 4 * m + 1))
}


normalized_bayer_pattern <- function(n) {
  pattern <- recursive_bayer_pattern(n)
  (1 + pattern) / ( 1 + length(pattern) )
}

bayer_cimg <- as.cimg(rep_mat(normalized_bayer_pattern(2),
                              nrow(gradient), ncol(gradient)))
gradient_bayer <- gradient > bayer_cimg
plot(gradient_bayer)

bayer_matrix <- rep_mat(normalized_bayer_pattern(2),
                        nrow(bubble_gum_grey), ncol(bubble_gum_grey))
bayer_cimg <- as.cimg(bayer_matrix)
bubble_gum_bayer <- bubble_gum_grey > bayer_cimg
plot(bubble_gum_bayer)

bubble_gum_bayer_color <- bubble_gum
for(rgb_i in 1:3) {
  color_channel <- bubble_gum_bayer_color[ , , 1, rgb_i, drop = FALSE]
  bubble_gum_bayer_color[ , , 1, rgb_i] <- color_channel > bayer_cimg
}
plot(bubble_gum_bayer_color, xaxt = "n")