什么是numpy数组阈值处理的最快方法?

8
我希望你能将结果数组转换为二进制的是/否。
我想到了以下代码:
    img = PIL.Image.open(filename)

    array = numpy.array(img)
    thresholded_array = numpy.copy(array)

    brightest = numpy.amax(array)
    threshold = brightest/2

    for b in xrange(490):
        for c in xrange(490):
            if array[b][c] > threshold:
                thresholded_array[b][c] = 255
            else:
                thresholded_array[b][c] = 0

    out=PIL.Image.fromarray(thresholded_array)

但是逐个值地迭代数组非常慢,我知道一定有更快的方法,那么最快的方法是什么?

2个回答

16

与其使用循环,你可以通过几种方式一次性比较整个数组。从...开始

>>> arr = np.random.randint(0, 255, (3,3))
>>> brightest = arr.max()
>>> threshold = brightest // 2
>>> arr
array([[214, 151, 216],
       [206,  10, 162],
       [176,  99, 229]])
>>> brightest
229
>>> threshold
114

方法1:使用np.where函数:

>>> np.where(arr > threshold, 255, 0)
array([[255, 255, 255],
       [255,   0, 255],
       [255,   0, 255]])

方法2:使用布尔索引创建新数组

>>> up = arr > threshold
>>> new_arr = np.zeros_like(arr)
>>> new_arr[up] = 255

方法三:采用算术技巧进行相同的操作

>>> (arr > threshold) * 255
array([[255, 255, 255],
       [255,   0, 255],
       [255,   0, 255]])

这是因为 False == 0True == 1


对于一个 1000x1000 的数组,从我的测试结果来看,算术方法是最快的,但老实说我会使用 np.where,因为我认为它更清晰:

>>> %timeit np.where(arr > threshold, 255, 0)
100 loops, best of 3: 12.3 ms per loop
>>> %timeit up = arr > threshold; new_arr = np.zeros_like(arr); new_arr[up] = 255;
100 loops, best of 3: 14.2 ms per loop
>>> %timeit (arr > threshold) * 255
100 loops, best of 3: 6.05 ms per loop

3

我不确定你的阈值操作是否特殊,例如需要为每个像素自定义它,但是你可以在np.arrays上使用逻辑运算。例如:

import numpy as np


a = np.round(np.random.rand(5,5)*255)

thresholded_array = a > 100; #<-- tresholding on 100 value

print(a)
print(thresholded_array)

提供:

[[ 238.  201.  165.  111.  127.]
 [ 188.   55.  157.  121.  129.]
 [ 220.  127.  231.   75.   23.]
 [  76.   67.   75.  141.   96.]
 [ 228.   94.  172.   26.  195.]]

[[ True  True  True  True  True]
 [ True False  True  True  True]
 [ True  True  True False False]
 [False False False  True False]
 [ True False  True False  True]]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接