c - 用 C 代码翻转图像

标签 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++;
        }
    }
}

最佳答案

您忘记在处理第一行后重置 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 = 0, right = 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;
    }
}

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

相关文章:

c++ - 在 token 中使用定义的常量

c - 在带有 gcc 的 sscanf 中使用 '-' 字符

c - Visual Studio 2010 问题中的链表

c++ - 是否可以分析程序的返回值?

c - 如何动态地将参数传递给函数?

c - 为什么标准输出不能被替换?

c - 我的链接列表没有正确添加(不断替换第 3 个位置)- c

c - 反转 5 位数字是 prog。它给出了错误的输出

c - 将最低有效位从 4 字节数组重新分配到半字节

c - 生成 4 个字节的(伪)随机数据