qfes / rdeck

Deck.gl widget for R
https://qfes.github.io/rdeck
MIT License
98 stars 0 forks source link

transparent_color not respected with add_bitmap_layer and image passed as array? #41

Closed yvanrichard closed 3 years ago

yvanrichard commented 3 years ago

It looks like transparent_color is not respected when the image is passed as an array to add_bitmap_layer().

Here's a toy example, where I'd like the black background of the image to be transparent.

library(rdeck)
library(raster)

## Some bounds around New Zealand
bounds <- c(xmin = 165.88693, ymin=-52.57695, xmax=183.88419, ymax=-29.22611)

## Get an image of NZ
download.file('https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/Map_of_New_Zealand_%28blank%29.svg/1200px-Map_of_New_Zealand_%28blank%29.svg.png', 'image.png')
nz <- raster('image.png')
nz[] <- nz[] / 255
nz[nz[] < 0.8] <- 0
nz[] <- round(nz[]) # ensure color values are either 0 or 1

## Deck
deck <- rdeck(map_style = 'mapbox://styles/mapbox/dark-v9', initial_bounds = st_bbox(bounds, crs=4326)) %>%
    add_bitmap_layer(
        name = 'NZ'
      , bounds = bounds
      , image = as.array(nz)
      , color_format = 'RGB'
      , transparent_color = '#000000'
    )
deck
anthonynorth commented 3 years ago

transparent_color is the colour to use for transparent pixels. I.e. transparent pixels will become this colour.

As far as I'm aware, BitmapLayer doesn't support replacing visible pixels with a transparent colour; it is simple to do in R however:

# the pre-downloaded image
nz <- png::readPNG("image.png")
# any pixels with a greyscale colour of less than 0.8 * 255 will become transparent
grey <- (nz[, , 1] + nz[, , 2] + nz[, , 3]) / 3
nz[, , 4] <- nz[, , 4] * as.integer(grey >= 0.8)

## Deck
deck <- rdeck(map_style = "mapbox://styles/mapbox/dark-v9", initial_bounds = st_bbox(bounds, crs = 4326)) %>%
  add_bitmap_layer(
    name = "NZ",
    bounds = bounds,
    image = nz
  )

deck

image

yvanrichard commented 3 years ago

Oh right, I was misinterpreting the transparent_color argument. My bad.

Thanks a lot for your elegant solution. And a big thank you for the package! Deck.gl is awesome and being able to use it from R is brilliant.