Python 什么';设置numpy阵列阈值的最快方法是什么?
我希望得到的数组为二进制是/否 我想出了Python 什么';设置numpy阵列阈值的最快方法是什么?,python,arrays,numpy,Python,Arrays,Numpy,我希望得到的数组为二进制是/否 我想出了 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):
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)
但是一次迭代数组中的一个值非常慢,我知道一定有一种更快的方法,什么是最快的?我不确定tresholding操作是否特殊,例如,需要为每个像素或其他对象自定义它,但您可以在np数组上使用逻辑操作。例如:
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)
您可以通过多种方式一次比较整个阵列,而不是循环。从
>>> 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。其中:
>>> 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==0
和True==1
对于1000x1000阵列,算术黑客似乎对我来说最快,但老实说,我会使用np。其中
,因为我认为它最清晰:
>>> %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
>>> %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