Adjusted code attached. I also repaired an error in it (it was confusing x and y).
The adjusted code does not require that the image is square, or an exact power of 2. However, it might ignore parts of the image outside the last full square power of 2 size.
The adjusted code uses baby.jpg as the same image to read, which is 3600 x 2450 or so. The program slows down a lot after i = 9.