在Python中从TCP客户端获取字符串后,加快从字节字符串到图像的转换
我有一个客户端,它在TCP客户端中接收来自TCP服务器的映像 在这之后,图像被序列化,当然是作为字节。现在我想再次将其重塑为一个图像 然而,我的过程需要很长时间,所以我想知道是否有一种更具python风格、更快的方法来实现这一点 每个步骤都会对代码进行注释,但它们是: 1.将其从十六进制二进制表示转换为可读字符串(0.002秒) 2.在每个字节对后拆分字符串(0.08秒) 3.将列表的每个值强制转换为整数(0.17秒) 4.重塑为红色、绿色、蓝色(0.02)的矩阵表示形式 5.一起重塑矩阵以形成图像 在查看了计时之后,我发现大部分时间都是通过第三步来完成的在Python中从TCP客户端获取字符串后,加快从字节字符串到图像的转换,python,string,image,opencv,numpy,Python,String,Image,Opencv,Numpy,我有一个客户端,它在TCP客户端中接收来自TCP服务器的映像 在这之后,图像被序列化,当然是作为字节。现在我想再次将其重塑为一个图像 然而,我的过程需要很长时间,所以我想知道是否有一种更具python风格、更快的方法来实现这一点 每个步骤都会对代码进行注释,但它们是: 1.将其从十六进制二进制表示转换为可读字符串(0.002秒) 2.在每个字节对后拆分字符串(0.08秒) 3.将列表的每个值强制转换为整数(0.17秒) 4.重塑为红色、绿色、蓝色(0.02)的矩阵表示形式 5.一起重塑矩阵以形成
#....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垃圾”,它们只是ascii中数字的表示。
用
binascci.hexlify(数据)
解码并打印出来后,我得到的值是一个巨大的字符串,如“011231A3B2B1C312…
”(只是一个例子)你确定你没有让事情变得比必要的复杂吗?也许我遗漏了什么,但是使用正确长度的mockbytes
对象,我在一行中获得了与您的五步方法相同的输出:
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
那么,哪一步占用了大部分时间/哪一部分是瓶颈?我现在发现的第三步可能您可以在上一步中进行
int
转换:[int(asstr[I:I+n],16)对于范围(0,len(asstr),n)]
?谢谢,这带来了一点改进:第2步现在需要约0.21秒——总体来说速度更快,但如果这是一个愚蠢的问题,那就太慢了。但第1-3步的目的到底是什么?如果我没弄错的话,您正在将字节(基本上是数字)转换为十六进制字符串,然后再转换回数字。你能不能把这个来回剪下来?我错过什么了吗?谢谢你这真的很棒!我不知道numpy的“frombuffer”方法