我需要能够通过操作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++;
        }
    }
}

最佳答案

在处理第一行之后,您忘记重置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


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

关于c - 用C代码翻转图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26169374/

10-16 04:53