c-CS50 Pset4滤波器(不太舒服)模糊函数算法问题



有关此任务的信息

当我尝试实现模糊功能时,它在图片上对我来说很好,但check50(cs50测试程序(会对我的输出发出警告。

这是我的代码

void blur(int height, int width, RGBTRIPLE image[height][width])
{
float average_red = 0;
float average_green = 0;
float average_blue = 0;
float count = 0;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
// reset values 
average_red = 0;
average_blue = 0;
average_green = 0;
count = 0;
// look for around a pixel 3x3 box
// column
for (int k = i - 1; k < i + 2; k++)
{
// row
for (int l = j - 1; l < j + 2; l++)
{
// if pixel on the top
if (k == -1)
{
// it skips a column because it is out of the border
break;
}
// if pixel is on the left side
if (l == -1)
{
// skips a row otherwise it is out of the border
continue;
}
// if pixel passes the bottom
if (k >= height)
{
break;
}
// if pixels passes the right side
if (l >= width)
{
continue;
}

// everything else
else
{
average_red += image[k][l].rgbtRed;
average_green += image[k][l].rgbtGreen;
average_blue += image[k][l].rgbtBlue;
count++;
}
}   
}
average_red /= count;
average_green /= count;
average_blue /= count;
image[i][j].rgbtRed  = round(average_red);
image[i][j].rgbtGreen = round(average_green);
image[i][j].rgbtBlue = round(average_blue);
}
}
return;
}

预期输出与我的输出在这里(模糊函数输出非常低(

它在拐角处工作良好,但其他像素值非常接近正确的输出,但不相同。感谢的任何帮助

代码需要考虑几个因素。建议:

如果得到的行号是<0或>(高度-1(则不计算该像素

如果得到的列编号是<0或>(宽度-1(则不计算该像素

因此,对于周围8个像素中的每一个,应用上述两个标准。

我解决了自己的问题,无论如何都感谢的帮助

中的问题是我的总和计算。它将结果保存在图像[i][j]中,然后再次使用该值。我将图像值复制到一个新值并用于此。这是我的代码

void blur(int height, int width, RGBTRIPLE image[height][width])
{
// copy original value to a new value to keep changing values
RGBTRIPLE copy[height][width];
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
copy[i][j] = image[i][j];
}
}
float average_red = 0.0f;
float average_green = 0.0f;
float average_blue = 0.0f;
float count = 0;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
// reset values 
average_red = 0.0f;
average_blue = 0.0f;
average_green = 0.0f;
count = 0;
// look for around a pixel 3x3 box
// column
for (int k = i - 1; k < i + 2; k++)
{
// row
for (int l = j - 1; l < j + 2; l++)
{
// if pixel on the top
if (k == -1)
{
// it skips a column because it is out of the border
break;
}
// if pixel is on the left side
else if (l == -1)
{
// skips a row otherwise it is out of the border
continue;
}
// if pixel passes the bottom
else if (k >= height)
{
break;
}
// if pixels passes the right side
else if (l >= width)
{
continue;
}

// everything else
else
{
average_red += copy[k][l].rgbtRed;
average_green += copy[k][l].rgbtGreen;
average_blue += copy[k][l].rgbtBlue;
count++;
}
}   
}
average_red /= count;
average_green /= count;
average_blue /= count;
image[i][j].rgbtRed  = round(average_red);
image[i][j].rgbtGreen = round(average_green);
image[i][j].rgbtBlue = round(average_blue);
}
}
return;
}

最新更新