Skip to content

Instantly share code, notes, and snippets.

@FlukeAndFeather
Created February 12, 2020 23:36
Show Gist options
  • Save FlukeAndFeather/41192b62fa0bec0ff7aad2ccdec0a126 to your computer and use it in GitHub Desktop.
Save FlukeAndFeather/41192b62fa0bec0ff7aad2ccdec0a126 to your computer and use it in GitHub Desktop.
# Takes a grayscale tiff (with alpha) and converts all dark points (by threshold) to the new color
colorize_tiff <- function(input, threshold, newcolor) {
# Read original tiff
orig_tiff <- tiff::readTIFF(input)
# Convert grayscale to black and white
orig_tiff[, , 1] <- ifelse(orig_tiff[, , 1] > threshold, 1, 0)
# Create a colorized tiff
new_tiff <- array(0, dim = c(dim(orig_tiff)[1:2], 4))
# Set RGB
new_tiff[, , 1] <- ifelse(orig_tiff[, , 1] == 0, newcolor[1], 1)
new_tiff[, , 2] <- ifelse(orig_tiff[, , 1] == 0, newcolor[2], 1)
new_tiff[, , 3] <- ifelse(orig_tiff[, , 1] == 0, newcolor[3], 1)
# Recover alpha
new_tiff[, , 4] <- orig_tiff[, , 2]
new_tiff
}
# Plotting to sanity check
plot_tiff <- function(tiff) {
plot(0:1, 0:1, type = "n", xlab = "", ylab = "")
rasterImage(as.raster(tiff), 0, 0, 1, 1)
}
# Look up Blue_Transparent.tif
bm_path <- file.choose()
# Convert blue whale to blue
bm_blue <- colorize_tiff(
bm_path,
0.4,
c(48, 112, 173) / 255
)
# Check it out
plot_tiff(bm_blue)
# Can save using tiff::writeTIFF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment