C语言图像模糊函数异常:整行呈现相同模糊效果的问题排查
图像模糊函数异常原因分析及修复
核心错误点
1. 邻接像素列坐标计算错误
代码中计算邻接像素的列坐标时,错误地使用了行索引i:
int nbrY = i + y; // 错误!
正确的应该是用当前像素的列索引j加上偏移量y:
int nbrY = j + y; // 正确
这个错误导致同一行的所有像素,都在计算同一列附近的像素RGB平均值,最终整行的模糊结果完全一致。
2. 模糊值赋值时机错误
你将temp[i][j]的赋值逻辑放在了行偏移的x循环内部,每循环一次x就会覆盖一次temp的值。正确的逻辑是:等x和y的两层循环都遍历完所有邻接像素,完成RGB值的累加和计数后,再计算平均值并赋值给temp。
修正后的完整代码
// Blur image void blur(int height, int width, RGBTRIPLE image[height][width]) { RGBTRIPLE temp[height][width]; for(int i = 0; i < height; i++) { for(int j = 0; j < width; j++) { float totalRed, totalGreen, totalBlue; totalRed = totalGreen = totalBlue = 0; float counter = 0.00; // 遍历周围3x3的邻接像素 for(int x = -1; x < 2; x++) { for(int y = -1; y < 2; y++) { int nbrX = i + x; int nbrY = j + y; // 修复:用j代替i // 检查是否超出图像边界 if (nbrX < 0 || nbrX > (height - 1) || nbrY < 0 || nbrY > (width - 1)) { continue; } totalRed += image[nbrX][nbrY].rgbtRed; totalGreen += image[nbrX][nbrY].rgbtGreen; totalBlue += image[nbrX][nbrY].rgbtBlue; counter++; } } // 修复:将赋值移到两层循环外部 temp[i][j].rgbtRed = round(totalRed / counter); temp[i][j].rgbtGreen = round(totalGreen / counter); temp[i][j].rgbtBlue = round(totalBlue / counter); } } // 将临时数组的结果复制回原图像 for(int i = 0; i < height; i++) { for(int j = 0; j < width; j++) { image[i][j].rgbtRed = temp[i][j].rgbtRed; image[i][j].rgbtGreen = temp[i][j].rgbtGreen; image[i][j].rgbtBlue = temp[i][j].rgbtBlue; } } }
内容的提问来源于stack exchange,提问作者Konvas
相关产品推荐
相关产品推荐

