Abstracted more from watershed kernel so the same function can be used in the 2D and 3D loops.