使用字符串定义 Numpy 数组切片

Jam*_*mac 5 python arrays numpy slice

我有一个图像数组,其 X 乘以 Y 形状为 2048x2088。x 轴有两个 20 像素的区域,一个在开始,一个在结束,用于校准主图像区域。要访问这些区域,我可以像这样对数组进行切片:

prescan_area = img[:, :20]
data_area = img[:, 20:2068]
overscan_area = img[:, 2068:]
Run Code Online (Sandbox Code Playgroud)

我的问题是如何在配置文件中定义这些区域,以便将此切片推广到其他可能具有不同预扫描和过扫描区域并因此需要不同切片的相机。

理想情况下,类似下面的字符串将允许在相机特定的配置文件中进行简单的表示,但我不确定如何将这些字符串转换为数组切片。

prescan_area_def = "[:, :20]"
image_area_def = "[:, 20:2068]"
overscan_area_def = "[:, 2068:]"
Run Code Online (Sandbox Code Playgroud)

也许我缺少一些明显的东西?

谢谢!

Kas*_*mvd 6

您可以解析字符串并使用slice. 以下生成器表达式tuple将为您创建切片对象:

tuple(slice(*(int(i) if i else None for i in part.strip().split(':'))) for part in prescan_area_def.strip('[]').split(','))
Run Code Online (Sandbox Code Playgroud)

演示:

In [5]: import numpy as np

In [6]: 

In [6]: a = np.arange(20).reshape(4, 5)

In [7]: a
Out[7]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

In [8]: 

In [8]: prescan_area_def = "[:, :3]"

In [9]: a[:, :3]
Out[9]: 
array([[ 0,  1,  2],
       [ 5,  6,  7],
       [10, 11, 12],
       [15, 16, 17]])

In [10]: indices = tuple(slice(*(int(i) if i else None for i in part.strip().split(':'))) for part in prescan_area_def.strip('[]').split(','))

In [11]: indices
Out[11]: (slice(None, None, None), slice(None, 3, None))

In [12]: a[indices]
Out[12]: 
array([[ 0,  1,  2],
       [ 5,  6,  7],
       [10, 11, 12],
       [15, 16, 17]])
Run Code Online (Sandbox Code Playgroud)


Bin*_*ven 2

你可以这样做:

var1="img"
prescan_area_def = "[:, :20]"
Run Code Online (Sandbox Code Playgroud)

并使用eval

prescan_area=eval(var1+prescan_area_def)
Run Code Online (Sandbox Code Playgroud)