How to Merge two images not overlay?

I have 2 transparent images (.png) of the same size.
Photo 1 contains red characters, photo 2 contains black characters.
My task is to take photo 1 on top of photo 2.
Thus, the red characters will obscure (overwrite) the black characters.
How to do this?

Mat background = imread(png1, IMREAD_UNCHANGED); //black text
Mat img2 = imread(png2, cv::IMREAD_UNCHANGED); //red text

img2.copyTo(img1); <–not working.

Thanks you!

read function for compositing two images that is aware of alpha-channel · Issue #20780 · opencv/opencv · GitHub

I don’t remember if I discussed “keeping the alpha” of the composite. in some SO answer or comment, I might have.

the equations aren’t complicated but one has to pay attention to get them right.

working in premultiplied space is a lot more natural (no dangerous divisions), so I’ll express this as premultiplied. collapsing two transparent layers into one, I think the contributions are:

  A_merged =   A_top + (1 - A_top) *   A_bottom
RGB_merged = RGB_top + (1 - A_top) * RGB_bottom

I didn’t test those equations. might be wrong. test them.

Hi, Thanks for the reply,
the OverlayImage function is very close to what I expected but I wanted to override it completely.
I tried your code @crackwitz, but got the exception at:

Mat m = img2 + (1 - img2) * background;

MatExpr::operator Mat() const
    Mat m;
    op->assign(*this, m); <--error
    return m;
Unhandled exception at 0x00007FF90B98FC8A in **.exe: Microsoft C++ exception: cv::Exception at memory location 0x0000003CC71FDF70.

is there a way fix this?

I tried this approach but the resulting images were quite low quality.

if (srcPx <1)
				src->data[y * src->step + src->channels() * x + c] = overlayPx;
				src->data[y * src->step + src->channels() * x + c] = srcPx;

Using overlayimage will give quite good output but is it possible to increase the quality further?

please test this link