从行

时间:2017-09-26 01:14:34

标签: python arrays list numpy for-loop

我有一个看起来像这样的numpy数组:

77.132  2.075   63.365  74.880
49.851  22.480  19.806  76.053
16.911  8.834   68.536  95.339
0.395   51.219  81.262  61.253
72.176  29.188  91.777  71.458
54.254  14.217  37.334  67.413
44.183  43.401  61.777  51.314
65.040  60.104  80.522  52.165
90.865  31.924  9.046   30.070
11.398  82.868  4.690   62.629

我正在尝试做的是

  • 查找每行中第一个和最后一个项目的平均值
  • 从该行中的每个像素中减去此平均值
  • 每行重复
  • 创建减去像素的新图像。

我已尝试使用for循环,但我无法使其正常工作:

import numpy as np

#   Create random arrays to simulate images
np.random.seed(10)
image = 100 * np.random.rand(10, 4)

no_disk_list = []

#for row in image:
#    left, right =   row[0], row[-1]
#    average = (left + right) / 2.0
#    for i in row:
#        no_average = row[i] - average
#        print(average)
#        no_disk_list.append(no_average)

subtracted = np.ones_like(image)
height, width = image.shape
for row in image:
    left, right =   image[0], image[-1]
    average = (left + right) / 2.0
    for element in row:
        subtracted[row, element] = image[row, element] - average

两个嵌套循环都会出错:

  File "C:/Users/Jeremy/Dropbox/Astro480/NEOWISE/subtract_disk.py", line 17, in <module>
    no_disk_value = row[i] - disk_value

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

表示第一个循环和

  File "C:/Users/Jeremy/Dropbox/Astro480/NEOWISE/subtract_pixels.py", line 23, in <module>
    print(image[row, element])

IndexError: arrays used as indices must be of integer (or boolean) type

第二个。在我的情况下,问题hereherehere的用途有限。此外,我知道矢量化将是一个更好的方法,因为我最终将使用的图像有130万像素。如何使循环工作,甚至更好,矢量化计算?

1 个答案:

答案 0 :(得分:1)

如果我理解这个问题,这将有效:

subtracted = np.ones_like(image)
height, width = image.shape
for row_no, row in enumerate(image):   # keep the row number using enumerate
    left, right = row[0], row[-1]      # you need the first and last value of the ROW!
    average = (left + right) / 2.0
    # Also use enumerate in the inner loop
    for col_no, element in enumerate(row):
        subtracted[row_no, col_no] = element - average

你甚至可以使用广播(&#34;矢量化&#34;)来大大缩短这一点:

subtracted = image - (image[:, [0]] + image[:, [-1]]) / 2

image[:, [0]]是第一列,image[:, [-1]]是最后一列。通过将它们加2并除以2,您将获得包含每行平均值的2D数组。最后一步是从图像中减去这个,这在这种情况下很容易,因为它会正确播放。

步骤一步:

>>> arr = np.arange(20).reshape(4, 5)
>>> arr
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])
>>> arr[:, [0]]  # first column
array([[ 0],
       [ 5],
       [10],
       [15]])
>>> arr[:, [-1]]  # last column
array([[ 4],
       [ 9],
       [14],
       [19]])
>>> (arr[:, [0]] + arr[:, [-1]]) / 2   # average
array([[  2.],
       [  7.],
       [ 12.],
       [ 17.]])
>>> arr - (arr[:, [0]] + arr[:, [-1]]) / 2  # subtracted
array([[-2., -1.,  0.,  1.,  2.],
       [-2., -1.,  0.,  1.,  2.],
       [-2., -1.,  0.,  1.,  2.],
       [-2., -1.,  0.,  1.,  2.]])