簡體   English   中英

閾值numpy數組的最快方法是什么?

[英]What's the fastest way to threshold a numpy array?

我想將結果數組作為二進制是/否。

我想出來了

    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)

但是一次迭代數組一個值非常慢,我知道必須有一個更快的方法,最快的是什么?

您可以通過多種方式一次比較整個陣列,而不是循環。 從...開始

>>> 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

方法#3:做同樣的事,但使用算術黑客

>>> (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

我不確定你的閾值操作是否特殊,例如需要為每個像素或其他東西定制它,但你可以在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]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM