Using string to define an array of numpy arrays

I have an array of images that is X shaped Y 2048x2088. The x-axis has two 20 pixel areas, one at the beginning and one at the end, which are used to calibrate the main area of ​​the image. To access these areas, I can slice the array like this:

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

      

My question is how to define these areas in the config file in order to generalize this slice to other cameras, which may have different prescan and jump areas and therefore a different slice is required.

Ideally, something like the lines below would allow a simple view in a specific camera config file, but I'm not sure how to translate those lines 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?

Thank!

+3


source to share


3 answers


you can do something like:

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

      



and use eval

prescan_area=eval(var1+prescan_area_def)

      

+2


source


You can parse the string and use slice

. The following generator expression inside tuple

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

      

+1


source


Here's a regular expression approach.

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)

      

0


source







All Articles