在C / C ++中用alpha值覆盖像素

时间:2014-11-16 11:21:04

标签: c++ overlay alpha pixels blend

我尝试使用透明胶片在完全不透明的图像上创建算法来覆盖图像。 在下一个样本中,我有一个完全不透明的背面图像,而前面的图像是一个带有漫反射边缘的蓝色框架。 我遇到的问题是我的实现错误地覆盖了产生暗像素的半透明区域。

enter image description here

这是我的实施:

#define OPAQUE 0xFF
#define TRANSPARENT 0
#define ALPHA(argb)  (uint8_t)(argb >> 24)
#define RED(argb)    (uint8_t)(argb >> 16)
#define GREEN(argb)  (uint8_t)(argb >> 8)
#define BLUE(argb)   (uint8_t)(argb)
#define ARGB(a, r, g, b) (a << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff)
#define BLEND(a, b, alpha) ((a * alpha) + (b * (255 - alpha))) / 255

void ImageUtil::overlay(const uint32_t* front, uint32_t* back, const unsigned int width, const unsigned int height)
{
    const size_t totalPixels = width * height;

    for (unsigned long index = 0; index < totalPixels; index++)
    {
        const uint32_t alpha = ALPHA(*front);

        const uint32_t R = BLEND(RED(*front), RED(*back), alpha);
        const uint32_t G = BLEND(GREEN(*front), GREEN(*back), alpha);
        const uint32_t B = BLEND(BLUE(*front), BLUE(*back), alpha);

        *backPixels++ = ARGB(OPAQUE, R , G, B);
        *frontPixels++;
    }
}

更新

测试图像文件

DOWNLOAD

1 个答案:

答案 0 :(得分:0)

根据 gman interjay 的评论提示,我进一步调查了,是的,数据正在加载预乘的alpha。 这会在混合时产生变暗。解决方案是取消前面像素的倍增,最后我得到了预期的结果。

Unmultiply formula:

((0xFF * color) / alpha)

最终代码:

#define OPAQUE 0xFF;
#define TRANSPARENT 0;

#define ALPHA(rgb) (uint8_t)(rgb >> 24)
#define RED(rgb)   (uint8_t)(rgb >> 16)
#define GREEN(rgb) (uint8_t)(rgb >> 8)
#define BLUE(rgb)  (uint8_t)(rgb)

#define UNMULTIPLY(color, alpha) ((0xFF * color) / alpha)
#define BLEND(back, front, alpha) ((front * alpha) + (back * (255 - alpha))) / 255
#define ARGB(a, r, g, b) (a << 24) | ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | (b & 0xFF)

void ImageUtil::overlay(const uint32_t* front, uint32_t* back, const unsigned int width, const unsigned int height)
{
    const size_t totalPixels = width * height;

    for (unsigned long index = 0; index < totalPixels; index++)
    {
        const uint32_t frontAlpha = ALPHA(*front);

        if (frontAlpha == TRANSPARENT)
        {
            *back++;
            *front++;
            continue;
        }

        if (frontAlpha == OPAQUE)
        {
            *back++ = *front++;
            continue;
        }

        const uint8_t backR = RED(*back);
        const uint8_t backG = GREEN(*back);
        const uint8_t backB = BLUE(*back);

        const uint8_t frontR = UNMULTIPLY(RED(*front), frontAlpha);
        const uint8_t frontG = UNMULTIPLY(GREEN(*front), frontAlpha);
        const uint8_t frontB = UNMULTIPLY(BLUE(*front), frontAlpha);

        const uint32_t R = BLEND(backR, frontR, frontAlpha);
        const uint32_t G = BLEND(backG, frontG, frontAlpha);
        const uint32_t B = BLEND(backB, frontB, frontAlpha);

        *back++ = ARGB(OPAQUE, R , G, B);
        *front++;
    }
}