dahtah / imager

R package for image processing
GNU Lesser General Public License v3.0
187 stars 43 forks source link

Example of colorise not working #140

Open tamas-ferenci opened 3 years ago

tamas-ferenci commented 3 years ago

Here is a minimal reproducible example:

library(imager)
im <- load.example("coins")
colorise(im,~ x < 50,"blue") %>% plot

This results in Error in if (spectrum(px) != 1) { : argument is of length zero.

ShotaOchi commented 3 years ago

The example works on my machine. Can you show the result of sessionInfo()?

tamas-ferenci commented 3 years ago

Sure, thanks!

sessionInfo()
#> R version 4.0.4 (2021-02-15)
#> Platform: x86_64-w64-mingw32/x64 (64-bit)
#> Running under: Windows 10 x64 (build 19042)
#> 
#> Matrix products: default
#> 
#> locale:
#> [1] LC_COLLATE=Hungarian_Hungary.1250  LC_CTYPE=Hungarian_Hungary.1250   
#> [3] LC_MONETARY=Hungarian_Hungary.1250 LC_NUMERIC=C                      
#> [5] LC_TIME=Hungarian_Hungary.1250    
#> 
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base     
#> 
ShotaOchi commented 3 years ago

The example works on my R 4.0.4 for Windows. What is the version of imager? And can you show the result of the following code?

library(imager)
im <- load.example("coins")
imeval(im, ~ x < 50) %>% print
tamas-ferenci commented 3 years ago

The version is imager 0.42.3 2020-05-11 [1] CRAN (R 4.0.3). Your code returns:

> im <- load.example("coins")
> imeval(im, ~ x < 50) %>% print
[1] NA

My naive debugging suggests that the problem is here: eval.form(args[[1]]) with eval.form being function(fo) parse(text = as.character(fo)[2]) %>% eval(envir = newenv). With this call the value of args[[1]] is ~x < 50, thus as.character(fo) is "~x < 50" which has no second component, thus it'll be NA, the eval of which is also NA.

ShotaOchi commented 3 years ago

It should be ok because args[[1]] is a formula. Consider the following example.

a <- ~ x < 50
as.character(a)

[1] "~" "x < 50"

as.character(a)[2]

[1] "x < 50"

ShotaOchi commented 3 years ago

I think eval function doesn't evaluate the formula as we expect for some reason. It seems that eval function finds the variables needed to evaluate the formula but they are not what we expect because eval function doesn't return an error. What is the result of imeval if you use basenev() as env?

library(imager)
im <- load.example("coins")
imeval(im, ~ x < 50, env = baseenv()) %>% print
tamas-ferenci commented 3 years ago

Wow, that's really strange. The problem is actually quite simple: as.character(~ x < 50) results in "~x < 50" at my computer.

I have absolutely no idea how is it possible, but I think you can close the issue now, because it has quite clearly nothing to do with imager. Thank you very much for the help in debugging!