我目前正在做一個 python 程式,將影像轉換為十六進制字串,反之亦然。我需要兩個函式,一個獲取影像并回傳對應于每個像素的 RGB 值的十六進制字串,另一個函式獲取一個十六進制字串,兩個整數,并生成與該十六進制字串對應的大小的可見影像.
我目前使用 imageio 從影像中獲取 RGB 矩陣,然后將其轉換為十六進制。這個速度很快,對于 918 x 575 像素的 442KB 影像大約需要 2.5 秒。
為了從字串中獲取影像,我將其轉換為十六進制值矩陣,然后將其轉換為 RGB 以使用 imageio 創建影像。這是出現問題的地方,因為對與相同 918 x 575 影像對應的字串執行處理需要 36 秒。
我怎樣才能讓它更快?
這是代碼:
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])
def BytesToImage(byteToConvert,originalRows,originalColumns,name):
"""
Convert from Bytes to Image
"""
Data = byteToConvert.hex()
stepOne = sliceStr(Data,originalColumns*6)
stepTwo = []
for i in stepOne:
step = sliceStr(i,6)
#Add lost pixels
while len(step) != originalColumns:
step = np.append(step,"ffffff")
stepTwo.append(step)
stepThree = []
for i in stepTwo:
d = []
for j in i:
d.append(hexToRGB(j))
if len(stepThree) < originalRows:
stepThree.append(d)
Img = np.asarray(stepThree)
imageio.imwrite(name,Img)
uj5u.com熱心網友回復:
洗掉此行中不正確的縮進:
Img = np.asarray(stepThree)
它在 for 回圈內,不應該
此外,代碼正在進行從位元組到字串到 int 的必要轉換,而不是直接將位元組轉換為 int,請考慮更改為以下更短更快的代碼
def BytesToImage2(byteToConvert,originalRows,originalColumns,name):
"""
Convert from Bytes to Image
"""
ia=[]
for i in range(0,len(byteToConvert),originalColumns*3):
row=[[y for y in x] for x in [byteToConvert[j:j 3] for j in range(i,i originalColumns*3,3)]]
ia.append(row)
Img = np.asarray(ia)
imageio.imwrite(name,Img)
uj5u.com熱心網友回復:
如果你的位元組長度是合規的,下面的代碼應該是最快的方法,它比 918 * 575 影像上的串列理解快 500k 倍(忽略 的時間imwrite):
def BytesToImage(byteToConvert, originalRows, originalColumns, name):
img = np.frombuffer(byteToConvert, np.uint8).reshape(originalRows, originalColumns, 3)
imageio.imwrite(name, img)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/537280.html
標籤:Pythonpython-3.x麻木的蟒蛇-imageio
