使用Python从现有的

2024-09-30 01:23:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要使用Python和Numpy获取一个灰度图像(作为Numpy数组),然后通过像素迭代它,以便在xa方向上区分图像。我不能使用任何函数来自动执行此操作,我需要迭代。 我需要对每个像素使用导数:F(x,y)=F(x,y+1)-F(x,y)并以新图像的形式返回输出(在Numpy数组中)。在

一个简单的4像素示例 1015年5月25日 会回来的 5 10 20个

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

我可以用np.N指示器,但我真的需要一些帮助来弄清楚如何将计算应用于每个元素并返回结果。在

我很快就用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]);
    }
}

}

Tags: 函数图像numpy像素数组public方向length
1条回答
网友
1楼 · 发布于 2024-09-30 01:23:40

听我对家庭作业的冷嘲热讽:

看看你的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])

编辑:

我只是简单地把数组的每个值从最后一个值中分离出来(因为没有什么可以计算的),并将它与第一个值之外的每个值进行比较。在

^{pr2}$

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:

在二维情况下使用循环:

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

相关问题 更多 >

    热门问题