【问题标题】:Convert RGB to hexadecimal colors from image and keep image dimensions将图像中的 RGB 转换为十六进制颜色并保持图像尺寸
【发布时间】:2018-08-24 07:14:52
【问题描述】:

我想将 2000x2000 像素 RGB 图像(具有三个分离通道的数组)中的颜色转换为一个通道,对应于十六进制颜色。我还想同时保留图像的尺寸,以便找到每个像素的确切十六进制颜色。然后目标是找到包含特定颜色的所有像素的位置。

让我们以这个可重现的例子为例:

    # A 3x3 pixels image 

    img <- array(runif(3,0,1), dim = c(3L, 3L, 3L))

    # The result I would expect (a unique matrix of hexadecimal values,
    # corresponding to the conversion and the merging of the RGB values)

    img_output <-matrix(c("#B1F5E1","#95E4EE","#A5EDD8","#517760",
    "#A1E2C7","#00FFFF","#A9EFDB","#A9EFC4","#73CEE6"),nrow=3,ncol=3)

    # In order then to find the position of specific color pixels in
    # my image

    which(img_output=="#95E4EE", arr.ind=TRUE)

目前,我已经有了将 RGB 颜色转换为十六进制的功能,但它返回了一个字符向量:

library(colorspace)
img_output <- hex(RGB(c(img[,,1]),c(img[,,2]),c(img[,,3])))

我该怎么做?

【问题讨论】:

    标签: r image hex rgb pixels


    【解决方案1】:

    为了让这一点更容易看到,我使用数据框而不是数组来使正在发生的事情更加明显。

    #Creating Data Frame of red, green and blue values 0-1 labeled
    img <- data.frame(R= runif(100,0,1),G = runif(100,0,1), B = runif(100,0,1))
    
    #you can use apply also, but wanted to show how it is dropping each
    # row into the 'rgb' command.
    for (ro in 1:nrow(img)){
      img$hex[ro] <-rgb(img[ro,'R'], img[ro, 'G'], img[ro, 'B'], max=1)
    }
    

    我们的输出:

                   R         G           B   hex
          0.23948334 0.4673375 0.479445200 #3D777A
          0.03930279 0.4029776 0.092679483 #0A6718
          0.93748689 0.6637624 0.900167870 #EFA9E6
          0.46137007 0.9688970 0.001738671 #76F700
          0.31737616 0.3566998 0.675646818 #515BAC
          0.62523116 0.3513590 0.035781224 #9F5A09
    

    你也可以对 0 到 255 的值做同样的事情:

    img <- data.frame(R= as.numeric(sample(0:255, 100)),G = as.numeric(sample(0:255, 100)), B = as.numeric(sample(0:255, 100)))
    for (ro in 1:nrow(img)){
      img$hex[ro] <-rgb(img[ro,'R'], img[ro, 'G'], img[ro, 'B'], max=255)
    }
    

    输出:

        R   G   B     hex
       175 147 202  #AF93CA
       124  90 183  #7C5AB7
       221 149 110  #DD956E
         0 186  23  #00BA17
        42  37 227  #2A25E3
        31   8 101  #1F0865
    

    您可以通过设置max= 来控制各个色彩空间的参数,以适应您的 r、g、b 值在原始数据中的显示方式。

    【讨论】:

      猜你喜欢
      • 2016-09-20
      • 2012-07-25
      • 2014-09-19
      • 2020-07-15
      • 1970-01-01
      • 2016-12-27
      • 2012-11-01
      • 2022-08-10
      • 1970-01-01
      相关资源
      最近更新 更多