旋转存储像素的矩阵

时间:2016-12-03 10:41:02

标签: 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列[但由于像素r,g,b值实际为9] 我必须旋转它们才能获得:

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

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

1 个答案:

答案 0 :(得分:1)

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

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

#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];
            }
        }
    }
}
相关问题