The rest of the function seems to work for N-D images, but here you assume 2-D images, don't you?