在 Linux 下将 Windows 字符串转换为 numpy 时的 fromstring()

fromstring() when converting Windows string to numpy under Linux

32 位 Windows 机器上的 Pyro4 服务器 运行 使用 img.tostring() 将 numpy 图像数据作为字符串提供,转换前报告的 dtypeint32.

服务器代码如下:

def getLastPhase(self):
    print("Sending the data now: ")
    print( self.lastPhase.dtype )
    return self.lastPhase.tostring()

客户端代码如下:

data = getLastPhase()

数据是在 Linux 机器上接收的,len( data ) = 4177920 或以字节为单位的图像大小 (1024x1020 x4)。

但是,使用 fromstring( data, dtype='int32' ) 会导致异常:

ValueError: string size must be a multiple of element size

如果使用 int16 而不是 int32,则不会引发异常,但数据是无意义的。

为什么在字符串大小与我的数据大小匹配的情况下会引发此异常,而在 int16 情况下不会引发此异常?

Windows下的Python和Linux中的string有区别吗?

任何关于如何克服这个问题的想法将不胜感激。

编辑: Windows 机器上的 python 版本是 2.7,而 Linux 上是 3.6

关键点是在 Python 2.x 中,str 类型是(有时!)一系列字节,因此除非您明确要求它,否则不会进一步解释就这样吧。

在 Python 3.x 中,str 类型 解释,并且我认为是标准的 UTF-8。

因此您希望在 Python 3.x 上使用 byte 类型。

执行此操作的自然方法是 encode 将字符串转换为一系列字节:

fromstring( data.encode('raw_unicode_escape'), dtype='int32' )

正如其他人所说, &

你需要小心,但在这种情况下,我知道它只是转换的二进制数据,所以我们不希望 raw_unicode_escape 范围之外的任何 Unicode 字符会成功de/encode.

所以没关系。