Shift elements in a numpy array

前端 未结 8 1723
萌比男神i
萌比男神i 2020-12-01 00:54

Following-up from this question years ago, is there a canonical \"shift\" function in numpy? I don\'t see anything from the documentation.

Here\'s a simple version o

8条回答
  •  星月不相逢
    2020-12-01 01:15

    One way to do it without spilt the code into cases

    with array:

    def shift(arr, dx, default_value):
        result = np.empty_like(arr)
        get_neg_or_none = lambda s: s if s < 0 else None
        get_pos_or_none = lambda s: s if s > 0 else None
        result[get_neg_or_none(dx): get_pos_or_none(dx)] = default_value
        result[get_pos_or_none(dx): get_neg_or_none(dx)] = arr[get_pos_or_none(-dx): get_neg_or_none(-dx)]     
        return result
    

    with matrix it can be done like this:

    def shift(image, dx, dy, default_value):
        res = np.full_like(image, default_value)
    
        get_neg_or_none = lambda s: s if s < 0 else None
        get_pos_or_none = lambda s : s if s > 0 else None
    
        res[get_pos_or_none(-dy): get_neg_or_none(-dy), get_pos_or_none(-dx): get_neg_or_none(-dx)] = \
            image[get_pos_or_none(dy): get_neg_or_none(dy), get_pos_or_none(dx): get_neg_or_none(dx)]
        return res
    

提交回复
热议问题