将RGB十六进制转换为R中的3d矩阵
Convert RGB hexadecimal to 3d matrix in R
我有一个RGB图像,任何单元格都是一个特征值,如“#FFFFFF”。
我想将这种格式转换为 3D 矩阵并将其用于图像处理,不幸的是我现在不知道该怎么做。
让我们使用颜色“#8A2BE2”:
# Create a 4x4 matrix with the same color
hex <- matrix(rep("#8A2BE2", 16), 4, 4)
hex
# [,1] [,2] [,3] [,4]
# [1,] "#8A2BE2" "#8A2BE2" "#8A2BE2" "#8A2BE2"
# [2,] "#8A2BE2" "#8A2BE2" "#8A2BE2" "#8A2BE2"
# [3,] "#8A2BE2" "#8A2BE2" "#8A2BE2" "#8A2BE2"
# [4,] "#8A2BE2" "#8A2BE2" "#8A2BE2" "#8A2BE2"
rgbs <- col2rgb(hex)
# First 5 columns
# [,1] [,2] [,3] [,4] [,5]
# red 138 138 138 138 138
# green 43 43 43 43 43
# blue 226 226 226 226 226
rgbs <- array(t(rgbs), c(4,4,3))
dim(rgbs)
# we get a 4x4x3 array
# [1] 4 4 3
rgbs[1:2,1:2,]
# First 2 lines and first 2 columns
# , , 1
#
# [,1] [,2]
# [1,] 138 138
# [2,] 138 138
#
# , , 2
#
# [,1] [,2]
# [1,] 43 43
# [2,] 43 43
#
# , , 3
#
# [,1] [,2]
# [1,] 226 226
# [2,] 226 226
我有一个RGB图像,任何单元格都是一个特征值,如“#FFFFFF”。 我想将这种格式转换为 3D 矩阵并将其用于图像处理,不幸的是我现在不知道该怎么做。
让我们使用颜色“#8A2BE2”:
# Create a 4x4 matrix with the same color
hex <- matrix(rep("#8A2BE2", 16), 4, 4)
hex
# [,1] [,2] [,3] [,4]
# [1,] "#8A2BE2" "#8A2BE2" "#8A2BE2" "#8A2BE2"
# [2,] "#8A2BE2" "#8A2BE2" "#8A2BE2" "#8A2BE2"
# [3,] "#8A2BE2" "#8A2BE2" "#8A2BE2" "#8A2BE2"
# [4,] "#8A2BE2" "#8A2BE2" "#8A2BE2" "#8A2BE2"
rgbs <- col2rgb(hex)
# First 5 columns
# [,1] [,2] [,3] [,4] [,5]
# red 138 138 138 138 138
# green 43 43 43 43 43
# blue 226 226 226 226 226
rgbs <- array(t(rgbs), c(4,4,3))
dim(rgbs)
# we get a 4x4x3 array
# [1] 4 4 3
rgbs[1:2,1:2,]
# First 2 lines and first 2 columns
# , , 1
#
# [,1] [,2]
# [1,] 138 138
# [2,] 138 138
#
# , , 2
#
# [,1] [,2]
# [1,] 43 43
# [2,] 43 43
#
# , , 3
#
# [,1] [,2]
# [1,] 226 226
# [2,] 226 226