Anastasia Karamitsou
Anastasia Karamitsou

Reputation: 11

How to turn a TIFF file into a binary image in R?

I have a TIFF file, and I need to turn it into a binary image. Is this possible in R? How should I write the arguments for setting a threshold?

Upvotes: 1

Views: 1087

Answers (2)

Droplet
Droplet

Reputation: 1125

Another option is to use the magick R package, based on the ImageMagick library:

library(magick)
#> Linking to ImageMagick 6.9.7.4
#> Enabled features: fontconfig, freetype, fftw, lcms, pango, x11
#> Disabled features: cairo, ghostscript, rsvg, webp

logo <- image_read("logo:")

plot(logo)

logo_gray <- image_convert(logo, colorspace = "Gray")

plot(logo_gray)

logo_bw <- logo_gray %>%
  image_threshold(type = "white", threshold = "50%") %>%
  image_threshold(type = "black", threshold = "50%")

plot(logo_bw)

Created on 2019-03-20 by the reprex package (v0.2.1)

Alternatively, if you want local adaptive thresholding, you should have a look at the image_lat() function.

Upvotes: 0

Sandipan Dey
Sandipan Dey

Reputation: 23101

You can use the imager library's threshold function. From the documentation:

library(imager)
im <- load.image("cameraman.tif") # provide the correct image path 
im.g <- grayscale(im)
im.g %>% plot

enter image description here

threshold(im.g,"15%") %>% plot # the threshold will be set at 15th percentile 

enter image description here

threshold(im.g,"auto") %>% plot # a threshold will be computed automatically using kmeans

enter image description here

#If auto-threshold is too high, adjust downwards or upwards using "adjust"
threshold(im,adjust=1.3) %>% plot

enter image description here

Upvotes: 1

Related Questions