Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polar to rectangular and back

I'm a little stuck. I'm trying to achieve a basic polar to rectangular conversion to match that of Photoshop's but I'm not getting the same results.

Converting from rectangular to polar matches Photoshop's but going from polar back to rectangular does not.

You can see in this image the differences between Photoshop's and mine: Polar Conversion

float a, b, ang, dist;
int px, py;
const PI=3.141592653589793;

// Convert from cartesian to polar
for (y=y_start; y<y_end; ++y)
{
    for (x=x_start; x<x_end; ++x)
    {
        a = (float)(x-X/2);
        b = (float)(y-Y/2);

        dist = (sqr(a*a + b*b)*2.0);

        ang = atan2(b,-a)*(58);
        ang = fmod(ang + 450.0,360.0);

        px = (int)(ang*X/360.0);
        py = (int)(dist);

        pset(x, y, 0, src(px,py,0));
        pset(x, y, 1, src(px,py,1));
        pset(x, y, 2, src(px,py,2));
    }
}

// Convert back to cartesian
for (y=y_start; y<y_end; ++y)
{
    for (x=x_start; x<x_end; ++x)
    {

        ang = ((float)x/X)*PI*2.0;

        dist = (float)y*0.5;

        px = (int)(cos(ang)*dist)+X/2;
        py = (int)(sin(ang)*dist)+Y/2;

        pset(x, y, 0, pget(px,py,0));
        pset(x, y, 1, pget(px,py,1));
        pset(x, y, 2, pget(px,py,2));
    }
}

This is my code. I'm sure I've messed something up in the polar to cartesian. The language is based off C.

What am I doing wrong? Any suggestions?

like image 456
Rich95 Avatar asked Nov 01 '22 19:11

Rich95


1 Answers

There are two issues with your polar-to-cartesian transformation:

  • The axes of the coordinate system you use to define angles are pointing right (x) and down (y) while you used a coordinate system with upwards- (x) and left-pointing (y) axes for your cartesian-to-polar transformation. The code to convert the angle to cartesian should be (I've added a bit of rounding)

    px = round(-sin(ang)*dist + X/2.)
    py = round(-cos(ang)*dist + Y/2.)
    

    With that code you move from red to green to blue instead of from gray to blue to green in the final picture when increasing the x coordinate there.

  • Assuming that pget and pset operate on the same bitmap, you're overwriting your source image. The loop construct takes you outward along concentric circles around the center of the source image while filling the target line by line, top to bottom. at some point the circles and the lines start to overlap and you start reading the data you modified earlier (happens at the apex of the parabola-like shape). It gets even more convoluted because at some point you start reading the transform of that modified data, so that it is effectively transformed again (I guess that causes the irregular triangular region on the right).
like image 124
Roland W Avatar answered Nov 15 '22 04:11

Roland W