gpt4 book ai didi

python - numpy 中数组末尾的零填充切片

转载 作者:太空狗 更新时间:2023-10-29 20:58:03 24 4
gpt4 key购买 nike

在 numpy 中,如果我在数组末尾进行切片,是否有办法将填充条目置零,这样我得到的东西就是所需切片的大小?

例如,

>>> x = np.ones((3,3,))
>>> x
array([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
>>> x[1:4, 1:4] # would behave as x[1:3, 1:3] by default
array([[ 1., 1., 0.],
[ 1., 1., 0.],
[ 0., 0., 0.]])
>>> x[-1:2, -1:2]
array([[ 0., 0., 0.],
[ 0., 1., 1.],
[ 0., 1., 1.]])

在视觉上,我希望越界区域用零填充:

enter image description here

我正在处理图像,并希望使用零填充来表示为我的应用程序移出图像。

我目前的计划是在切片之前使用 np.pad 使整个数组变大,但索引似乎有点棘手。有可能更简单的方法吗?

最佳答案

据我所知,没有针对此类问题的 numpy 解决方案(我知道的任何软件包中也没有)。你可以自己做,但即使你只想要基本的切片,它也会非常非常复杂。我会建议你手动 np.pad您的数组并在实际切片之前简单地偏移您的开始/停止/步骤。

但是,如果您只需要支持整数和没有步骤的切片,我有一些“工作代码”:

import numpy as np

class FunArray(np.ndarray):
def __getitem__(self, item):

all_in_slices = []
pad = []
for dim in range(self.ndim):
# If the slice has no length then it's a single argument.
# If it's just an integer then we just return, this is
# needed for the representation to work properly
# If it's not then create a list containing None-slices
# for dim>=1 and continue down the loop
try:
len(item)
except TypeError:
if isinstance(item, int):
return super().__getitem__(item)
newitem = [slice(None)]*self.ndim
newitem[0] = item
item = newitem
# We're out of items, just append noop slices
if dim >= len(item):
all_in_slices.append(slice(0, self.shape[dim]))
pad.append((0, 0))
# We're dealing with an integer (no padding even if it's
# out of bounds)
if isinstance(item[dim], int):
all_in_slices.append(slice(item[dim], item[dim]+1))
pad.append((0, 0))
# Dealing with a slice, here it get's complicated, we need
# to correctly deal with None start/stop as well as with
# out-of-bound values and correct padding
elif isinstance(item[dim], slice):
# Placeholders for values
start, stop = 0, self.shape[dim]
this_pad = [0, 0]
if item[dim].start is None:
start = 0
else:
if item[dim].start < 0:
this_pad[0] = -item[dim].start
start = 0
else:
start = item[dim].start
if item[dim].stop is None:
stop = self.shape[dim]
else:
if item[dim].stop > self.shape[dim]:
this_pad[1] = item[dim].stop - self.shape[dim]
stop = self.shape[dim]
else:
stop = item[dim].stop
all_in_slices.append(slice(start, stop))
pad.append(tuple(this_pad))

# Let numpy deal with slicing
ret = super().__getitem__(tuple(all_in_slices))
# and padding
ret = np.pad(ret, tuple(pad), mode='constant', constant_values=0)

return ret

这可以按如下方式使用:

>>> x = np.arange(9).reshape(3, 3)
>>> x = x.view(FunArray)
>>> x[0:2]
array([[0, 1, 2],
[3, 4, 5]])
>>> x[-3:2]
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 1, 2],
[3, 4, 5]])
>>> x[-3:2, 2]
array([[0],
[0],
[0],
[2],
[5]])
>>> x[-1:4, -1:4]
array([[0, 0, 0, 0, 0],
[0, 0, 1, 2, 0],
[0, 3, 4, 5, 0],
[0, 6, 7, 8, 0],
[0, 0, 0, 0, 0]])

请注意,这可能包含 Bug 和“编码不干净”的部分,除了在微不足道的情况下,我从未使用过它。

关于python - numpy 中数组末尾的零填充切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41153803/

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