簡體   English   中英

CS50 pset4 中的模糊 function 無法正常工作

[英]Blur function in CS50 pset4 not fully working

我花了兩天時間試圖糾正我的 function 模糊給定圖像,但盡管進行了廣泛的校對,它現在只適用於極端情況。 對於 rest,它會在 RGB 值中產生 2-20+ 的差異。

該任務是哈佛 CS50 課程的一部分(有關 pset4 https://cs50.harvard.edu/x/2020/psets/4/filter/less/的更多信息)。

我已經閱讀了我可以在網上找到的所有內容,並嘗試使用這些技巧,例如將新的 RGB 值與浮點數相除、將結果直接復制回原始圖像、調整 if 條件,但這並沒有幫助,我仍然不知道是什么錯誤的。 非常感謝幫助,謝謝!

 // Blur image
 void blur(int height, int width, RGBTRIPLE image[height][width])
 {
    float new_red, new_blue, new_green;
    new_red = new_blue = new_green = 0;

    int count = 0;

    // Copy the image
    RGBTRIPLE temp[height][width];

    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            temp[i][j] = image[i][j];
        }
    }

    // Loop through height
    for (int i = 0; i < height; i++)
    {
        // Loop through width
        for (int j = 0; j < width; j++)
        {
            // Loop through rows around a pixel
            for (int k = -1; k <= 1; k++)
            {
                // Loop through columns around a pixel
                for (int m = -1; m <= 1; m++)
                {
                    if (i + k >= 0 && i + k < height && j + m >= 0 && j + m < width)
                    {
                        count++;
                        new_red += temp[i + k][j + m].rgbtRed;
                        new_blue += temp[i + k][j + m].rgbtBlue;
                        new_green += temp[i + k][j + m].rgbtGreen;
                    }
                }
            }

            temp[i][j].rgbtBlue = round(new_blue / count);
            temp[i][j].rgbtRed = round(new_red / count);
            temp[i][j].rgbtGreen = round(new_green / count);
        }

    }

    // Copy the blurred image to original file
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            image[i][j] = temp[i][j];
        }
    }

    return;
}

我假設您要為每個像素重置計數、new_blue、new_red 和 new_green。 在您的代碼中,這些值會隨着您處理圖像而繼續增長。

// Loop through height
for (int i = 0; i < height; i++)
{
    // Loop through width
    for (int j = 0; j < width; j++)
    {
        count = new_blue = new_red = new_green = 0;

在調試時你可能會發現這一點的一種方法是在進行除法和賦值之前打印出每個像素的這些變量的值。 您可能已經注意到計數值太高了。

我相信另一個問題是您正在模糊臨時圖像中的像素。 當您模糊一個像素時,您將使用其上方像素已經模糊的值。 相反,您可能想在最里面的循環中使用原始圖像:

                    new_red += image[i + k][j + m].rgbtRed;
                    new_blue += image[i + k][j + m].rgbtBlue;
                    new_green += image[i + k][j + m].rgbtGreen

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM