在另一个图像的顶部不透明地层叠图像。 - 开放式简历

Layer image with opacity over the top of another image. - OpenCV

编辑

任何有类似问题的人 - 我找到了另一个 SO 答案 here 有一个很好的 python 解决方案,利用了 NumPy 的速度。

请考虑以下问题:

我有两张图片,大小相同。一个是具有不同不透明度层的红色方块:

第二个,蓝色方块,比红色方块小,没有不透明度,周围是白色。

我正在为这个项目使用 OpenCV 的 python 绑定,到目前为止(在阅读了水印 here 我有这个:

redSquare = cv2.imread('redSquare.png', cv2.IMREAD_UNCHANGED)
(rH, rW) = redSquare.shape[:2]

blueSquare = cv2.imread('blueSquare.png')
(h, w) = blueSquare.shape[:2]

blueSquare = np.dstack([blueSquare, np.ones((h,w), dtype = 'uint8') * 255])
overlay = np.zeros((h,w,4), dtype = 'uint8')
overlay[0:rH, 0:rW] = redSquare
output = blueSquare .copy()
cv2.addWeighted(overlay, 0.5, output, 0.5, 0, output)

cv2.imwrite('imageAdded.png', output)

产生以下输出:

然而想要的效果是:

现在我明白了通过使用加权相加,我每个都使用 0.5,当我真的想要每个 1.0,但是当我尝试增加两者的权重时,只有一个增加而另一个减少。

如果有人对我如何实现这一点有一些了解,最好是 Python,但如果你知道 C++ 中的方法,我相信我可以复制它。

谢谢。

这里的 C++ 代码给出了您想要的结果。

// http://jepsonsblog.blogspot.be/2012/10/overlay-transparent-image-in-opencv.html
// https://gist.github.com/maximus5684/082f8939edb6aed7ba0a

#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "iostream"

using namespace cv;
using namespace std;

void overlayImage(Mat* src, Mat* overlay, const Point& location)
{
    for (int y = max(location.y, 0); y < src->rows; ++y)
    {
        int fY = y - location.y;

        if (fY >= overlay->rows)
            break;

        for (int x = max(location.x, 0); x < src->cols; ++x)
        {
            int fX = x - location.x;

            if (fX >= overlay->cols)
                break;

            double opacity = ((double)overlay->data[fY * overlay->step + fX * overlay->channels() + 3]) / 255;

            for (int c = 0; opacity > 0 && c < src->channels(); ++c)
            {
                unsigned char overlayPx = overlay->data[fY * overlay->step + fX * overlay->channels() + c];
                unsigned char srcPx = src->data[y * src->step + x * src->channels() + c];
                src->data[y * src->step + src->channels() * x + c] = srcPx * (1. - opacity) + overlayPx * opacity;
            }
        }
    }
}

int main( int argc, char** argv )
{
    Mat overlay = imread("ZuWDz.png",IMREAD_UNCHANGED);
    Mat underlay = imread("CtBAe.png",IMREAD_UNCHANGED);

    if( underlay.empty() || overlay.empty() )
    {
        return -1;
    }

    overlayImage( &underlay, &overlay, Point() );
    imshow("underlay result",underlay);

    waitKey();

    return 0;
}