我需要能够通过操纵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++;
}
}
}
答案 0 :(得分:1)
处理完第一行后,您忘记重置left
和right
。
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 = n
,right = 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;
}
}