简体   繁体   English

将计算值元素添加到多维numpy数组的快速方法

[英]Fast way to add calculated value element to multidimensional numpy array

I've got a numpy array 'image' that is a two dimensional array where each element has two components. 我有一个numpy数组'image'是一个二维数组,其中每个元素都有两个组件。 I want to convert this to another two dimensional array where each element has three components. 我想将其转换为另一个二维数组,其中每个元素都有三个组件。 The first two and a third one calculated from the first two, like so: 从前两个计算的前两个和第三个,如下所示:

for x in range(0, width):
    for y in range(0, height):
        horizontal, vertical = image[y, x]

        annotated_image[y, x] = (horizontal, vertical, int(abs(horizontal) > 1.0 or abs(vertical) > 1.0))

This loop works as expected, but is very slow when compared to other numpy functions. 这个循环按预期工作,但与其他numpy函数相比非常慢。 For a medium-sized image this takes an unacceptable 30 seconds. 对于中等大小的图像,这需要30秒不可接受。

Is there a different way to do the same calculation but faster? 是否有不同的方法来进行相同的计算但速度更快? The original image array does not have to be preserved. 不必保留原始图像阵列。

You could just separate the components of the image and work with multiple images instead: 您可以将图像的组件分开,然后使用多个图像:

image_component1 = image[:, :, 0]
image_component2 = image[:, :, 1]

result = (np.abs(image_component1) > 1.) | (np.abs(image_component2) > 1.)

If you for some reason need the layout you specified you could as well construct another three dimensional image: 如果由于某种原因需要您指定的布局,您还可以构建另一个三维图像:

result = np.empty([image.shape[0], image.shape[1], 3], dtype=image.dtype)

result[:, :, 0] = image[:, :, 0]
result[:, :, 1] = image[:, :, 1]
result[:, :, 2] = (np.abs(image[:, :, 0]) > 1.) | (np.abs(image[:, :, 1]) > 1.)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM