簡體   English   中英

在Python中從TCP客戶端獲取字符串后,加快從字節字符串到圖像的轉換

[英]Speeding up conversion from Byte-String to Image after getting the String from TCP Client in Python

我有一個從TCP客戶端中的TCP服務器接收圖像的客戶端。

此后,圖像將被序列化,當然也將其作為字節。 現在,我想再次將其重塑為圖像。

但是我的過程花了很長時間,所以我想知道是否有更Pythony的,更快的方法?

該代碼對每個步驟都進行了注釋,但它們是:

1.將其從十六進制二進制表示形式轉換為可讀字符串(0.002 s)

2.在每個字節對之后拆分字符串(0.08 s)

3.將列表的每個值轉換為整數(0.17 s)

4.將形狀重塑為紅色,綠色,藍色(0.02)的矩陣表示形式

5.一起重塑矩陣以形成圖像

查看時間后,我發現最多的時間花在了步驟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... ”(只是一個例子)

您確定您沒有使事情變得不必要的復雜嗎? 也許我缺少了一些東西,但是使用正確長度的模擬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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM