Using a string to define Numpy array slice

不羁的心 提交于 2019-12-22 07:59:42

问题


I have an image array that has an X times Y shape of 2048x2088. The x-axis has two 20 pixel regions, one at the start and one at the end, which are used to calibrate the main image area. To access these regions I can slice the array like so:

prescan_area = img[:, :20]
data_area = img[:, 20:2068]
overscan_area = img[:, 2068:]

My question is how to define these areas in a configuration file in order the generalise this slice for other cameras which may have different prescan and overscan areas and therefore require a different slice.

Ideally, something like the strings below would allow a simple representation in the camera specific configuration file, but I am not sure how to translate these strings into array slices.

prescan_area_def = "[:, :20]"
image_area_def = "[:, 20:2068]"
overscan_area_def = "[:, 2068:]"

Maybe there is something obvious that I am missing?

Thanks!


回答1:


you can do something like:

var1="img"
prescan_area_def = "[:, :20]"

and to use eval

prescan_area=eval(var1+prescan_area_def)



回答2:


You can parse the string and use slice. The following generator expression within tuple will create the slice objects for you:

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

Demo:

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]])



回答3:


Here's an approach using regular expressions.

import numpy as np
import re

def slice_from_str(img, s):

    REGEX = r'\[(\d*):(\d*), (\d*):(\d*)\]'

    m = re.findall(REGEX,s)
    if m:
        # convert empty strings to None
        groups = [None if x=='' else int(x) for x in m[0]]
        start_x, end_x, start_y, end_y = groups
        x_slice = slice(start_x, end_x)
        y_slice = slice(start_y, end_y)

        return img[x_slice,y_slice]

    return []

img = np.random.rand(2048,2088)

prescan_area_def = '[:, :20]'
image_area_def = "[:, 20:2068]"
overscan_area_def = "[:, 2068:0]"

slice_from_str(img, prescan_area_def)
slice_from_str(img, image_area_def)
slice_from_str(img, overscan_area_def)


来源:https://stackoverflow.com/questions/43089907/using-a-string-to-define-numpy-array-slice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!