索引转换:行主序到笛卡尔坐标的转换(例如,像素)

3

我需要将内存索引从行主序和笛卡尔布局之间进行转换/访问。

如果这有助于您想象使用或问题:该情况是访问以不同内存布局存储的像素(读取/操作)。

一个小程序以说明:

#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;
}

这是一个简单的问题,但我无法解决(或通过搜索找到答案)。

谢谢你的帮助!

细节:

1)很抱歉,外部库不是一个选项。(也许示例不好:stl 也不是一个选项)

2)我所指的笛卡尔(Cartesian)不是列主序(column major)。

*也许有一个更好的术语来形容这个?

1个回答

4

将原始索引转换为行列索引: r = i/WIDTH, c = i%WIDTH 然后转换为笛卡尔索引:c*HEIGHT + (HEIGHT-1-r)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接