reflect图像翻转算法未正确生效却通过部分测试的技术求助
图像水平翻转代码问题排查
我无法理解为何这段reflect代码能通过测试系统的部分用例,但实际处理图像时输出与原图完全一致。测试报告如下:
:) reflect correctly filters 1x2 image
:) reflect correctly filters 1x3 image
:) reflect correctly filters image that is its own mirror image
:) reflect correctly filters 3x3 image
:( reflect correctly filters 4x4 image expected "100 110 120\n7...", not "10 20 30\n70 8..." (except this one)
处理后输出图像与原图无差异。
问题代码
void reflect(int height, int width, RGBTRIPLE image[height][width]) { for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { RGBTRIPLE temp; if( j != width - j) { temp = image[i][j]; image[i][j] = image[i][width - j - 1]; image[i][width - j - 1] = temp; } if( j == width - j - 1) { j = width; } } } return; }
问题分析
- 重复交换导致图像复原:内层循环遍历所有列时,交换
j和width-j-1位置的像素后,当循环走到width-j-1的位置时,会再次执行交换操作,把像素换回去,最终图像和原图一致。比如4x4图像,j=0时交换0和3,j=3时又交换3和0,等于没做任何修改。 - 终止条件逻辑失效:判断
j == width - j -1仅适用于奇数宽度的图像(如3x3),但偶数宽度(如4x4)不存在这样的j值,导致内层循环会完整遍历所有列,触发重复交换。
修复方案
内层循环只需遍历到图像宽度的一半,避免重复交换:
void reflect(int height, int width, RGBTRIPLE image[height][width]) { for (int i = 0; i < height; i++) { // 仅遍历前半列,避免重复交换操作 for (int j = 0; j < width / 2; j++) { RGBTRIPLE temp = image[i][j]; image[i][j] = image[i][width - j - 1]; image[i][width - j - 1] = temp; } } return; }
修复说明
- 循环条件改为
j < width / 2:对于偶数宽度(如4),j遍历0、1,对应交换0和3、1和2,刚好完成整行翻转;对于奇数宽度(如3),j遍历0,交换0和2,中间列无需处理,符合预期。 - 移除原代码中错误的终止判断逻辑,简化代码同时避免逻辑漏洞。
内容的提问来源于stack exchange,提问作者Mandar Gurav
相关产品推荐
相关产品推荐

