Your complete implementation relies on 2D images as of now. Nevertheless, then better access img.shape in the loop below or create an array. It should be faster.