Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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)
share|improve this question
1  
you should not shadow builtins such as min/max ... just an aside totally unrelated to your problem – Joran Beasley Jun 24 '15 at 23:00
up vote 3 down vote accepted
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.

share|improve this answer

I believe you could directly do this:

total_img = 255*(min-total_img)/(min - max)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.