我有一個單幀灰度圖像。我想修改圖像,以便某個值的所有像素變成彩色的,例如紅色。很顯然,我需要將圖像轉換爲3幀圖像。 爲了方便起見,我使用包EBImage,但只使用基本包的簡單代碼會很好。將顏色元素添加到單幀灰度圖像
mat = round(matrix(runif(100), ncol = 5), digits = 1)
mat
[,1] [,2] [,3] [,4] [,5]
[1,] 0.1 0.2 0.6 0.1 0.8
[2,] 0.1 0.3 0.4 0.5 0.6
[3,] 0.6 0.3 0.8 0.8 0.5
[4,] 0.5 0.9 0.7 0.3 0.2
[5,] 0.7 0.7 0.9 0.3 0.2
[6,] 0.6 1.0 0.4 0.7 0.3
[7,] 0.7 0.6 0.5 0.8 0.5
[8,] 0.4 0.8 0.2 0.2 0.1
[9,] 0.2 0.1 0.4 0.9 0.6
[10,] 0.7 0.3 0.2 0.3 0.8
[11,] 0.8 1.0 0.4 0.8 0.3
[12,] 0.8 1.0 0.5 0.8 0.7
[13,] 0.6 0.5 0.9 0.9 0.1
[14,] 1.0 0.5 0.6 0.0 0.3
[15,] 0.1 0.5 0.6 0.6 0.2
[16,] 0.2 0.8 0.2 0.5 0.2
[17,] 0.9 0.9 0.4 0.7 0.1
[18,] 0.3 0.7 0.9 0.7 0.4
[19,] 1.0 0.0 0.5 0.0 1.0
[20,] 0.2 0.3 0.9 0.3 0.6
matgray = 255*mat
mat_rgb = channel(matgray, 'rgb') ## using EBImage package
dim(mat_rgb)
[1] 20 5 3
mat_red = channel(mat_rgb, 'asred')
# To generate and save gray image from gray matrix
par(mar = c(0,0,0,0))
png(filename = paste("Image.png"), res=1)
image(mat_red, axes = FALSE)
dev.off()
當我去保存圖像,它說Missing frame index for an image stack, assuming 'i = 1'
,並且圖像確實沒有表現出任何紅色...感謝您的幫助!
謝謝你,這看起來不錯。但我不確定這是我想要做的。您建議您在保持明暗對比的同時將所有像素以紅色着色。我想要的是保持大多數像素的灰度,並將灰度值爲0的所有像素都改爲紅色。結果將是灰度圖像,只有少量紅色像素在其中漂浮 – Gabriel123
感謝您的澄清,我已經相應地更新了我的答案。 – aoles
謝謝你oales,那很好用:-) – Gabriel123