在C代码中翻转图像

时间:2014-10-02 20:45:56

标签: c

我需要能够通过操纵png文件中的像素在c中水平翻转图像。尽管我尝试过,但经过测试,我的算法什么也没做。我还需要能够垂直地执行此操作,但这是我的水平翻转代码:

void flip_horizontal( uint8_t array[], unsigned int cols, unsigned int rows ) {
    unsigned int left = 0;
    unsigned int right = cols;

    for(int r = 0; r < rows; r++){  
        while(left != right && right > left){
            int temp = array[r * cols + left];
            array[(r * cols) + left] = array[(r * cols) + cols - right];
            array[(r * cols) + cols - right] = temp;
            right--;
            left++;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

处理完第一行后,您忘记重置leftright

void flip_horizontal( uint8_t array[], unsigned int cols, unsigned int rows ) {
    unsigned int left = 0;
    unsigned int right = cols;

    for(int r = 0; r < rows; r++){  
        while(left != right && right > left){
            int temp = array[r * cols + left];
            array[(r * cols) + left] = array[(r * cols) + cols - right];
            array[(r * cols) + cols - right] = temp;
            right--;
            left++;
        }

        // Reset left and right after processing a row.
        left = 0;
        right = cols;
    }
}

<强>更新

您正在计算错误的指数。看一下以下一行。

            array[(r * cols) + left] = array[(r * cols) + cols - right];

left = 0right = cols

(r * cols) + left == (r * cols) + cols - right

left = nright = cols - n,仍然

(r * cols) + left == (r * cols) + cols - right

这就是为什么你没有看到图像的任何变化。

尝试:

void flip_horizontal( uint8_t array[], unsigned int cols, unsigned int rows ) {
    unsigned int left = 0;
    unsigned int right = cols-1;

    for(int r = 0; r < rows; r++){  
        while(left != right && right > left){
            int index1 = r * cols + left;
            int index2 = r * cols + right;

            int temp = array[index1];
            array[index1] = array[index2];
            array[index2] = temp;
            right--;
            left++;
        }

        // Reset left and right after processing a row.
        left = 0;
        right = cols-1;
    }
}