如何将一个图像叠加在另一个图像上? C ++

时间:2013-05-22 05:21:21

标签: c++ image overlay

我有两张RGB图像(ppm格式),我希望能够将顶部图像不是纯黑色的任何像素叠加到底部图像上。

我可以成功加载图像,保存图像,复制图像......但我无法以上述方式从两幅图像中创建图像。

我不打算包含我所拥有的所有代码,但实现这一目标的重要部分是:

struct Pixel
{
    unsigned int r;
    unsigned int g;
    unsigned int b;
}

我重载了它的==运算符以便于比较:

bool Pixel::operator==(const Pixel& other)
{
    if(r != other.r)
    {
        return true;
    }
    else if(g != other.g)
    {
        return true;
    }
    else if(b != other.b)
    {
        return true;
    }
    else
    {
        return false;
    }
}

在我的Pic课程中,我有这个方法:

Pic Pic::overlay(const Pic& top, Pixel mask)
{    
    for(int h = 0; h < height; h++)
    {
        for(int w = 0; w < width; w++)
        {
            if(!(top.pixels[h][w] ==  mask))
            {
                pixels[h][w] = top.pixels[h][w];  // pixels[][] is a Pixel array
            }
        }
    }

    return *this;
}

我的主文件有:

Pic top;
Pic bot;
Pic overlay;

Pixel mask:
mask.r = 0;
mask.g = 0;
mask.b = 0;

top.loadimage("top.ppm");  //loadimage() loads the image in and all the data
bot.loadimage("bot.ppm");  //samme thing

overlay = bot.overlay(bot, mask);
overlay.saveimage("overlay.ppm");

显然,对于Pic类,=运算符是重载的。

我遇到的问题是:

在overlay方法中,如果我如上所述保留此if语句,则顶部图像将显示在保存的文件中。如果我没有!()部分,它将显示底部图像。

如果我完全摆脱if()语句,只是尝试改变单个像素,例如:

pixels[h][w].r = pixels[h][w].r - 50;

由于显而易见的原因,保存的图像会被改变,看起来很古怪。

然而...... .b和.g对图像没有影响。

我没有想法......我已经玩了2天了,我无法弄清楚出了什么问题。除了这种叠加方法,我的程序中的所有内容都可以正常工作。

编辑:所以,我发现我的代码中存在一个问题,它又回到了我用PPM P6格式加载图像的方式。我没有将每个像素单独加载为1个字节,而是尝试将它们全部加载在一起,因此它创建了缓冲的东西,它发生在结构和二进制读取压缩...现在我能够将顶部图像的叠加层放到上面底部图像,但不是所有颜色都显示。仍然比以前更好。

这是我将overlay的嵌套for()循环修改为:

for(int h = 0; h < height; h++)
{
    for(int w = 0; w < width; w++)
    {
        if(top.pixels[h][w].r != mask.r &&
           top.pixels[h][w].g != mask.g &&
           top.pixels[h][w].b != mask.b   )
        {
            pixels[h][w].r = top.pixels[h][w].r;
            pixels[h][w].g = top.pixels[h][w].g;
            pixels[h][w].b = top.pixels[h][w].b;
        }

    }
}

显然它仍然需要工作。

1 个答案:

答案 0 :(得分:1)

这一行看起来不对:

overlay = bot.overlay(bot, mask);

不应该是:

overlay = bot.overlay(top, mask);

如果你想要一个更短的方式来编写你的平等测试,那么你可能会喜欢这个:

bool Pixel::operator==(const Pixel& other)
{
    return (r==other.r && g==other.g && b==other.b);
}

最后,既然你有一个相等运算符,那么为什么不添加和赋值('=')来保持你的编码器尽可能整洁

相关问题