Overlay two images without losing the intensity of the color using OpenCV and Python
<p>How can i overlay two images without losing the intensity of the colors of the two images.</p>

<p>I have Image1 and Image2:</p>

<ol>
<li><a href="http://i.stack.imgur.com/kidOJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/kidOJ.png" alt="enter image description here"></a> 2. <a href="http://i.stack.imgur.com/4hCe5.png" rel="nofollow"><img src="http://i.stack.imgur.com/4hCe5.png" alt="enter image description here"></a></li>
</ol>

<p>I tried using 0.5 alpha and beta but it gives me a merged image with half the color intensity</p>

<pre><code>dst = cv2.addWeighted(img1,0.5,img2,0.5,0)
</code></pre>

<p><a href="http://i.stack.imgur.com/7dLsU.png" rel="nofollow"><img src="http://i.stack.imgur.com/7dLsU.png" alt="enter image description here"></a></p>

<p>but when i try using 1 to both alpha and beta channels, it only gives me the merged regions.</p>

<pre><code> dst = cv2.addWeighted(img1,1,img2,1,0)
</code></pre>

<p><a href="http://i.stack.imgur.com/Q2BNO.png" rel="nofollow"><img src="http://i.stack.imgur.com/Q2BNO.png" alt="enter image description here"></a></p>

<p>I have to get an output that looks like this.</p>

<p><a href="http://i.stack.imgur.com/lKu57.png" rel="nofollow"><img src="http://i.stack.imgur.com/lKu57.png" alt="enter image description here"></a></p>

<p>Actually the <code>dst</code> is created according the following formula:</p>

<pre><code>dst = src1*alpha + src2*beta + gamma
</code></pre>

<p>When you multiply your image which is an 3D array with alpha you are multiplying all the items for example for a blue pixle you have <code>[255, 0, 0]</code> and the white <code>[255, 255, 255]</code>, and when you are adding the matrices together, if you want to see the original color of your images you have to convert the white pixels to black which their values are all zero. So you can simply find the white pixels with and advanced numpy indexing <code>img1[img1[:, :, 1:].all(axis=-1)]</code> then convert them to zero.</p>

<pre><code>import cv2    

img1 = cv2.imread('img1.png')
img2 = cv2.imread('img2.png')

img1[img1[:, :, 1:].all(axis=-1)] = 0
img2[img2[:, :, 1:].all(axis=-1)] = 0

dst = cv2.addWeighted(img1, 1, img2, 1, 0)

cv2.imshow('sas', dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code></pre>

<p>Result:</p>

<p><a href="http://i.stack.imgur.com/wWqUf.png" rel="nofollow"><img src="http://i.stack.imgur.com/wWqUf.png" alt="enter image description here"></a></p>

python image opencv