[英]Applying tuple operations element-wise to a numpy array of tuples
I'm working with a 2d array of "pixels" (rgb int tuples), and I need an efficient way to apply some numpy operations to each element. 我正在使用二维数组的“像素”(rgb int元组),并且我需要一种有效的方法来对每个元素进行一些numpy操作。 Specifically, I'm trying to find pixels within a few color shades of a goal colour to later isolate them with numpy.nonzero 具体来说,我正在尝试在目标颜色的几种颜色阴影内找到像素,以便稍后使用numpy.nonzero进行隔离
Using For loops is for this case takes tens of seconds, so I'm looking to apply the numpy operations element-wise to achieve the same result. 在这种情况下,使用For循环需要数十秒,因此我希望逐个元素地应用numpy操作以达到相同的结果。
I'm looking to apply 我正在申请
Tuple subtraction : 元组减法:
pixel_diff = numpy.subtract( pixel_a, pixel_b)
Tuple absolute value: 元组绝对值:
pixel_abs = numpy.abs( pixel_diff )
Tuple comparison: 元组比较:
pixel_bool = pixel_abs < int_tolerance
Tuple all (): 元组全部():
is_similar = numpy.all(pixel_bool)
Trying to apply any of these operations blindly to my array results in invalid promotion errors, so I figure there must be a proper way to do it, instead. 尝试将任何这些操作盲目地应用于我的阵列会导致无效的升级错误,因此我认为必须有一种适当的方法来执行此操作。
import numpy as np
#create a RGB array of 1000x1000x3 and separate into colors
R, G, B = np.random.randint(0, 255, size = (1000, 1000, 3))
#find all pixels less than 100, 100, 100
np.logical_and((R<100), (G<100), (B<100))
You may modify the last line to suit your color needs. 您可以修改最后一行以适合您的颜色需求。 As is, the last line takes about 1.5 ms on a single core. 照原样,最后一行在单个内核上花费约1.5 ms。
You can convert into an equivalent non-structured view (without incurring any additional cost of making a copy of the underlying data): 您可以转换为等效的非结构化视图 (无需花费任何额外成本来复制基础数据):
my_3dview_of_ints = my_2d_of_3tuples.view(dtype=int)
where my_2d_of_3tuples
is your current structured array (array of tuples) 其中my_2d_of_3tuples
是您当前的结构化数组(元组数组)
You can then perform your usual numpy array operations on this view without running into any type errors. 然后,您可以在此视图上执行常规的numpy数组操作,而不会遇到任何类型错误。
For example, if your array looks like this: 例如,如果您的数组如下所示:
[[(207, 27, 185) ( 90, 197, 52) ( 58, 153, 145) (239, 42, 39)]
[(218, 23, 195) (226, 92, 170) ( 21, 114, 190) (192, 145, 48)]]
then the view, as created above, would look like this: 然后,如上创建的视图将如下所示:
[[[207 27 185]
[ 90 197 52]
[ 58 153 145]
[239 42 39]]
[[218 23 195]
[226 92 170]
[ 21 114 190]
[192 145 48]]]
For example: 例如:
pixel_a = my_3dview_of_ints[0,0] # pixel [207,27,185] at [0,0]
pixel_b = my_3dview_of_ints[1,1] # pixel [226,92,170] at [1,1]
pixel_diff = numpy.subtract( pixel_a, pixel_b) # Gives [-12,-65,5]
You can even change specific elements in the view, and the changes would automatically reflect at the corresponding location in your original structured array: 您甚至可以更改视图中的特定元素,并且更改将自动反映在原始结构化数组中的相应位置:
my_3dview_of_ints[3,3] = pixel_a # Assign [207, 27,185] to location [3,3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.