代码之家  ›  专栏  ›  技术社区  ›  Eshaka

如何更快地处理N数组

  •  0
  • Eshaka  · 技术社区  · 7 年前

    我有两个图像加载到两个numpy数组中。我想得到它们之间的差异,删除小于50的值,并将其其余部分设置为255,最终结果为back和white image。

    def count(base, image):
        x, y, z = base.shape
        sheet = np.zeros(base.shape)
        for i in range(x):
            for j in range(y):
                temp = 0
                for k in range(z):
                    if base[i, j, k] > image[i, j, k]:
                        t = base[i, j, k] - image[i, j, k]
                        if t > 50:
                            temp = 255
                    else:
                        t = image[i, j, k] - base[i, j, k]
                        if t > 50:
                            temp = 255
                sheet[i, j] = [temp, temp, temp]
    
        array = sheet[:, :, 0]
    

    谢谢您

    0 回复  |  直到 7 年前
        1
  •  3
  •   Wai Ha Lee captain-yossarian from Ukraine    7 年前

    将代码矢量化看起来很简单,除了一个问题:您的数据似乎是无符号整数( uint8 np.abs(image-base)>50 实际上,检测大于50的差异是行不通的 np.abs

    sheet = np.array([[0,0,0],[255,255,255]], 'u1')[((np.maximum(base, image)-np.minimum(base, image))>50).any(2).view('u1')]
    

    或

    sheet = np.array([[0,0,0],[255,255,255]], 'u1')[(np.abs(np.subtract(image, base, dtype='i2'))>50).any(2).view('u1')]
    

    这个

    1. 正确计算亚像素级的差异,

      • 第二个强制使用有符号的结果类型 'i2' 或 int16 为了区别

    2. 用至少一个这样的子像素标记像素( any(2) ),

    3. .view('u1') )0和1

    4. 并使用这些索引到模板数组中。

        2
  •  1
  •   Francisco Rivera    7 年前

    def count_new(base, image, thresh=50):
        # these are the pixel absolute value differences
        differences = np.abs(base - image)
    
        # whether the difference exceeds the threshold
        big_difference = differences > thresh
    
        # whether each pixel has at least one big difference
        big_difference = big_difference.any(axis=2)
    
        # return 255 where big differences, and 0 everywhere else
        return 255 * big_difference.astype(int)
    

    x = np.random.randint(256, size=(10, 11, 3))
    y = np.random.randint(256, size=(10, 11, 3))
    assert((count(x,y) == count_new(x,y)).all())
    

    这说明它是。