How to remove background of images with the magick package?

瘦欲@ 提交于 2019-12-24 08:35:34

问题


Is it possible to remove the background of images with the magick package?

I know how to use edge detection with Gimp/Inkscape to crop out silhouettes; however, I'm looking to automate the process for a large batch of images with R.

My ultimate goal is to use the ggimage package to plot these images as x,y coordinates but the background of these images is currently overlapping the plot (the dog compared to fink)

library("ggplot2")
library("ggimage")

set.seed(2017-02-21)
d <- data.frame(x = rnorm(10),
                y = rnorm(10),
                image = sample(c("http://www.supercoloring.com/sites/default/files/silhouettes/2015/05/cairn-terrier-black-silhouette.svg", "https://jeroenooms.github.io/images/frink.png"),
                               size=10, replace = TRUE)
                )

ggplot(d, aes(x, y)) + geom_image(aes(image=image))

One can trim the edges of an image using image magick's image_trim()

img <- image_read_svg("http://www.supercoloring.com/sites/default/files/silhouettes/2015/05/cairn-terrier-black-silhouette.svg")
image_trim(img)

but this isn't exactly what I would like.

Any ideas?


回答1:


The image_transparent() function does this, e.g.:

logo <- image_read("logo:")
image_transparent(logo, 'white')

The white parts of the image will be made transparent, which should be enough for the simple image in your example.




回答2:


see my answer in https://yulab-smu.github.io/treedata-book/image-processing-using-magick-package.html#example-1-remove-background-of-images.

You can pass image processing function provided by magick package to geom_image via the image_fun parameter.



来源:https://stackoverflow.com/questions/50479875/how-to-remove-background-of-images-with-the-magick-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!