在Python中从TCP客户端获取字符串后,加快从Byte-String到Image的转换

时间:2017-04-16 21:53:35

标签: python string image opencv numpy

我有一个客户端从TCP客户端的TCP服务器接收图像。

在此之后,Image被序列化,当然还有字节。现在我想重新塑造一个图像。

然而,我的过程需要很长时间,所以我想知道是否有更多的pythonic,更快的方式呢?

每个步骤都会对代码进行注释,但这里是:

1.将它从十六进制二进制表示转换为可读字符串(0.002秒)

2.在每个字节耦合(0.08 s)后分离字符串

3.将列表的每个值转换为整数(0.17 s)

4.Reshape为红色,绿色,蓝色(0.02)的矩阵表示

5.Reshape Matrices一起形成图像

在查看时间后,我发现第3步的时间最多。

#....Some TCP stuff before, and this code is in a loop:
#Convert from hex binary to string
asstr = binascii.hexlify(data)
#Split up after each byte couple
n = 2
split = [asstr[i:i+n] for i in range(0, len(asstr), n)]
#Convert each byte couple to integer from its hex representation    
asint = [];
for i in split:    
    asint.append(int(i,16))   

#Reshape into red,green and blue
try:
    red = np.asarray(asint[::3]).reshape(240,424);
    green = np.asarray(asint[1::3]).reshape(240,424);
    blue = np.asarray(asint[2::3]).reshape(240,424);
except ValueError:
    continue;

#Reshape into an Image representation for opencv
img = np.transpose(np.asarray([red,green,blue],dtype=np.uint8),axes=(1, 2, 0))

#Show image
cv2.imshow('something',img)
if cv2.waitKey(1) & 0xFF == ord('q'):
    break

如果我打印出数据,我会在命令行中找到一些“ascii-crap”,这些只是ascii中数字的表示。 在使用binascci.hexlify(data)对其进行解码并将其打印出来后,我将值设为一个巨大的字符串,如“0112311a3b2b1c312...”(仅作为示例)

1 个答案:

答案 0 :(得分:1)

你确定你没有把事情变得比必要的更复杂吗?也许我错过了一些东西,但是如果使用正确长度的模拟bytes对象,我会在一行中获得与五步法相同的输出:

import numpy as np
import binascii

def the_humourless_route(data):
    return np.frombuffer(data, dtype=np.uint8).reshape(240, 424, 3)

def the_scenic_route(data):
    #....Some TCP stuff before, and this code is in a loop:
    #Convert from hex binary to string
    asstr = binascii.hexlify(data)
    #Split up after each byte couple
    n = 2
    split = [asstr[i:i+n] for i in range(0, len(asstr), n)]
    #Convert each byte couple to integer from its hex representation    
    asint = [];
    for i in split:    
        asint.append(int(i,16))   

    #Reshape into red,green and blue
    try:
        red = np.asarray(asint[::3]).reshape(240,424);
        green = np.asarray(asint[1::3]).reshape(240,424);
        blue = np.asarray(asint[2::3]).reshape(240,424);
    except ValueError:
        pass

    #Reshape into an Image representation for opencv
    img = np.transpose(np.asarray([red,green,blue],dtype=np.uint8),axes=(1, 2, 0))
    return img

data = bytes(np.random.randint(0, 256, (240*424*3,)).tolist())
print(np.all(the_scenic_route(data) == the_humourless_route(data)))

输出:

True