look at this picture

I am trying to write a script that asks user for
N sections they want to have and then divide
a square (or rectangle) image into that many NxN squares (or rectangles).
I thought if i loop from 1 to N for Y and then inside that loop i loop from 1 to N for X
selecting the square or rectangle..
using math
I can perspective it into the image shown above...
but i am stuck at the math...
so basically I got cos(180 degrees) down to cos(0 degrees) ..i put degrees here but i actually convert it to radians before calling cos...
But I am still stumpled at the math to get the mapping of these squares/rectangles into the shape shown above.
i am assuming if i have the math down, a rectangle image will turn to an oval shape and a square will turn into a circle...
anyone can offer any help on the math behind this?