mArk
mArk

Reputation: 658

Replace a center pixel value in a NumPy array with a maximum value in the same array

Suppose a variable contains multiple arrays like:

data = array([[1,2,3],
             [4,5,6],
             [10,11,12]],dtype=float32)

       array([[1,2,3],
               [4,5,6],
               [7,8,9]],dtype=float32)

I want to compare the center element (ie. 5 in both the arrays) with all of the elements in their respective arrays and return the largest element whose value is greater than 2 times of the center element (5x2=10 in both of the arrays) otherwise return the center element.

The expected output for the above example:

 data = [[12],
        [5]]

Upvotes: 1

Views: 616

Answers (2)

David Buck
David Buck

Reputation: 3828

This will do what I think you're asking for:

import numpy as np

data = [np.array([[1, 2, 3],
                   [4, 5, 6],
                   [9, 11, 12]], dtype=int),
        np.array([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]], dtype=int)]

output = []
for arr in data:
    centre = arr[len(arr)//2, len(arr)//2]
    maximum = np.max(arr)
    if maximum > (centre * 2):
        output.append(maximum)
    else:
        output.append(centre)

print(output)

Output

[12, 5]

As an interesting aside, from Python 3.8 you can use the assignment (aka Walrus) operator to do this in a single list line.

print([maximum if (maximum:= np.max(x)) > ((centre := x[(point := len(x)//2), point]) * 2) else centre for x in data])

Upvotes: 1

Charef B
Charef B

Reputation: 437

import numpy as np 

def getMax(array): 
    shape = array.shape
    l = shape[0]
    r = shape[1]
    middle = array[l // 2, r // 2]
    _max = np.amax(array)
    return _max if _max > 2 * middle else middle

d1 = np.array([[1,2,3],
               [4,5,6],
               [9,10,11]])

d2 = np.array([[1,2,3],
               [4,5,6],
               [7,8,9]])

data = [d1, d2]

ans = []
for d in data:
    ans.append(getMax(d))

print(ans) # [11, 5]

This is what i got for 3 by 3 matrix, assuming you're using numpy.

Upvotes: 1

Related Questions