Import Libraries


In [1]:
import cv2

In [2]:
import matplotlib.pyplot as plt

Read Images


In [3]:
img1 = cv2.imread('demo1.jpg', cv2.IMREAD_GRAYSCALE)

In [4]:
img2 = cv2.imread('nature.jpg', cv2.IMREAD_GRAYSCALE)

In [5]:
plt.figure(figsize=(20,15))


Out[5]:
<matplotlib.figure.Figure at 0x7f0ba5b3bc88>

In [6]:
plt.subplot(1,2,1)


Out[6]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f0ba5b3bda0>

In [7]:
plt.imshow(img1, cmap='gray')


Out[7]:
<matplotlib.image.AxesImage at 0x7f0ba58053c8>

In [8]:
plt.subplot(1,2,2)


Out[8]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f0ba5805390>

In [9]:
plt.imshow(img2, cmap='gray')


Out[9]:
<matplotlib.image.AxesImage at 0x7f0ba57847f0>

In [10]:
plt.show()


1. Add Images


In [11]:
plt.figure(figsize=(20,15))


Out[11]:
<matplotlib.figure.Figure at 0x7f0ba5742cf8>

In [12]:
plt.subplot(1,3,1)


Out[12]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f0ba5742f98>

In [13]:
img_sum = img1 + img2

plt.imshow(img_sum, cmap='gray')


In [14]:
print('Image type:', img_sum.dtype)


Image type: uint8

In [15]:
plt.title('1. A + B')


Out[15]:
<matplotlib.text.Text at 0x7f0ba56de128>

In [16]:
plt.imshow(img_sum, cmap='gray')


Out[16]:
<matplotlib.image.AxesImage at 0x7f0ba1604e48>
1. The resultant image looks highly distorted, this is due to the fact that img_sum is a unit8 image i.e. 0-255 pixel values. But when added img1 and img2, then for addition greater than 255 is lowered back to 255. This makes the image unrecognizable.

2. Add Images using average


In [17]:
plt.subplot(1,3,2)


Out[17]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f0ba1604c50>

In [18]:
img_avg = (img1 + img2)/2

In [19]:
plt.title('2. (A + B)/2')


Out[19]:
<matplotlib.text.Text at 0x7f0ba15cf860>

In [20]:
plt.imshow(img_avg, cmap='gray')


Out[20]:
<matplotlib.image.AxesImage at 0x7f0ba15d77b8>
2. Still image is distorted, because values of img1 and img2 add first, then round back to 255 and then reduced to half. This makes even the highest sum intensity pixel values equal to 128.

3. Add image using altered average


In [21]:
plt.subplot(1,3,3)


Out[21]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f0ba15d7710>

In [22]:
img_avg_alt = img1/2 + img2/2

In [23]:
plt.title('3. A/2 + B/2')


Out[23]:
<matplotlib.text.Text at 0x7f0ba15a75f8>

In [24]:
plt.imshow(img_avg_alt, cmap='gray')


Out[24]:
<matplotlib.image.AxesImage at 0x7f0ba1553710>

In [25]:
plt.show()


3. Finally!!! a bit better image addition achieved.