Error in rgb color intensity nan, not in [0,1] when using image_palette

I am attempting to create color palettes based on several pictures, namely album covers.
I'm using the LastFM API to acquire the album covers and I'm using RImagePalette to generate the palettes.

Very simply, my code looks as follows, the url used are in the following format:
example album 1 (works fine)

image <- readPNG( getURLContent( url ))
album_palette = image_palette(image, 4)

However, when trying to do this for certain pictures, specifically darker ones it seems to stop working and I get and error saying:
Error in rgb(choice(x$red), choice(x$green), choice(x$blue)) :
color intensity nan, not in [0,1]

An image where this doesn't work is as follows:
example album 2 (not working)

Why are these darker images causing an error and how can I fix it?

I took a stab at reading the source code, I think this is basically a bug and you should report it to the package author.

Specifically, the package considers each channel (red, green, blue) and computes the min, max, "extent" (max-min) and median. Then it takes the channel with the greatest extent and takes its median as a threshold.

The problem with your second image is the red channel has a lot of pixels (more than half) exactly = 0. So its median is 0. But since its min is also 0 (whereas the other channels have only non-0 pixels), it's also the channel with the greatest extent! So the package attempts to use a threshold of 0, bad things ensue.

One easy solution is to inject some noise:

image2 <- image
image2[] <- pmin(image2 + rpois(length(image2), lambda = 1)/100, 1)
RImagePalette::image_palette(image2, 4)

potentially you could inject enough noise to avoid the median=0 problem, but not too much that you change the results. You would need to fine-tune that.

But ultimately I'd say it's a problem in the package logic: the author probably didn't consider this particular edge-case (I think mostly your images are much smaller than his test cases), and might be able to change something in the computation to get a result that makes sense. You could try opening a Github issue, though it doesn't seem like the author has been active on Github recently.

1 Like

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.