JPG/JPEG图像背景是不能透明的,但PNG图像可以。代码如下,应用前提是背景和徽标色能较好地区分(稍修改也可以做背景色替换):
- library(jpeg)
- library(png)
- FILTER <- matrix(c("JPG file", "*.jpg", "JPEG file", "*.jpeg"), ncol = 2, byrow = T)
- img <- choose.files(caption = "Select JPG files", filters = FILTER, index = 1, multi=T)
- for(i in 1:length(img)){
- x <- readJPEG(img[i])
- dimx <- dim(x)
- n <- dimx[1]*dimx[2]
- r <- x[1:n]
- g <- x[(n+1):(2*n)]
- b <- x[(2*n+1):(3*n)]
- ps <- 5; ps <- dimx[1]*(ps-1) + ps # 背景取值,ps为左上到右下角的像素,5。按情况修改
- tv <- 0.1 # tv为容差范围,0-1取值,越小越精确
- sel <- abs(r-r[ps])<tv & abs(g-g[ps])<tv & abs(b-b[ps])<tv
- alpha <- rep(1, n)
- alpha[sel] <- 0
- x <- array(c(x, alpha), dim=c(dimx[1:2], 4))
- writePNG(x, gsub("(.+\\.)(jpg|jpeg)$","\\1png", img[i], ignore.case = TRUE))
- }
- winDialog("ok", "Work done!")
下面是几张网站徽标截图进行透明处理后在幻灯片中的叠加效果: