c - 旋转存储像素的矩阵

标签 c for-loop matrix multidimensional-array rotation

我有一个存储像素的矩阵,如下所示:

(0, 0, 255) (0, 255, 0) (255, 0, 0)
(0, 128, 0) (0, 255, 0) (0, 128, 0) 

行数为 2,列数为 3 [但实际上是 9,因为像素 r、g、b 值] 我必须旋转它们,这样我才能得到:

(0, 128, 0) (0, 0, 255) 
(0, 255, 0) (0, 255, 0)
(0, 128, 0) (255, 0, 0)

有 3 行和 2 列。我还有一个限制:不允许使用结构体,只能使用 for 循环。尝试了多种组合,但通常没有一个是正确的。任何帮助将不胜感激。

最佳答案

您需要将您的矩阵视为由 block 构建的。它包含 BLOCK_MATRIX_M x BLOCK_MATRIX_N block 。每个 block 包含 BLOCK_M x BLOCK_N 元素。

您需要旋转 block 矩阵,但保持 block 本身不变:

#define BLOCK_MATRIX_M          2
#define BLOCK_MATRIX_N          3
#define BLOCK_M                 1
#define BLOCK_N                 3

#define MATRIX_M                (BLOCK_MATRIX_M * BLOCK_M)
#define MATRIX_N                (BLOCK_MATRIX_N * BLOCK_N)
#define ROTATED_MATRIX_M        (BLOCK_MATRIX_N * BLOCK_M)
#define ROTATED_MATRIX_N        (BLOCK_MATRIX_M * BLOCK_N)

int matrix[MATRIX_M][MATRIX_N] = {
    { 0, 0, 255, 0, 255, 0, 255, 0, 0 },
    { 0, 128, 0, 0, 255, 0, 0, 128, 0 }
};

int rotated_matrix[ROTATED_MATRIX_M][ROTATED_MATRIX_N];

// iterate over the blocks
for (int i = 0; i < BLOCK_MATRIX_M; i++) {
    for (int j = 0; j < BLOCK_MATRIX_N; j++) {
        int rotated_i = j;
        int rotated_j = BLOCK_MATRIX_M - i - 1;

        // iterate over the elements of a block
        for (int k = 0; k < BLOCK_M; k++) {
            for (int l = 0; l < BLOCK_N; l++) {
                int x = i * BLOCK_M + k;
                int y = j * BLOCK_N + l;
                int rotated_x = rotated_i * BLOCK_M + k;
                int rotated_y = rotated_j * BLOCK_N + l;

                rotated_matrix[rotated_x][rotated_y] = matrix[x][y];
            }
        }
    }
}

关于c - 旋转存储像素的矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40946852/

相关文章:

javascript - 如何编写一个 for 循环,从中断处开始计算?

java - 奥赛罗 - 寻找可用选项的算法

matrix - 将所有数据文件加载到 Octave 中的目录中

c - 调试无效的 free()

c - 在链表上存储字符串的元素

javascript - 如果 for 循环返回 null javascript

javascript - For 循环 Canvas 动画

c - 如何获取文件中的元素数量?

c - DisplayContext、displaySurface 和 displayBuffer 之间的区别?

c - 变量乘法的优化