Efficient element-wise multiplication in Python with numpy array

594 views Asked by At

I have a numpy array of type np.int64, to which I am trying to apply a formula.

Let's say the array is a 2D array called total_img which has dimensions 400 X 300 pixels. For each pixel I want to compute the following formula. px = 255*(min - px)/(min - max). I want these rescaled pixels to be stored always in total_img. How can I efficiently implement this using numpy arrays?

Note, min and max are simply the 1th percentile and 99th percentile values and are actually stored as floats. Should I convert them to ints for better accuracy (remember total_img is of type np.int64 - No Overflow will ever occur). Also min will most likely be negative.

I was using:

for row in total_img:
    for px in row:        
        px = 255*(min-px)/(min - max)
2

There are 2 answers

0
user2357112 On BEST ANSWER
total_img = 255*(min - total_img)/(min - max)

You literally just plug in total_img instead of px, and it does the operation elementwise. If you want to store the result into the original total_img instead of replacing it, you can slice-assign:

total_img[:] = 255*(min - total_img)/(min - max)

but note that this doesn't actually save any time or memory.

0
sparklearner On

I believe you could directly do this:

total_img = 255*(min-total_img)/(min - max)