Giter VIP home page Giter VIP logo

imager's People

Contributors

arfon avatar asgr avatar bisaloo avatar dahtah avatar devsjr avatar karldw avatar salim-b avatar sebastien-jalgos avatar shotaochi avatar uribo avatar velaco avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

imager's Issues

Can't save to file when file/pathname contains dots

I just ran into this today. If I pass a file or pathname that contains a dot to save.image, and ImageMagick isn't available, the save fails:

> save.image(boats, file="my.file.jpg")
Error in save.image(boats, file = "my.file.jpg") : 
  Unsupported output file format. Use jpg/png or install ImageMagick
> save.image(boats, file="temp.folder/myfile.jpg")
Error in save.image(boats, file = "temp.folder/myfile.jpg") : 
  Unsupported output file format. Use jpg/png or install ImageMagick

The underlying cause is the regex that save.image uses to detect the file type:

    ftype <- stringr::str_match(file, "\\.(.+)$")[1, 2]
    if (ftype == "png") ...

If file contains more than one dot, it will match everything past the first dot:

> stringr::str_match("my.file.jpg", "\\.(.+)$")
     [,1]        [,2]      
[1,] ".file.jpg" "file.jpg"

Replacing the regex with \\.([^.]+)$ should fix this:

> stringr::str_match("my.file.jpg", "\\.([^.]+)$")
     [,1]   [,2] 
[1,] ".jpg" "jpg"

Mac crash on loading png files

For example: load.example("parrots") results in:
*** caught segfault ***
address 0x18, cause 'memory not mapped'

I believe imager uses read.bitmap() from readbitmap package, which in turn uses readPNG() from png package.

I have contacted Peter Urbanak on more than one occasion, filed a bug report, etc., perhaps if the developer of a package that depended upon his were to reach out the problem might be fixed!

It used to work just fine under R3.2, broke when I went to R3.3 and still doesn't work under R3.4.

Convert/read from magick

Also ref: ropensci/magick#34
How can I read from a magick-image into imager::Cimg?

> head(dimg)
  format width height colorspace filesize
1   JPEG  3266   2450       sRGB        0
> str(dimg)
Class 'magick-image' <externalptr> 

Do we need some helper methods?

as.cimg.magick-image

Would it make sense to add such a function to the imager package? Or is there a quicker alternative for the conversion?

library(imager)
library(magick)
library(abind)
"as.cimg.magick-image" <- function(x){
  out <- lapply(x, FUN=function(frame){
    frame <- as.integer(frame[[1]])[, , 1:3] # dropping the alpha channel
    dim(frame) <- append(dim(frame), 1, after = 2)
    frame
  })
  out$along <- 3
  out <- do.call(abind::abind, out)
  out <- as.cimg(out)
  out <- permute_axes(out, "yxzc")
  out
}
banana <- image_read("https://jeroenooms.github.io/images/banana.gif")
x <- as.cimg(banana)
plot(x, 7)

Size Limitation

When I try to load large images with imager the result is that the computer locks up and has to be restarted. This seems to happen for anything beyond a few hundred pixels across. I do understand that any scaling should be approximately quadratic but I was surprised that an image of 1000x1000 pixels caused so much trouble when a 500x500 version of the same file loaded instantly.

Is this more likely to do with how imager is designed or limitations of the hardware (laptop) I'm using?

any function for contrast limit histogram equalization?

Hi Dahtah,
is there any function I can use for contrast limit histogram equalization? I mean we can use the function for clipping image. I know there is a function called hist.eq( ) which can do histogram equalization but here I want one which can do contrast limit. Thanks!

Error when i call imager in r 3.3

Hello, I use imager in r but i cannot load the package properly.

system: opensuse leap 42.2
R version: 3.3

when i typed the command below I got error message as follows:

library(imager)

Error in get(Info[i, 1], envir = env) :
cannot open file '/home/issactoast/R/x86_64-suse-linux-gnu-library/3.3/imager/R/imager.rdb': No such file or directory
Error: package or namespace load failed for ‘imager’

Support 1-row data frame

row <- data.frame(t(runif(64)))
as.cimg(row, x=8, y=8)

Gives a confusing error: "Error in function_list[k] : Variable value is missing"

The solution is:

as.cimg(unlist(row), x=8, y=8)

Can the library do the unlist automatically? I think this might be the most common use-case?

There might be a more elegant way, but I think adding this line to the top of imager:::as.cimg.data.frame() will do it:

if(nrow(obj) == 1)obj <- unlist(obj)

No need for Cairo support (?)

