numpy image arrays: how to efficiently switch from rgb to hex

  • Last Update :
  • Techknowledgy :

Using beaker's idea, you can also eliminate the double for-loop:

def tohex(array):
   array = np.asarray(array, dtype = 'uint32')
return ((array[: ,: , 0] << 16) + (array[: ,: , 1] << 8) + array[: ,: , 2])

String operations are probably pretty slow. A direct mathematical approach would be:

array[v, u] = ((array[v, u, 0] << 16) + (array[v, u, 1] << 8) + array[v, u, 2])

This combines the 3 bytes of the RGB representation into a single int:

>>> A = [123, 255, 255] >>>
   B = (A[0] << 16) + (A[1] << 8) + A[2] >>>
   B
8126463
   >>>
   hex(B)
'0x7bffff'

Not sure if this is much faster, but you could do something like this:

hexarr = np.vectorize('{:02x}'.format)

And then run it on an RGB array:

In[67]: a = (np.random.rand(2, 5, 3) * 255).astype('u1')

In[68]: a
Out[68]:
   array([
      [
         [149, 145, 203],
         [210, 234, 219],
         [223, 50, 26],
         [166, 34, 65],
         [213, 78, 115]
      ],

      [
         [191, 54, 168],
         [85, 235, 36],
         [180, 140, 96],
         [127, 21, 24],
         [166, 210, 128]
      ]
   ], dtype = uint8)

In[69]: hexarr(a)
Out[69]:
   array([
         [
            ['95', '91', 'cb'],
            ['d2', 'ea', 'db'],
            ['df', '32', '1a'],
            ['a6', '22', '41'],
            ['d5', '4e', '73']
         ],

         [
            ['bf', '36', 'a8'],
            ['55', 'eb', '24'],
            ['b4', '8c', '60'],
            ['7f', '15', '18'],
            ['a6', 'd2', '80']
         ]
      ],
      dtype = '|S2')

You can collapse the third dimension with view:

In[71]: hexarr(a).view('S6')
Out[71]:
   array([
         [
            ['9591cb'],
            ['d2eadb'],
            ['df321a'],
            ['a62241'],
            ['d54e73']
         ],

         [
            ['bf36a8'],
            ['55eb24'],
            ['b48c60'],
            ['7f1518'],
            ['a6d280']
         ]
      ],
      dtype = '|S6')

Suggestion : 2

We will use the following approach to convert hex color codes into RGB format:,Now, let’s see how we can convert the RGB values to their hex representation.,In line 1, we define the rgb_to_hex() function that accepts three RGB values.

def hex_to_rgb(hex):
   rgb = []
for i in (0, 2, 4):
   decimal = int(hex[i: i + 2], 16)
rgb.append(decimal)

return tuple(rgb)

print(hex_to_rgb('FFA501'))
def rgb_to_hex(r, g, b):
   return ('{:X}{:X}{:X}').format(r, g, b)

print(rgb_to_hex(255, 165, 1))

Suggestion : 3

Convert RGB color values to YCbCr color space,Import, Export, and Conversion,RGB color values to convert, specified as a numeric array in one of these formats.,Understanding Color Spaces and Color Space Conversion

RGB = imread('board.tif');
YCBCR = rgb2ycbcr(RGB);
figure
imshow(RGB);
title('Image in RGB Color Space');
figure
imshow(YCBCR);
title('Image in YCbCr Color Space');
[I, map] = imread('forest.tif');
newmap = rgb2ycbcr(map);

Suggestion : 4

Last Updated : 01 Aug, 2022

1._
Input: r, g, b = 45, 215, 0
Output:
   h, s, v = 107.44186046511628, 100.0, 84.31372549019608

Input: r, g, v = 31, 52, 29
Output:
   h, s, v = 114.78260869565217, 44.230769230769226, 20.392156862745097

Output : 

(30.0, 63.56589147286821, 50.588235294117645)

Suggestion : 5

An intuitive way to convert a color image 3D array to a grayscale 2D array is, for each pixel, take the average of the red, green, and blue pixel values to get the grayscale value. This combines the lightness or luminance contributed by each color band into a reasonable gray approximation. , Color images are represented as three-dimensional Numpy arrays - a collection of three two-dimensional arrays, one each for red, green, and blue channels. Each one, like grayscale arrays, has one value per pixel and their ranges are identical. , There is lightening throughout the image after accounting for gamma compression. It brings the luminance up to be a closer match to that of the original image. Finally, we have a high quality grayscale representation. , The axis=2 argument tells numpy.mean() to average values across all three color channels. (axis=0 would average across pixel rows and axis=1 would average across pixel columns.)

from PIL
import Image
import numpy as np
color_img = np.asarray(Image.open(img_filename)) / 255