简体   繁体   English

优化 numpy ndarray 到字符串的转换

[英]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.我目前正在做一个 python 程序,将图像转换为十六进制字符串,反之亦然。 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.我需要两个函数,一个获取图像并返回对应于每个像素的 RGB 值的十六进制字符串,另一个 function 获取一个十六进制字符串,两个整数,并生成与该十六进制字符串对应的大小的可见图像.

I currently use imageio to get an RGB matrix from the image and then convert that to hex.我目前使用 imageio 从图像中获取 RGB 矩阵,然后将其转换为十六进制。 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.我正在尝试将图像优化为字节部分,因为 918 x 575 像素的 442KB 图像大约需要 2.5 秒。

How could I make it quicker?我怎样才能让它更快?

Here's the code:这是代码:

def rgb2hex(rgb):

    """
    convert a list or tuple of RGB values
    to a string in hex
    """

    r,g,b = rgb
    return '{:02x}{:02x}{:02x}'.format(r, g, b)


def arrayToString(array):
    """
    convert an array to a string
    """

    string = ""
    for element in array:
        string += str(element)

    return string


def sliceStr(string,sliceLenght):
    """
    slice a string in chunks of sliceLenght lenght
    """

    string = str(string)
    array = np.array([string[i:i+sliceLenght] for i in range(0,len(string),sliceLenght)])
    return array



def hexToRGB(hexadecimal):
    """
    convert a hex string to an array of RGB values
    """
    h = hexadecimal.lstrip('#')
    if len(h)!=6:
        return
    return [int(h[i:i+2], 16) for i in (0, 2, 4)]

def ImageToBytes(image):
    """
    Image to convert from image to bytes
    """
    dataToEncrypt =imageio.imread(image)

    if dataToEncrypt.shape[2] ==4:
        dataToEncrypt = np.delete(dataToEncrypt,3,2)

    originalRows, originalColumns,_ = dataToEncrypt.shape


    #converting rgb to hex
    hexVal = np.apply_along_axis(rgb2hex, 2, dataToEncrypt)
    hexVal = np.apply_along_axis(arrayToString, 1, hexVal)
    hexVal = str(np.apply_along_axis(arrayToString, 0, hexVal))

    byteImage = bytes.fromhex(hexVal)

    return (byteImage, [originalRows,originalColumns])

One simple approach is to use tobytes on the numpy array.一种简单的方法是在 numpy 数组上使用tobytes Eg,例如,

image = imageio.imread(filename)
# Drop the alpha channel.
if image.shape[2] == 4:
    image = image[..., :3]
# Convert to bytes directly.
byte_image = image.tobytes()

On my machine, this gives a 250x speed up compared with converting to strings first.在我的机器上,与首先转换为字符串相比,这提供了 250 倍的速度。 Note: this will only work if the dtype of the array is uint8 .注意:这仅在数组的 dtype 为uint8时有效。 But that's luckily the default provided by imread .但幸运的是,这是imread提供的默认设置。

This should be more faster due to less conversions由于转换次数较少,这应该会更快

def ImageToBytes2(image):
    """
    Image to convert from image to bytes
    """
    dataToEncrypt =imageio.imread(image)

    if dataToEncrypt.shape[2] ==4:
        dataToEncrypt = np.delete(dataToEncrypt,3,2)

    originalRows, originalColumns,_ = dataToEncrypt.shape

    dataToEncrypt = dataToEncrypt.reshape(1,originalRows*originalColumns*3)

    #converting rgb to hex
    byteImage = bytes(dataToEncrypt)

    return (byteImage, [originalRows,originalColumns])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM