使用Python从现有数组创建新的Numpy数组

时间:2015-09-16 13:57:45

标签: python arrays numpy

我需要使用Python和Numpy拍摄灰度图像(作为Numpy数组),然后逐个像素地迭代,以区分X方向的图像。我无法使用任何函数自动执行此操作,遗憾的是我需要迭代。 我需要使用导数:F(x,y)= F(x,y + 1) - F(x,y)到每个像素,并以新图像的形式返回输出(在Numpy数组中)。

一个简单的4像素示例 10 15 5 25 会回来 5 10 20

我想取绝对值(消除负值)并使输出宽度比输入短1列(因为不能对最后一列进行计算)。

我可以使用np.nditer读取数组,但我真的可以使用一些帮助来弄清楚如何将计算应用于每个元素并返回结果。

我很快就用Java来解决这个问题,那里的任何Python专家都可以帮我转换吗?

public class ArrayTest {
public static void main(String[] args) {

    int[] arrayOne = { 5, 10, 20, 5 };
    int[] newArray = new int[arrayOne.length];

    for (int i = 0; i < arrayOne.length - 1; i++) {

        newArray[i] = Math.abs(arrayOne[i + 1] - arrayOne[i]);

        System.out.println(newArray[i]);
    }
}

}

1 个答案:

答案 0 :(得分:3)

根据我对家庭作业的评论:

看看你的Java代码,我认为这就是你想要的?

import numpy as np

data = np.array([10, 15, 5, 25])
diff = np.abs(data[:-1] - data[1:])

print diff
array([ 5, 10, 20])

编辑:

我只是简单地将数组的每个值与最后一个值分开(因为那里没有任何东西可以计算),并将该值与除第一个值之外的每个值进行差分。

print data[:-1]
array([10, 15,  5])
print data[1:]
array([15,  5, 25])

data[1:] - data[:-1]相当于F(x)= F(x + 1) - F(x)。

我想你已经熟悉了使用列表切割符号。

使用循环:

new = np.empty(shape = data.shape[0]-1)

for i in range(0, new.shape[0]):
    new[i] = np.abs(data[i+1] - data[i])

正如@Joe Kington所说,你通常不应该这样做,因为numpy允许使用向量化表达式(在整个数组而不是每个元素上计算的操作),这使代码更快。在这个简单的例子中不是一个要求,但是如果你用很多大型数组做这件事,可能会给你带来明显的好处。

编辑2:

在2D情况下使用循环:

import numpy as np
data =  np.array([10, 15, 5, 25])
data_2d = np.repeat(data,2).reshape(-1,2) #make some 2d data
data_2d[:,1] = data_2d[:,1] + 100 #make the y axis different so we can tell them apart easier

print data_2d
[[ 10 110]
 [ 15 115]
 [  5 105]
 [ 25 125]]

'''
Making a new array to store the results, copying over the Y values.
The X values we will change later. Note that not using the .copy() 
method would create a VIEW of data_2d, so when we change new,
data_2d would change as well.
'''

new = data_2d[:-1,:].copy()

print new.shape
(3,2) # 3 here is the number of elements per axis, 2 is the number of axes. 

for i in range(0,data_2d.shape[0]-1): # looping the X axis
   new[i,0] = np.abs(data_2d[i+1,0] - data_2d[i,0]) # referencing the X axis explicitly

print new
[[  5 110]
 [ 10 115]
 [ 20 105]]
相关问题