Processing an input image using probability I have the function below which is used to process an input image using probability predicted by a CNN network model.

def interp_map(prob, zoom, width, height):
    zoom_prob = np.zeros((height, width, prob.shape[2]), dtype=np.float32)
    for c in range(prob.shape[2]):
        for h in range(height):
            for w in range(width):
                r0 = h // zoom
                r1 = r0 + 1
                c0 = w // zoom
                c1 = c0 + 1
                rt = float(h) / zoom - r0
                ct = float(w) / zoom - c0
                v0 = rt * prob[r1, c0, c] + (1 - rt) * prob[r0, c0, c]
                v1 = rt * prob[r1, c1, c] + (1 - rt) * prob[r0, c1, c]
                zoom_prob[h, w, c] = (1 - ct) * v0 + ct * v1
    return zoom_prob


At the moment, the method takes around 26-30 secs execution time. I want to reduce it, if possible. The 3 for loops consumes a lot of time, however, not sure how can I reduce it.

Any suggestions on how to optimize it?

Attributes of the input parameters:



prob.shape
Out[3]: (66, 66, 13)
width
Out[4]: 480
height
Out[5]: 360
I'm not familiar with the algorithm, so I can't say whether there is a radically different approach which will improve performance. That said:


With such short variable names it's hard to know what things are. What is c0 actually? What does the "t" in rt and ct mean? Also, the structure and semantics of prob is completely opaque. I can guess that it's related to probability in some way, but why do you only care about the third index of its shape and what is prob[r0, c0, c]?
Try compressing the calculation into a single expression to avoid reassigning so many times. This should be optimised away, but see point 4.
Instead of converting the height and width indexes into floating point numbers, can you use an integer scaling factor to avoid floating point math?
This sort of performance problem really should be profiled, but without the full context and realistic images it would amount to nothing more than guesses.