用R製作漸變背景圖片

library(jpeg)
## 先用barplot函數產生一張JPG圖片,默認背景爲白色
img <- "result.jpg"
jpeg(img, width = 300, height = 300)
barplot(sample(1:100, 10))
dev.off()
## 讀取圖片
x <- readJPEG(img)
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)]
## 原背景色,這裏取白色
bg <- as.vector(col2rgb("white")/255)
tv <- 0.1
sel <- abs(r - bg[1]) < tv & abs(g - bg[2]) < tv & abs(b - bg[3]) < tv
## 替換背景
bg <- matrix(cm.colors(n), ncol = dimx[1])
bgx <- t(sapply(bg, col2rgb, USE.NAMES = F))/255
r[sel] <- bgx[sel, 1]
g[sel] <- bgx[sel, 2]
b[sel] <- bgx[sel, 3]
x <- array(c(r, g, b), dim = dimx)
writeJPEG(x, "result1.jpg")
## 旋轉背景顏色矩陣,改變顏色方向
bg <- t(bg)
bgx <- t(sapply(bg, col2rgb, USE.NAMES = F))/255
r[sel] <- bgx[sel, 1]
g[sel] <- bgx[sel, 2]
b[sel] <- bgx[sel, 3]
x <- array(c(r, g, b), dim = dimx)
writeJPEG(x, "result2.jpg")
## 對角線漸變
ndx1 <- expand.grid(1:dimx[1], 1:dimx[2])
ndx1 <- ndx1[, 1] + ndx1[, 2]
ndx2 <- sort(unique(ndx1))
ndx <- ndx1
for (i in 1:length(ndx2)) ndx[ndx1 == ndx2[i]] <- i
bg <- cm.colors(length(ndx2))
bg <- bg[ndx]
bgx <- t(sapply(bg, col2rgb, USE.NAMES = F))/255
r[sel] <- bgx[sel, 1]
g[sel] <- bgx[sel, 2]
b[sel] <- bgx[sel, 3]
x <- array(c(r, g, b), dim = dimx)
writeJPEG(x, "result3.jpg")


文章來源:測序幫


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章