【问题标题】:fromstring() when converting Windows string to numpy under LinuxLinux下将Windows字符串转换为numpy时的fromstring()
【发布时间】:2018-08-04 12:39:03
【问题描述】:

在 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和Linux下Python中的string有区别吗?

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

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

【问题讨论】:

    标签: python linux windows numpy tostring


    【解决方案1】:

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

    在 Python 3.x 中,str 类型解释,我相信它是标准的 UTF-8。

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

    这样做的自然方法是将encode字符串转换为一系列字节:

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

    正如其他人提到的, String to Bytes Python without change in encoding & Python: Convert Raw String to Bytes String without adding escape chraracters

    您需要小心,但在这种情况下,我知道它只是转换后的二进制数据,因此我们不希望任何超出raw_unicode_escape 范围的 Unicode 字符成功 > 解码/编码。

    所以没关系。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-10
      • 2013-05-05
      • 1970-01-01
      • 2021-04-26
      • 2015-03-28
      • 1970-01-01
      • 2019-11-24
      • 1970-01-01
      相关资源
      最近更新 更多