gpt4 book ai didi

python - 使用 numpy 将范围设置为零

转载 作者:太空宇宙 更新时间:2023-11-04 10:38:52 25 4
gpt4 key购买 nike

我开始使用 numpy cookbook 独立学习 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)是什么意思?

谢谢大家!

最佳答案

第一段代码实际上具有误导性,它依赖于 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]

特别是,这颠倒了之前的列表,因此从右到左而不是从左到右捕获对角线。

关于python - 使用 numpy 将范围设置为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21971483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com