【问题标题】:Quick method to combine (x,y) pixel value of multiple images?组合多个图像的(x,y)像素值的快速方法?
【发布时间】:2018-09-23 16:05:10
【问题描述】:

我有 10 个 1944 x 2546 二进制图像存储在 nparray images 中。 我想读取 10 张图像上每个像素的像素值,并将它们组合成一串 0 和 1(例如 '1001101100')并将它们存储到二维数组 output 中。到目前为止,我正在使用嵌套的 for 循环,这非常慢。因此,我想知道是否有任何更聪明的方法来实现相同的结果。我目前的代码如下:

output = [()]
for y in range(0,image_height):
    for x in range(0,image_width):
        code_string = ''
        for n in range(0,len(images)-2):
            code_string = code_string + str(images[n][y,x]/255)
        output.append(code_string)

【问题讨论】:

  • 这是一件很奇怪的事情!你愿意说一下你之后打算如何处理这些字符串吗?您是否考虑过将它们存储为每个位置的整数中的位?然后,您可以使用逻辑 AND、OR、XOR 对它们进行操作。
  • 我正在解码一系列格雷码结构光图案(最终用于 3D 场景重建),因此我需要为每个像素获取一个类似 '1001101100' 的字符串。此信息将有助于提供 2 个摄像头之间的空间对应关系。

标签: arrays python-3.x image performance numpy


【解决方案1】:

你可以这样做:

# create 0, 255 arrays
imgs = [255 * np.random.randint(0, 2, (1944,2546)) for i in range(10)]

# binarize them, convert to int32, stack them along the last axis,
# add the offset of character '0' and view-cast to unicode
binstr = (np.r_[('2,3,0', *map(np.int32, map(np.bool8, imgs)))] + ord('0')).view('U10').squeeze()
binstr
# array([['0010110011', '0101011101', '0001000000', ..., '1011101100',
#         '1110011110', '0011110111'],
#        ['1101110100', '0000001000', '0000100101', ..., '0000110100',
#         '1000010011', '0001101011'],
#        ['0100011100', '0111101001', '0001011001', ..., '1111011111',
#         '0110100000', '0001111000'],
#        ...,
#        ['0100000110', '1000000000', '0000001011', ..., '1001110001',
#         '1001010000', '0010010111'],
#        ['0011100010', '0110010101', '0011111000', ..., '1011100101',
#         '1011001111', '1100011011'],
#        ['0011111101', '0000001101', '1110011011', ..., '1011110100',
#         '0001010010', '0001010010']], dtype='<U10')

在我的笔记本电脑上转换需要半秒钟。

【讨论】:

  • 谢谢!该代码可以高速实现结果。另外一个问题是,我得到的不是'0011111101',而是'įį0į000000'。关于为什么我会得到一个符号而不是 1 的任何想法?
  • @yukchingleung 我怀疑这是因为您的输入不是0s 和1s,而是0s 和255s。我会更新答案。
  • @yukchingleung 完成。请看一下。
【解决方案2】:

您可能会通过不迭代地创建和附加到字符串来获得小幅加速,但只有在收集图像中的位之后才一次:

    code_string = []
    for n in range(0,len(images)-2):
        code_string.append(images[n][y,x]/255)
    output.append(''.join(code_string))

可能更好的方法是将图像加载到 numpy-arrays 并正确切片和切块 - 我的 numpyfu 还不够好。

【讨论】:

    【解决方案3】:

    我认为最慢的部分是调用 10 x 1944 x 2546 追加命令。

    您可以将这些图像重新整形为 (1944x2546, 10) 表格,如果您想要列表,请在最后使用 X.tolist() 命令。

    images_bool = images < 256
    output = images_bool.transpose((1,2,0)).reshape((1944*2546,10)).tolist()
    

    为什么要转换成字符串?

    【讨论】:

      猜你喜欢
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      • 2022-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-05
      • 2013-12-05
      相关资源
      最近更新 更多