I am exploring NumPy version of struct.pack and struct.unpack. My particular problem is converting an RGB value (r, g, b) into a binary.
For example:
f = lambda r, g, b: struct.unpack('I', struct.pack('BBBB', r, g, b, 255))[0]
f(155, 156, 148)
#--> 4287929499
When I apply this conversion to an image (2-d array of RGB), it becomes very slow.
For example:
import numpy as np
import struct
img_rgb = np.random.randint(0, 256, (480, 640, 3))
%%time
np.apply_along_axis(lambda rgb: struct.unpack('I', struct.pack('BBBB', rgb[0], rgb[1], rgb[2], 255))[0], 2, img_rgb)
#--> Wall time: 5.23 s
My question is that is there NumPy version of struct.pack and struct.unpack? Or, how can I make this code faster with NumPy?