Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy Image Arrays: How to efficiently switch from RGB to Hex

I have been using nested for loops to turn RGB images into an image array of Hex values, but it is too slow for large images. Does anyone know a quick way and or a library that can help me switch back and from RGB to HEX?

edit: @ragingSloth

This is what I came up with but it is too slow for what I need:

def rgb_to_hex(array):
    (x, y, z) = array.shape
    for v in range(0, x):
        for u in range(0, y):
            array[v, u] = int('%02x%02x%02x' % (array[v, u, 0], array[v, u, 1], array[v, u, 2]))
like image 276
user2909415 Avatar asked Dec 01 '25 21:12

user2909415


1 Answers

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])
like image 82
unutbu Avatar answered Dec 04 '25 13:12

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!