【问题标题】:Setting ranges to zero using numpy使用 numpy 将范围设置为零
【发布时间】:2014-03-25 03:42:51
【问题描述】:

我开始使用 numpy 食谱独立学习 numpy。我查看并执行了以下代码:

import scipy.misc
import matplotlib.pyplot

#This script demonstates fancy indexing by setting values
#On the diagnols to 0

#Load lena array
lena = scipy.misc.lena()
xmax = lena.shape[0]
ymax = lena.shape[1]

#Fancy indexing
#can set ranges of points to zero, all at once instead of using loop
lena[range(xmax), range(ymax)] = 0
lena[range(xmax-1,-1,-1), range(ymax)] = 0
matplotlib.pyplot.imshow(lena)
matplotlib.pyplot.show()

我理解这段代码中的所有内容,除了:

lena[range(xmax), range(ymax)] = 0
lena[range(xmax-1,-1,-1), range(ymax)] = 0

我阅读了the documentation 关于索引和切片的内容,但仍然无法理解上述代码。以下是我的困惑点:

1)range(xmax) 和 range(ymax) 包含整个 x,y 轴。将它们设置为零不会使整个图像变黑吗?

2)range(xmax-1,-1,-1)是什么意思?

谢谢大家!

【问题讨论】:

  • 您的last question 的答案中没有解释#1 吗?而#2 可以用help(range) 来解释。

标签: python numpy scipy


【解决方案1】:

第一段代码实际上具有误导性,它依赖于lena 是一个正方形图像这一事实:发生的情况相当于调用zip(range(xmax), range(ymax)),然后将每个生成的元组设置为0。您可以在这里查看可能出现的问题:如果xmax != ymax,那么事情将无法正常工作:

>>> test = lena[:,:-3]
>>> test.shape
(512, 509)
>>> xmax, ymax = test.shape
>>> test[range(xmax), range(ymax)] = 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: shape mismatch: objects cannot be broadcast to a single shape

最好先定义diag_max = min(xmax, ymax),然后设置lena[range(diag_max), range(diag_max)] = 0

第二个问题的答案更简单:range(from, to, step) 是对range 的一般调用:

>>> range(1, 10, 2)
[1, 3, 5, 7, 9]
>>> range(1, 10, -2)
[]
>>> range(10, 1, -2)
[10, 8, 6, 4, 2]
>>> range(10, 0, -1)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

特别是,这反转了前一个列表,因此从右到左而不是从左到右抓取对角线。

【讨论】:

  • " range(from, to, step) 是对 range 的一般调用:" 好的,很酷,我混合了 range() 和列表索引(使用分号)。感谢您澄清以上内容
【解决方案2】:

'range' 会给你一个列表。在你的 REPL 中尝试一下,看看会发生什么:

r = range(5)
# r is no [0,1,2,3,4]

因此,执行 'lena[range(xmax), range(ymax)] = 0' 会将 'lena' 矩阵的 diagonal 设置为零,因为您正在遍历 x 和 y同时增量坐标。

'range' 非常简单。 @JLLagrange 的答案完美地回答了它。

【讨论】:

  • "同时递增。"啊!这是我缺少的一个核心概念。我没有意识到它同时循环通过两者。这更有意义!谢谢
猜你喜欢
  • 1970-01-01
  • 2013-02-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-22
相关资源
最近更新 更多