【发布时间】:2020-04-23 18:02:16
【问题描述】:
我的模糊功能表现异常。我从 check50 重新创建了 3x3 位图,以便从我的测试中获得更近似的结果,但由于某种原因,每个右边缘或下边缘像素都无法正常工作。
在调试时,我发现出于某种原因,我的 for 循环运行不正常。我将在下面展示我的代码和示例。
代码:
// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width])
{
RGBTRIPLE temp[height][width]; // Declares temporary structure to avoid overwriting of original values while running loops
// For loop to set the value of i, rows or height
for (int i = 0; i < height; i++)
{
// For loop to set the value of j, columns or width
for (int j = 0; j < width; j++)
{
float counter = 0.0;
int sumRed = 0;
int sumGreen = 0;
int sumBlue = 0;
// For loop to set the value of k, to get surrounding pixels
for (int k = -1; k < 2; k++)
{
for (int m = -1; m < 2; m++)
{
if ((i - k) >= 0 && (i - k) < height && (j - m) >= 0 && (j - m) < width)
{
sumRed = sumRed + image[i - k][j - m].rgbtRed; // Adds the value of verified pixel to the sum
sumGreen = sumGreen + image[i - k][j - m].rgbtGreen;
sumBlue = sumBlue + image[i - k][j - m].rgbtBlue;
counter++; // To get the average
}
}
}
temp[i][j].rgbtRed = round(sumRed / counter); // Sets new color based on average of surrounding pixels
temp[i][j].rgbtGreen = round(sumGreen / counter);
temp[i][j].rgbtBlue = round(sumBlue / counter);
}
}
// Start new loops to switch original values with temp values
for (int i = 0; i < height - 1; i++)
{
for (int j = 0; j < width - 1; 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;
}
}
return;
}
这是 output.
作为我在调试过程中发现的一个示例,假设:
i = 0
j = 2
k = 0
m = 0
这里,不是sumRed 获取image[0 - 0][2 - 0] (RGB 70, 80, 90) 的值,而是从image[2][2] (RGB 240, 250, 255) 获取值。
我还没有测试其他错误案例,但我想那里正在发生类似的事情。
任何帮助将不胜感激。
【问题讨论】:
-
如果您使用
row和col而不是i和j,您的代码会更容易阅读。 -
如果
counter是int可能会更好。然后,执行:round((double) sumRed / counter),但是,输出单元只有八位。您可能需要:sumRed = round((double) sumRed / counter); temp[i][j].rgbtRed = (sumRed < 255) ? sumRed : 255;这是饱和度数学。否则,当您分配给 8 位单元时,它是模数学,相当于sumRed % 256。这将产生257 --> 1(接近黑色)而不是257 --> 255(亮红色)