因此,我一直在努力纠正我的代码以修复pset4的模糊功能,并觉得我的代码是正确的(即使效率不是最佳)。
这是我的处理方式:
首先,我循环遍历了股票图像的高度和宽度 2个循环。
将pixelcounter设置为0以计算周围的有效像素数 第i行第j个像素定义的任何特定像素。
我设置了两个for循环以遍历3x3网格状结构 有问题的像素周围。这里的变量是k和 l。 K必须在i上方1行(因此k = i-1),在i下方结束1行 (因此k <= i + 1),并且l必须位于j后面1个像素(因此l = j-1), 在j之前结束1个像素(因此l <= j + 1)
在“ 3”中所述的for循环内。我用一个“ if循环”来确定 3x3网格中是否存在迭代的像素- 指出k必须大于-1且小于“高度”,并且 同上l。
pixelcounter ++,可将其添加到周围的有效像素总数中 [i] [j]个像素。
退出混乱的循环,以确保对所有像素进行计数 pixelcolour声明为pixelcounter的大小。
我使用了与第3步中相同的循环来遍历3x3 第[i] [j]个像素周围的像素网格,如果 健康)状况。只有这次我使用z作为嵌套在for循环中 我的pixelcounter,这样它就可以遍历一维数组 pixelcolor,将其颜色存储在zth位置 如果有效,请在[k] [l]处显示RGB颜色。
我声明了3个变量-rawred,rawblue,rawgreen,目的是 只是对红色,绿色和蓝色的值求和。
让循环执行第8步。
然后我用初始化RGB分量的平均值 平均/平均蓝色/平均绿色,带有未分类的红色/原始蓝色/原始绿色的花车 由pixelcounter转换为浮点数。取整结果给出 整数值。
然后我将那些整数值输入到第[i] [j]个像素 像素。
代码如下:
void blur(int height, int width, RGBTRIPLE image[height][width])
{
// Looping through height of the image
for (int i = 0; i < height; i++)
{
// Looping through the individual pixels in each row
for (int j = 0; j < width; j++)
{
int pixelcounter = 0;
// Looping through a 3x3 pixel grid surrounding of the individual pixel - Height
for (int k = i - 1; k <= i + 1; k++)
{
// Looping through individual pixels within the kth row
for (int l = j - 1; l <= j + 1; l++)
{
// Counting the number of valid pixels in the 3x3 grid
if ((k > -1) && (k < height) && (l > -1) && (l < width))
{
pixelcounter++;
}
}
}
RGBTRIPLE pixelcolour[pixelcounter];
// Looping through array 3x3 pixel grid surrounding the individual pixel - height
for (int z = 0; z < pixelcounter; z++)
{
for (int k = i - 1; k <= i + 1; k++)
{
for (int l = j - 1; l <= j + 1; l++)
{
// Storing valid pixels in an array of valid pixels
if ((k > -1) && (k < height) && (l > -1) && (l < width))
{
pixelcolour[z] = image[k][l];
}
}
}
}
// adding all RGB components
float rawred = 0;
float rawblue = 0;
float rawgreen = 0;
for (int a = 0; a < pixelcounter; a++)
{
rawred = rawred + pixelcolour[a].rgbtRed;
rawblue = rawblue + pixelcolour[a].rgbtBlue;
rawgreen = rawgreen + pixelcolour[a].rgbtGreen;
}
// Calculating average values of RGB component
int avgred = round(rawred / (float) pixelcounter);
int avgblue = round(rawblue / (float) pixelcounter);
int avggreen = round(rawgreen / (float) pixelcounter);
// Dereferencing original pixel colour to new colour
image[i][j].rgbtRed = avgred;
image[i][j].rgbtBlue = avgblue;
image[i][j].rgbtGreen = avggreen;
}
}
return;
}
P.S:我知道可能有一种更有效的方法来执行此操作,但是我真的很想看看我在这段代码中到底出了什么问题。编译后,最终结果图片奇怪地移到了左角。没有任何东西会变得模糊,整个图片会移动一个像素,并且不应该有像素出现(杂色的随机像素)。
编辑1: 以下是我收到的错误:
:( blur correctly filters middle pixel
expected "127 140 149\n", not "145 160 169\n"
:( blur correctly filters pixel on edge
expected "80 95 105\n", not "90 106 116\n"
:) blur correctly filters pixel in corner
:( blur correctly filters 3x3 image
expected "70 85 95\n80 9...", not "70 85 95\n90 1..."
:( blur correctly filters 4x4 image
expected "70 85 95\n80 9...", not "70 85 95\n90 1..."
答案 0 :(得分:1)
解决了仍然困扰我的问题。我意识到模糊功能受到周围模糊像素的影响,解决方案是使用临时数组创建图像的副本。