arrays - 快速组合多幅图像的(x,y)像素值的方法?

标签 arrays python-3.x image performance numpy

我有 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)

最佳答案

您可以进行如下操作:

# 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')

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

关于arrays - 快速组合多幅图像的(x,y)像素值的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49814569/

相关文章:

java - 为坐标对的二维数组返回一维数组的整数索引

php - 如何调整从 mysql 检索到的 blob 图像的大小

arrays - 按列逐行匹配两个文件 - 无键

arrays - Swift 扩展特定类型的数组

python - 初始化 MCI python 时出现问题

python-3.x - 无法在 Visual Studio 代码上导入 Tkinter?

python-3.x - 名称 'Key' 未定义用于访问 DynamoDB 的 Lambda 函数

node.js - 无法在 Node js中显示静态文件夹中的图像

html - 如何将 img 居中但只有 1920px 的 1200px?

javascript - 动态抓取输入/选择值而不直接定位 - Javascript