Hi, as far as I can tell there is no need for Cairo as a import dependency (I've removed it on my local fork). The reason this was an issue for us is some super-computer systems (Cray for sure) have no support for libcairo and we couldn't get things working just for this reason. There might be a reason for it being in the import list, but I couldn't easily spot it.

A

No images can bre loaded without ImageMagic

On Windows 10, R3.2.3, Imager 0.15, no images could be loaded e.g.
fpath <- system.file('extdata/Leonardo_Birds.jpg',package='imager')
im <- load.image(fpath)
would fail on the second line
until ImageMagick was installed. The error was about unrecognized image format.

save.image after grayscale results in black images

Hello everybody,
when i try to save an image

library(imager) 
fpath <- system.file('extdata/Leonardo_Birds.jpg',package='imager') 
im <- load.image(fpath)
save.image(im, "test.jpg")

everything, went's fine, but if i change the last row with

save.image(grayscale(im), "test.jpg")

i get an black image. Missed i something or is it a bug?

best regards
Andreas

Error in download.file(url, method = method, ...)

I am trying to reproduce your code that is given here.

When I run the following code:

im <- load.image("https://upload.wikimedia.org/wikipedia/commons/thumb/f/fd/Aster_Tataricus.JPG/1024px-Aster_Tataricus.JPG")

I get the following error:

trying URL 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/fd/Aster_Tataricus.JPG/1024px-Aster_Tataricus.JPG'
Error in download.file(url, method = method, ...) : 
  cannot open URL 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/fd/Aster_Tataricus.JPG/1024px-Aster_Tataricus.JPG'

How do I solve this error?
I am working on an Windows 8 machine.

Also, is there a method to load locally downloaded images into Rstudio using imager?

load.image() error

require(imager)
im = load.image("text.jpg")

Error: [instance(0,0,0,0,0000000000000000,non-shared)] CImg::load(): Failed to recognize format of file 'D:\r\mxnet\text.jpg'.

channel combine problem

hi boss, @dahtah
i have 2 pics, A and B, both with RGB channels
i have split their channels with imsplit(img,'c'),
now i wanna combine A's RGB channels with B's channel[[1]] and save it as a tiff,
can you give sm advices ?
as my test:
t2 <- add(imlist(t1[[1]],t1[[2]],t1[[3]],t2[[1]]))
t2
Image. Width: 424 pix Height: 512 pix Depth: 1 Colour channels: 1

cimg::load_network(): Failed to load file

I get the following error when I run load.image("https://cran.r-project.org/Rlogo.jpg")

sh: -c: line 0: unexpected EOF while looking for matching `"'
sh: -c: line 1: syntax error: unexpected end of file
Error in eval(substitute(expr), envir, enclos) : 
  cimg::load_network(): Failed to load file 'https://cran.r-project.org/Rlogo.jpg' with external commands 'wget' or 'curl'.

Environment:
R version 3.3.1 (2016-06-21)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.10.5 (Yosemite)

Better handling of corrupt files?

Dear Simon,

great work on imager. I use it to process many files, some of which may be corrupted (somehow).
I was wondering whether load.image could be slightly more immune to those files.

Attachment:
corrupted_file

On load.image("corrupted_file.jpg") I get

'gm.exe' is not recognized as an internal or external command,
operable program or batch file.
'gm.exe' is not recognized as an internal or external command,
operable program or batch file.
Error in load_image(file) : 
  cimg::stderr(): Reference to 'stderr' stream not allowed in R mode ('cimg_use_r' is defined).

I am using try() on load.image so it is not a major issue, but perhaps can be cleaned up (also, the first two messages cannot be suppressed).

(Windows 7, R 3.4.0, imager 0.40.2)

installation problem on xubuntu

when trying to install imager (both github and install.packages("imager"), I get this message:

* installing *source* package ‘imager’ ...
** package ‘imager’ successfully unpacked and MD5 sums checked
checking for gcc... gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables... 
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking how to run the C preprocessor... gcc -E
checking for X... libraries , headers 
configure: creating ./config.status
config.status: creating src/Makevars
** libs
g++ -I/usr/share/R/include -DNDEBUG -I../inst/include -DCIMG_COMPILING -Dcimg_use_rng -Dcimg_r_mode -Dcimg_use_fftw3_singlethread -Dcimg_verbosity=1 -DSTRICT_R_HEADERS  -I"/home/henk/R/x86_64-pc-linux-gnu-library/3.2/Rcpp/include"   -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c RcppExports.cpp -o RcppExports.o
g++ -I/usr/share/R/include -DNDEBUG -I../inst/include -DCIMG_COMPILING -Dcimg_use_rng -Dcimg_r_mode -Dcimg_use_fftw3_singlethread -Dcimg_verbosity=1 -DSTRICT_R_HEADERS  -I"/home/henk/R/x86_64-pc-linux-gnu-library/3.2/Rcpp/include"   -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c colourspace.cpp -o colourspace.o
g++ -I/usr/share/R/include -DNDEBUG -I../inst/include -DCIMG_COMPILING -Dcimg_use_rng -Dcimg_r_mode -Dcimg_use_fftw3_singlethread -Dcimg_verbosity=1 -DSTRICT_R_HEADERS  -I"/home/henk/R/x86_64-pc-linux-gnu-library/3.2/Rcpp/include"   -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c display.cpp -o display.o
g++ -I/usr/share/R/include -DNDEBUG -I../inst/include -DCIMG_COMPILING -Dcimg_use_rng -Dcimg_r_mode -Dcimg_use_fftw3_singlethread -Dcimg_verbosity=1 -DSTRICT_R_HEADERS  -I"/home/henk/R/x86_64-pc-linux-gnu-library/3.2/Rcpp/include"   -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c drawing.cpp -o drawing.o
g++ -I/usr/share/R/include -DNDEBUG -I../inst/include -DCIMG_COMPILING -Dcimg_use_rng -Dcimg_r_mode -Dcimg_use_fftw3_singlethread -Dcimg_verbosity=1 -DSTRICT_R_HEADERS  -I"/home/henk/R/x86_64-pc-linux-gnu-library/3.2/Rcpp/include"   -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c filtering.cpp -o filtering.o
In file included from ../inst/include/imager.h:21:0,
                 from filtering.cpp:2:
../inst/include/CImg.h:424:19: fatal error: fftw3.h: No such file or directory
 #include "fftw3.h"
                   ^
compilation terminated.
make: *** [filtering.o] Error 1
ERROR: compilation failed for package ‘imager’
* removing ‘/home/henk/R/x86_64-pc-linux-gnu-library/3.2/imager’
Warning in install.packages :
  installation of package ‘imager’ had non-zero exit status

The downloaded source packages are in
    ‘/tmp/RtmpuKsXQP/downloaded_packages’
> sessionInfo()
R version 3.2.2 (2015-08-14)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 14.04.3 LTS

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8     LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                  LC_ADDRESS=C               LC_TELEPHONE=C             LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] rsconnect_0.4.2.2 tools_3.2.2      

overlaying and stacking images

How can I overlay an image to another image given some x,y pixels? is that possible in imager?

If I have two images, how can I make a new images by putting them together side by side?
This is what I am doing right now: stacking arrays.

library(abind)
  x <- abind(img1, img2, along = 1)
  x <- as.cimg(x)

I was wondering if there is some function in ìmager` to handle this.
Thanks for the help!

Efficient custom filter

(Feature request)

I want to write a custom image processing function; it would be useful to have a function that allows processing a NxM (e.g. 3x3) sliding window over an image. I ran the below code, by using d <- as.vector(im) on my imager object, im. I was fairly pleased with the results (*), but it was very slow.

What would be nice is a function something like:

im2 <- imcustom(im, 3, 3, function(m){
#m is a 3x3 matrix
#return the new value of the point at the centre
})

(Hhhmmm, my below code is actually modifying multiple points, as it processes each 3x3 matrix, so maybe the above is not flexible enough. But I think the above kind of function would still be a useful thing to have?)

*: This is a 28x28 greyscale image, and I wanted to sharpen the results. I found this code more effective than the imsharpen() function. (I'm about to open a second feature request, which will explain the real problem I'm trying to solve here.)

sharpenImageVector = function(d){
threshold = 100  #Pixels dimmer than this never get any bonuses
strength = 40  #How much to sharpen: lower number means more sharpening
d2 = d
for(row in (2:27)-1){
  for(col in 2:27){
    ix=(row*28)+col   #30:462  (but with gaps, e.g. 30:55, 58:83, etc.)
    v = d[ix]
    for(offset in c(-29,-28,-27,-1,1,27,28,29)){
      if(v < d[ix+offset] && d[ix+offset] >= threshold){
        z = d[ix+offset] / strength   #How much to move
        d2[ix+offset] = d2[ix+offset] + z  #Give it to neighbour
        d2[ix] = d2[ix] - z  #Take it from us
        }
      }
    }
  }

#Now clip to 0..255, and return an integer vector
d2 = trunc(d2)
d2 = ifelse(d2<0,0,d2)
d2 = ifelse(d2>255,255,d2)
as.integer(d2)
}

imager doesn't compile with MKL (2017) compiled version of R-3.3.3

...snip...
In file included from /home/jon/R/x86_64-pc-linux-gnu-library/3.3/Rcpp/include/RcppCommon.h(64),
from /home/jon/R/x86_64-pc-linux-gnu-library/3.3/Rcpp/include/Rcpp.h(27),
from ../inst/include/imager.h(11),
from RcppExports.cpp(4):
/data/opt/intel/compilers_and_libraries_2017.1.132/linux/compiler/include/complex(265): error #308: member "std::complex::_M_value" (declared at line 1341 of "/home/usr/bin/../include/c++/5/complex") is inaccessible
return ~__z._M_value;
^

...snip...
compilation aborted for RcppExports.cpp (code 2)
/usr/local/lib64/R/etc/Makeconf:141: recipe for target 'RcppExports.o' failed
make: *** [RcppExports.o] Error 2
ERROR: compilation failed for package ?imager?
removing ?/home/jon/R/x86_64-pc-linux-gnu-library/3.3/imager?

Many other packages compile/install fine.

If I follow: http://stackoverflow.com/questions/36722505/installing-r-forecast-package-on-a-linux-cluster-compiler-issues , then I get the errors:

../inst/include/CImg.h(28776): error: parallel loops with collapse must be perfectly nested
for (int c = c0; c<(int)sc; c+=spectrum())
^
detected during:
instantiation of "cimg_library::CImg cimg_library::CImg::get_resize(int, int, int, int, int, unsigned int, float, float, float, float) const [with T=unsigned char]" at line 28711
instantiation of "cimg_library::CImg &cimg_library::CImg::resize(int, int, int, int, int, unsigned int, float, float, float, float) [with T=unsigned char]" at line 58816
instantiation of "const cimg_library::CImgList<cimg_library::CImgList::ucharT> &cimg_library::CImgList::font(unsigned int, bool) [with T=unsigned char]" at line 44013
instantiation of "cimg_library::CImg &cimg_library::CImg::draw_text(int, int, const char *, const tc1 *, const tc2 *, float, unsigned int, ...) [with T=unsigned char, tc1=unsigned char, tc2=unsigned char]" at line 59949
instantiation of "int cimg_library::cimg::dialog(const char *, const char *, const char *, const char *, const char *, const char *, const char *, const char *, const cimg_library::CImg &, bool) [with t=unsigned char]" at line 60088

Error: the OpenMP "single" pragma must not be enclosed by the "for" pragma
detected during:
instantiation of "cimg_library::CImg cimg_library::CImg::get_resize(int, int, int, int, int, unsigned int, float, float, float, float) const [with T=unsigned char]" at line 28711 of "../inst/include/CImg.h"
instantiation of "cimg_library::CImg &cimg_library::CImg::resize(int, int, int, int, int, unsigned int, float, float, float, float) [with T=unsigned char]" at line 58816 of "../inst/include/CImg.h"
instantiation of "const cimg_library::CImgList<cimg_library::CImgList::ucharT> &cimg_library::CImgList::font(unsigned int, bool) [with T=unsigned char]" at line 44013 of "../inst/include/CImg.h"
instantiation of "cimg_library::CImg &cimg_library::CImg::draw_text(int, int, const char *, const tc1 *, const tc2 *, float, unsigned int, ...) [with T=unsigned char, tc1=unsigned char, tc2=unsigned char]" at line 59949 of "../inst/include/CImg.h"
instantiation of "int cimg_library::cimg::dialog(const char *, const char *, const char *, const char *, const char *, const char *, const char *, const char *, const cimg_library::CImg &, bool) [with t=unsigned char]" at line 60088 of "../inst/include/CImg.h"

Purpose is to compile mxnet R stuff with R compiled with icpc/icc and MKL. R works and many other packages work, but this stops me from installing mxnet with R support.

grayscale function difference between windows and ubuntu

Hi,
First thank you very much for this package, which i like and use a lot.
However, I am having some problem passing my code from windows to linux. The grayscale function give very different results.
in linux :

summary(grayscale(boats))
Min. 1st Qu. Median Mean 3rd Qu. Max.
0.08454 0.44090 0.53570 0.51690 0.59970 0.99700
in windows :
summary(grayscale(boats))
Min. 1st Qu. Median Mean 3rd Qu. Max.
0.07847 0.43400 0.52270 0.50720 0.58560 0.98630

in linux the two method ("luma" and "XYZ") gives differents results than in windows

The help from the grayscale function in windows says "This function converts from RGB to grayscale by first converting to HSL and keeping only the L channel". So I have try in linux to use the RGBtoHSL function and extract the L channel in linux to reproduce the grayscale function of windows. Now, the histogram now look the same however the values are differents. In linux you have to divide the L channel by 255 to have the same results than in windows.
for example in linux :
summary(channel(RGBtoHSL(im),3)/255)
is the same in windows that
summary(channel(RGBtoHSL(im),3))
Sadly, this example don't work for boats because the max value for boats are different (255 in windows, 1 in linux).
Even if my problem is resolved, this is very confusing, because my code who work perfectly in windows has to be changed to run on linux.
May be this has to be resolved,
Thank you again for this brillant package.
Cheers,

Fabien

Hough transform

Add Hough transform, possibly from CImg's own hough_transform2d.cpp

png metadata

Is it possible to extract/read metadata associated to a png?
The png package has it:

img5 <- readPNG(r, info=TRUE)
attr(img5, "info")
attr(img5, "metadata")

can't load url's

running the example gives me errors:

> imager::load.image("https://cran.r-project.org/Rlogo.jpg")
sh: -c: line 0: unexpected EOF while looking for matching `"'
sh: -c: line 1: syntax error: unexpected end of file
Error in eval(substitute(expr), envir, enclos) : 
  cimg::load_network(): Failed to load file 'https://cran.r-project.org/Rlogo.jpg' with external commands 'wget' or 'curl'.

i have imagemagick, etc installed. i can replicate on CRAN as well as latest Github versions. the imager::read.jpeg function also fails since it passes the url rather than content to the jpeg::readJPEG function

the 'parrots' example works for me

search <- read_html("https://www.google.com/search?site=&tbm=isch&q=parrot")
urls <- search %>% html_nodes("img") %>% html_attr("src") #Get urls of parrot pictures
imager::load.image(urls[1]) %>% plot()

Build warning "unused function 'validateSignature'"

Nice package! I'm looking forward to trying it out on some image processing analysis I've been doing in Matlab because of the lack of tools in R.

Thought you might want to know I got a couple of build warnings:

> install_github("dahtah/imager")
Downloading github repo dahtah/imager@master
Installing imager
'/Library/Frameworks/R.framework/Resources/bin/R' --no-site-file --no-environ  \
  --no-save --no-restore CMD INSTALL  \
  '/private/var/folders/pj/42xw7sns6kq9pwkf72h9zdyr0000gn/T/Rtmp7yEZib/devtools167856dfb7b0/dahtah-imager-27a7789'  \
  --library='/Library/Frameworks/R.framework/Versions/3.2/Resources/library'  \
  --install-tests 

* installing *source* package ‘imager’ ...
Warning in .write_description(db, file.path(outDir, "DESCRIPTION")) :
  Unknown encoding with non-ASCII data: converting to ASCII
** libs
clang++ -I/Library/Frameworks/R.framework/Resources/include -DNDEBUG -I/opt/X11/lib -I/usr/X11R6/include -I/usr/local/include -I/usr/local/include/freetype2 -I/opt/X11/include -I"/Library/Frameworks/R.framework/Versions/3.2/Resources/library/Rcpp/include"   -fPIC  -Wall -mtune=core2 -g -O2  -c RcppExports.cpp -o RcppExports.o
In file included from RcppExports.cpp:4:
In file included from ./../inst/include/imager.h:7:
./../inst/include/imager_RcppExports.h:14:14: warning: unused function 'validateSignature'
      [-Wunused-function]
        void validateSignature(const char* sig) {
             ^
1 warning generated.
[[... snipped ...]]

Here's the result of sessionInfo():

R version 3.2.0 (2015-04-16)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.10.3 (Yosemite)

locale:
[1] en_CA.UTF-8/en_CA.UTF-8/en_CA.UTF-8/C/en_CA.UTF-8/en_CA.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] imager_0.1    stringr_1.0.0 magrittr_1.5  plyr_1.8.2   

loaded via a namespace (and not attached):
[1] tools_3.2.0   Rcpp_0.11.6   stringi_0.4-1

plyr dependency

Could plyr be moved from a Dependency to an Import? Right now attaching imager after e.g. dplyr will lead to issues as plyr is getting attached as well.

Thanks for the very useful package! 👍

issue convert: delegate failed `"ffmpeg" with mpeg

tennis <- load.image(system.file('extdata/tennis_sif.mpeg',package='imager'))
convert: delegate failed "ffmpeg" -nostdin -v -1 -i "%i" -vframes %S -vcodec pam -an -f rawvideo -y "%u.pam" 2> "%Z"' @ error/delegate.c/InvokeDelegate/1332. convert: unable to open image/var/tmp/magick-50575o_bXKN24kYIc.pam': No such file or directory @ error/blob.c/OpenBlob/2695.
convert: no images defined `pnm:-' @ error/convert.c/ConvertImageCommand/3230.
sh: gm: command not found
Error: [instance(0,0,0,0,0x0,non-shared)] CImg::load(): Failed to recognize format of file '/Users/kruny1001/Library/R/3.2/library/imager/extdata/tennis_sif.mpeg'.
play(tennis)
Error in play(tennis) : object 'tennis' not found

now filter in the time direction and pipe to play

deriche(tennis,10,axis="z") %>% play
Error in deriche(tennis, 10, axis = "z") : object 'tennis' not found

I can run png image with your sample code but I can't run the video with your example. What am I missing?

how to swapaxes?

Hi ,
how can I do the following transformation,swap axes to make image from (224, 224, 3) to (3, 224, 224)

  • python code:
    sample = np.swapaxes(sample, 0, 2)
    sample = np.swapaxes(sample, 1, 2)

the origin image is a 4D arrays,like (224.224.1.3). I want to change it to (1,3,244,244).

Overwrite axis in plot function

For displaying it might be nice to have empty labels, but

$ plot(boats, xlab="")

results in:
Error in plot.default(c(1, w), c(1, h), type = "n", xlab = "x", ylab = "y", :
formal argument "xlab" matched by multiple actual arguments

Documentation problems.

Hi there,
LOVE your package, working myself on image analysis in R. Just a few things I noticed in the documentation which I think are worth correcting.

  1. In the bucketfill() example, rather than filling in part of the sail, I get a completely pink image. Also I'm not sure how the sigma threshold works from reading the docs.

pinksail

  1. In common_pixsets there's a misspelt diamond (it says "diamong" instead).

Thanks,
Rory

Cannot replicate the CImg API example

Hello,

Great package! I am just struggling to replicate the following example given in the documentation:
`library(imager)
library(Rcpp)

Some C++ code as a character string

The function takes an image, applies blur and erode operations, and returns the result

foo.inline <- "
NumericVector foo(NumericVector inp)
{
CImg img = as<CImg >(inp);
img.blur(3).erode(4);
return wrap(img);
} "

Compile the function. The compiler may issue a number of warnings which you can all ignore

cppFunction(foo.inline,depends="imager")`

The last line gives me the following error:

g++ -m64 -I"/R-32~1.2/include" -DNDEBUG -I/R-3.2.2/library/Rcpp/include" -I"/R-3.2.2/library/imager/include" -I"/R-3.2.2/library/Rcpp/include" -I"/RCompile/r-compiling/local/local320/include" -O2 -Wall -mtune=core2 -c file275023be36bb.cpp -o file275023be36bb.o
In file included from *\rbuildtools\3.3\gcc-4.6.3\bin../lib/gcc/i686-w64-mingw32/4.6.3/../../../../i686-w64-mingw32/include/objbase.h:154:0,
from *\rbuildtools\3.3\gcc-4.6.3\bin../lib/gcc/i686-w64-mingw32/4.6.3/../../../../i686-w64-mingw32/include/ole2.h:16,
from *\rbuildtools\3.3\gcc-4.6.3\bin../lib/gcc/i686-w64-mingw32/4.6.3/../../../../i686-w64-mingw32/include/shlobj.h:86,
from */R-3.2.2/library/imager/include/CImg.h:171,
from */R-3.2.2/library/imager/include/imager.h:21,
from file275023be36bb.cpp:3:
*\rbuildtools\3.3\gcc-4.6.3\bin../lib/gcc/i686-w64-mingw32/4.6.3/../../../../i686-w64-mingw32/include/objidl.h:598:52: error: macro "Realloc" requires 3 arguments, but only 2 given
*\rbuildtools\3.3\gcc-4.6.3\bin../lib/gcc/i686-w64-mingw32/4.6.3/../../../../i686-w64-mingw32/include/objidl.h:598:56: error: ISO C++ forbids initialization of member 'Realloc' [-fpermissive]
*\rbuildtools\3.3\gcc-4.6.3\bin../lib/gcc/i686-w64-mingw32/4.6.3/../../../../i686-w64-mingw32/include/objidl.h:598:56: error: making 'Realloc' static [-fpermissive]
*\rbuildtools\3.3\gcc-4.6.3\bin../lib/gcc/i686-w64-mingw32/4.6.3/../../../../i686-w64-mingw32/include/objidl.h:598:56: error: invalid in-class initialization of static data member of non-integral type 'void
'
\rbuildtools\3.3\gcc-4.6.3\bin../lib/gcc/i686-w64-mingw32/4.6.3/../../../../i686-w64-mingw32/include/objidl.h:599:25: error: expected identifier before '(' token
*\rbuildtools\3.3\gcc-4.6.3\bin../lib/gcc/i686-w64-mingw32/4.6.3/../../../../i686-w64-mingw32/include/objidl.h:599:25: error: 'parameter' declared as function returning a function
*\rbuildtools\3.3\gcc-4.6.3\bin../lib/gcc/i686-w64-mingw32/4.6.3/../../../../i686-w64-mingw32/include/objidl.h:599:25: error: expected ')' before ',' token
In file included from *
\rbuildtools\3.3\gcc-4.6.3\bin../lib/gcc/i686-w64-mingw32/4.6.3/../../../../i686-w64-mingw32/include/msxml.h:209:0,
from \rbuildtools\3.3\gcc-4.6.3\bin../lib/gcc/i686-w64-mingw32/4.6.3/../../../../i686-w64-mingw32/include/urlmon.h:219,
from *\rbuildtools\3.3\gcc-4.6.3\bin../lib/gcc/i686-w64-mingw32/4.6.3/../../../../i686-w64-mingw32/include/objbase.h:348,
from *\rbuildtools\3.3\gcc-4.6.3\bin../lib/gcc/i686-w64-mingw32/4.6.3/../../../../i686-w64-mingw32/include/ole2.h:16,
from *\rbuildtools\3.3\gcc-4.6.3\bin../lib/gcc/i686-w64-mingw32/4.6.3/../../../../i686-w64-mingw32/include/shlobj.h:86,
from */R-3.2.2/library/imager/include/CImg.h:171,
from */R-3.2.2/library/imager/include/imager.h:21,
from file275023be36bb.cpp:3:
*\rbuildtools\3.3\gcc-4.6.3\bin../lib/gcc/i686-w64-mingw32/4.6.3/../../../../i686-w64-mingw32/include/oaidl.h:1890:28: error: expected identifier before '(' token
*\rbuildtools\3.3\gcc-4.6.3\bin../lib/gcc/i686-w64-mingw32/4.6.3/../../../../i686-w64-mingw32/include/oaidl.h:1890:28: error: 'parameter' declared as function returning a function
*\rbuildtools\3.3\gcc-4.6.3\bin../lib/gcc/i686-w64-mingw32/4.6.3/../../../../i686-w64-mingw32/include/oaidl.h:1890:28: error: expected ')' before ',' token
In file included from *
/R-3.2.2/library/imager/include/imager.h:21:0,
from file275023be36bb.cpp:3:
/R-3.2.2/library/imager/include/CImg.h: In function 'const char cimg_library::cimg::strbuffersize(UINT_PTR)':
/R-3.2.2/library/imager/include/CImg.h:56410:82: warning: format '%lu' expects argument of type 'long unsigned int', but argument 4 has type 'UINT_PTR {aka long long unsigned int}' [-Wformat]
In file included from *
/R-3.2.2/library/imager/include/imager.h:23:0,
from file275023be36bb.cpp:3:
/R-3.2.2/library/imager/include/wrappers.h: In function 'SEXPREC Rcpp::wrap(const T&) [with T = cimg_library::CImgList, SEXP = SEXPREC_]':
*/R-3.2.2/library/imager/include/wrappers.h:39:35: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
make: ** [file275023be36bb.o] Error 1
Warning message:
running command 'make -f "
/R-321.2/etc/x64/Makeconf" -f "_/R-321.2/share/make/winshlib.mk" SHLIB_LDFLAGS='$(SHLIB_CXXLDFLAGS)' SHLIB_LD='$(SHLIB_CXXLD)' SHLIB="sourceCpp_54.dll" WIN=64 TCLBIN=64 OBJECTS="file275023be36bb.o"' had status 2
Error in sourceCpp(code = code, env = env, rebuild = rebuild, showOutput = showOutput, :
Error 1 occurred building shared library.

I am using Imager 0.2 and Rcpp 0.12.1.

Thanks!,
Michel

Avoid blurring when doing imrotate; or apply a histogram

(feature request)

When I use imrotate, on a 28x28 pixel, greyscale image (actually MNIST data), it ends up more blurred. I.e. when I plot the before and after histogram, the after image has slightly lower peaks at the black and white extremes, and all the much smaller grey peaks in the middle have got a bit higher.

If I do 12 rotations of 30 degrees, I get a blurry blob. The ideal would be no information loss at all and to get back the exact pixels I started with. (I tried all three values for interpolation: 1 is more blurry, 2 is better, and 0 gives a weird "pulled apart" result.)

(BTW, I used crop.borders(after , nPix = (width(after)-width(before))/2) to sort out the size problem.)

Using imsharpen() after imrotate() was not successful.

IDEA 1: Be able to apply the histogram of another image, and it will brighten or dim pixels until it matches. I don't know how to write this, but the usage would be: after <- imApplyHisogram(after, before)

IDEA 2: Could there be a version of imrotate() that didn't change the image size, and didn't blur? (It feels like the fact that the image grows in size is related to the dilution of image brightness?)

P.S. I'm happy to provide test data, and my test rotation scripts, if there is interest.

Can imager collaborate with tcltk efficiently?

I'm trying interactive image thresholding with tcltk and imager.
But it's laggy when treating a big image.
This is because plot() is slow.

Can I use efficient plotting function such as display() with tcltk?

The source code of interactive image thresholding function is below.
Click "source code" to see the source code.
Thanks.

source code
library(tcltk2)
library(tkrplot)
library(imager)
threshold_interactive <- function(im, scale_im = 1, wait = TRUE) {
  if (!is.cimg(im)) {
    warning("Class of argument must be cimg.")
    return(NA)
  }
  if (spectrum(im) != 1) {
    warning("The image was converted to grayscale")
    im <- grayscale(im)
  }
  val_im <- as.data.frame(im)$value
  min_im <- min(val_im)
  max_im <- max(val_im)
  iniv <- (min_im + max_im) / 2
  win1 <- tktoplevel()
  win1.frame1 <- tk2frame(win1)
  im_tcl <- function(val) {
    return(function() plot(threshold(im, thr = val), main = "Binary Image", asp=1, axes=F))
  }
  win1.frame1.im <- tkrplot(win1.frame1, fun = im_tcl(iniv), hscale = scale_im, vscale = scale_im)
  hist_tcl <- function(val) {
    return({function() {
      hist(val_im, main = "Histogram of Original Image")
      abline(v = val, col = "red")
      }
    })
  }
  win1.frame1.hist <- tkrplot(win1.frame1, fun = hist_tcl(iniv), hscale = scale_im, vscale = scale_im)
  tkpack(win1.frame1.im, side = "left")
  tkpack(win1.frame1.hist, side = "left")
  tkpack(win1.frame1, side = "top")
   text_label <- "Threshold value: "
  win1.label <- tk2label(win1, text = sprintf("%s%f",text_label, iniv))
  tkpack(win1.label, side = "top", anchor = "c")
  win1.frame2 <- tk2frame(win1)
  sliderValue <- tclVar(iniv)
  command_slider <- function(...) {
    assign("sliderValue", sliderValue, inherits = TRUE)
 }
  temp_margin <- 0
  win1.frame2.slider <- tk2scale(win1.frame2, from = min_im - temp_margin, to = max_im + temp_margin, variable=sliderValue, orient="horizontal", length=200, command=command_slider)
  command_button <- function(...) {
    tkdestroy(win1)
  }
  win1.frame2.button <- tkbutton(win1.frame2, text = "OK", command = command_button)
  tkpack(win1.frame2.button, side = "right", anchor = "e", padx = 50)
  tkpack(win1.frame2.slider, side = "right")
  tkpack(win1.frame2, side =  "top")
  quitWaiting <- 0
  pre_sliderValue <- as.numeric(tclvalue(sliderValue))
  while (wait) {
    tryCatch({
      tkwm.state(win1) 
      },
      error = function(e) assign("quitWaiting", 1, inherits = TRUE)
    )  
    if (quitWaiting) break
    if (pre_sliderValue != as.numeric(tclvalue(sliderValue))) {
      tempSliderVal <- as.numeric(tclvalue(sliderValue))
      templabel <- sprintf("%s%f", text_label, tempSliderVal)
      tkconfigure(win1.label, text = templabel)
      tempim <- tkrplot(win1, fun = im_tcl(tempSliderVal), hscale = scale_im, vscale = scale_im)
      temphist <- tkrplot(win1, fun = hist_tcl(tempSliderVal), hscale = scale_im, vscale = scale_im)
      tkconfigure(win1.frame1.im, image = tempim$image)
      tkconfigure(win1.frame1.hist, image = temphist$image)
    }
    pre_sliderValue <- as.numeric(tclvalue(sliderValue))
  }
  val_res <- as.numeric(tclvalue(sliderValue))
  return(list(im = threshold(im, thr = val_res), val = val_res))
}

"TIFF" format images seem not to be properly converted

Here's an image example (file can be downloaded here):

> iminfo(image_path)

$name
[1] "19_433666_203692_1212017.tif"

$format
[1] "TIFF"

$width
[1] 256

$height
[1] 256

$size
[1] 327221

This is how the image normally looks (using imagemagick):

image

When running:

> load.image(image_path) %>% display()

I get:

image

I get the same result with plot().

When saving the image object back to tif with save. image() and opening with imagemagick i get the same result:

image

This is my sessionInfo()


R version 3.3.2 (2016-10-31)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.1 LTS

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=nl_NL.UTF-8       
 [4] LC_COLLATE=en_US.UTF-8     LC_MONETARY=nl_NL.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=nl_NL.UTF-8       LC_NAME=C                  LC_ADDRESS=C              
[10] LC_TELEPHONE=C             LC_MEASUREMENT=nl_NL.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] dplyr_0.5.0     purrr_0.2.2     readr_1.0.0     tidyr_0.6.1     tibble_1.2     
 [6] ggplot2_2.2.1   tidyverse_1.1.1 imager_0.31     magrittr_1.5    plyr_1.8.4     

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.9      forcats_0.2.0    tools_3.3.2      lubridate_1.6.0  jsonlite_1.2    
 [6] nlme_3.1-128     gtable_0.2.0     lattice_0.20-34  png_0.1-7        psych_1.6.12    
[11] DBI_0.5-1        parallel_3.3.2   haven_1.0.0      readbitmap_0.1-4 bmp_0.2         
[16] xml2_1.1.1       httr_1.2.1       stringr_1.1.0    hms_0.3          grid_3.3.2      
[21] R6_2.2.0         jpeg_0.1-8       readxl_0.1.1     foreign_0.8-67   modelr_0.1.0    
[26] reshape2_1.4.2   scales_0.4.1     rvest_0.3.2      assertthat_0.1   mnormt_1.5-5    
[31] colorspace_1.3-2 stringi_1.1.2    lazyeval_0.2.0   munsell_0.4.3    broom_0.4.2    

Switch off anti-aliasing?

When plotting small images, the anti-alias effect is sometimes undesirable. With 5x5 pixel images it is quite extreme: I want to see the individual pixels, and cannot!
Is there anyway to turn this off, or is it being done by R processes underneath the Imager library?

More detailed imsharpen docs

For these three, the default values are 1, 0, 0, and the descriptions are:
edge: Edge threshold (shock filters only).
alpha: Gradient smoothness (shock filters only).
sigma: Tensor smoothness (shock filters only).

It gives no description on the possible ranges (are they 0.0 to 1.0, or 0 to 255?), or values that might be successful for different applications. So far I've only found this, suggesting sigma values of 0.0, 0.5, 1.0, 2.0 or 5.0. (I assume higher meaning more smoothing?) http://www.halcon.com/download/reference/shock_filter.html But no hints for edge or alpha.

BTW, the sharpen_type argument would be more R-like if it was a string parameter: "diffusion" vs. "shock", or something like that. If keeping it as a bool, it might be better to rename it as use_shock_filters ?

Loss of detail when loading an image using imager

I am trying to load an image that consist of a gridded pattern of about 1"X1" lines that are about 50 microns thick. I seem to lose the line detail when loading the image using imager. The lines are pronounced in the image but not after I load it into R. Any ideas or suggestions are welcomed.

Regards

installation problem

Get an error in dyn.load(file, DLLpath = DLLpath, ...) on 2 Macs with OS X El Capitan. The file seems to exist.

kann shared object '/Library/Frameworks/R.framework/Versions/3.3/Resources/library/imager/libs/imager.so' nicht laden:
dlopen(/Library/Frameworks/R.framework/Versions/3.3/Resources/library/imager/libs/imager.so, 6): Library not loaded: /opt/X11/lib/libX11.6.dylib
Referenced from: /Library/Frameworks/R.framework/Versions/3.3/Resources/library/imager/libs/imager.so

apply over multiple images

Is there a faster way to do the following calculation?

library(imager)
pics = imlist(boats, boats, boats)
for(i in seq_along(pics)) {
  pics[[i]] = implot(pics[[i]], {text(sample(0:250, size = 3), sample(0:350, size = 3), "NOISE", cex=3, col = "red")})
}
plot(pics)
pics = imappend(pics, "z")
res = apply(X = pics, FUN = median, MARGIN = c(1:2,4))
plot(as.cimg(res))

The apply is quite slow, it there a faster way?

btw: Thanks for the package and the comprehensive documentation.

as.data.frame on image lists

Hi,
I'm having trouble applying as.data.frame to image lists such as the one returned by imgradient("xy"):

> gr <- imgradient(grayscale(boats),"xy")
> range(as.data.frame(gr[['x']])$x)
[1]   1 256
> range(as.data.frame(gr)$x)
[1] -0.5  0.5
Warning messages:
1: In if (standardise) { :
  the condition has length > 1 and only the first element will be used
2: In if (standardise) { :
  the condition has length > 1 and only the first element will be used

On a single image, as.data.frame maintains the original coordinates of the boats image.
However, on an image list, as.data.frame produces the above warning and updates the x,y tuples

I'm not sure if the rescale is intended but this has practical consequences: for example the Plotting a gradient field code relies on x and y being integers:

##Subsample: take every fourth pixel
dgr.sub <- dplyr::filter(dgr,(x %% 4) ==0,(y %% 4) == 0)

Sorry if I'm missing something and thanks for the amazing package!

> packageVersion("imager")
[1] '0.40.2'

suggestion on save.image function name

I know this is a detail, but in projects I tend to use both imager::save.image() and base::save.image(), and I often end up writing only save.image() when the function I actually want is the masked one. Is it necessary to mask save.image() or would changing the function names to something like image.save() and image.load() be a good idea?

Loop problems

Hi guys,

Just wanted to let you know that I tried using the load.image and save.image functions in a loop and it looks like they are completely unusable. I noticed that your package is unstable when using "load.image", and "save.image" inside a loop in RStudio in Windows 7. The loop takes an array from a loaded image (using load.image) randomly samples row and column index sequences that represent a smaller tile of that image and are valid, then subsets the array by using imagearray[xsequence,ysequence,,drop = FALSE) and attempts to write the resulting array as a png using "save.image". This causes one image tile (the first one created) to be written repeatedly regardless of the values of xsequence and ysequence that are being used to subset the matrix. I've verified that the xsequence and ysequence are being modified by the loop correctly by printing them right next to the line that subsets the image matrix and saves it. I've also used a different package (png) and this package has no similar issue in my code.

Deep learning with imager error (deprecation in Dec 2015)

https://www.r-bloggers.com/deep-learning-with-mxnetr/

In the classify real-world images with pre-trained model portion of this website, part of the code no longer works. This is due to the fact that imager was deprecated in December 2015 which somehow affected the API. There is supposedly a fix for this code, but I can't find it anywhere online. Can anyone help?

Specifically, I get the following messages:

model <- mx.model.load("Inception/Inception_BN", iteration=39)
[08:32:51] d:\chhong\mxnet\src\operator./softmax_output-inl.h:292: Softmax symbol is renamed to SoftmaxOutput. This API will be deprecated in Dec, 2015

normed <- preproc.image(im, mean.img)
Error: Expecting a four-dimensional array

Thanks!

NA support

  • Add na.rm option to parsd, parvar.
  • Check CImg functions for NA safety
    So far, functions that should be NA-safe but aren't: boxblur, median, medianblur

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.