开发者

index conversion: row-major to cartesian coordinates (e.g., pixels)

i need to transform/access memory indices to and from row-major and cartesian* layouts.

if it helps you imagine the use or problem: the case is accessing pixels (reading/manipulation) stored in different mem开发者_运维问答ory layouts.

a small program to illustrate:

#include <cassert>
#include <iostream>

/*
memory layout:
    row major:
        0 1 2 3
        4 5 6 7
        8 9 10 11

    cartesian:
        2 5 8 11
        1 4 7 10
        0 3 6 9
*/

unsigned rowmaj_to_cartesian(const unsigned& i) {
    return ?;
}

int main(int argc, const char* argv[]) {

    const unsigned W(4);
    const unsigned H(3);
    const unsigned A(W * H);

    unsigned a[A];

    for (size_t i(0); i < A; ++i) {
        /* populate a[] with row-major layout */
        a[i] = i;
    }

    for (size_t i(0); i < A; ++i) {
        /* convert the index values to cartesian layout */
        a[i] = rowmaj_to_cartesian(a[i]);
        std::cout << i << ": " << a[i] << "\n";
    }

    /* sanity check the results */
    assert(a[0] == 2);
    assert(a[1] == 5);
    assert(a[2] == 8);
    assert(a[3] == 11);

    assert(a[4] == 1);
    assert(a[5] == 4);
    assert(a[6] == 7);
    assert(a[7] == 10);

    assert(a[8] == 0);
    assert(a[9] == 3);
    assert(a[10] == 6);
    assert(a[11] == 9);

    return 0;
}

it's a simple problem, but i haven't able to figure it out (or find an answer to by searching).

thanks for your help!

details:

1) sorry, external libraries are not an option. (maybe the example was bad: stl is also not an option)

2) what i am referring to as cartesian is not column major.

*perhaps there is a better term for this?


convert from your original indexing to row column: r = i/WIDTH, c = i%WIDTH then to the cartesian indexing: c*HEIGHT + (HEIGHT-1-r).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