Skip to content
Advertisement

Optimize conversion of numpy ndarray to string

I am currently doing a python program to convert from image to hex string and the other way around. I need two functions, one that takes an image and returns a hex string that corresponds to the RGB values of each pixel, and another function that takes a hex string, two ints, and generates a visible image of that size corresponding to that hex string.

I currently use imageio to get an RGB matrix from the image and then convert that to hex. I’m trying to optimize the Image to bytes part, as it takes around 2.5 seconds for a 442KB image of 918 x 575 pixels.

How could I make it quicker?

Here’s the code:

JavaScript

Advertisement

Answer

One simple approach is to use tobytes on the numpy array. E.g.,

JavaScript

On my machine, this gives a 250x speed up compared with converting to strings first. Note: this will only work if the dtype of the array is uint8. But that’s luckily the default provided by imread.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement