I am trying to get average merged image to show up using the following code:
import numpy as np
import cv2
import matplotlib.pyplot as plt
dolphin=cv2.imread('dolphin.png',0) #Also tried without the 0
bicycle=cv2.imread('bicycle.png',0)
The following code adds the two images and result is same as whats shown in the course. But a simple addition avg=img1+img2 doesnt work.
sumimg=cv2.add(dolphin,bicycle)
cv2.imshow('Sum image', sumimg)
Two images added together without any modification - washout areas are due to addition being over 255 for that element so the value is set to 255
cv2.waitKey(0)
cv2.destroyAllWindows()
Following code just gives me a white image. When I try to display an half intensity dolphin or cycle ...same result except for a few black dots
avgimg=cv2.add(dolphin/2,bicycle/2)
same result obtained by avgimg=img1/2+img2/2
cv2.imshow('Avg image', avgimg)
cv2.waitKey(0)
cv2.destroyAllWindows()
The Udacity course shows that if you add images by division by 2 you should get this:
So the question is: When I divide either of the image by 2, the matrix contains values below 255 and addition of two matrices also contains values below 255, why then is the resulting image a complete washout?
If you wish to add both images into one (so they both appear on the resulting image), with each one of the inputs averaged, you should use the addWeighted()
method, like this (taken from the docs):
import numpy as np
import cv2
#load your images
dolphin = cv2.imread('dolphin.png') #use 0 for grayscale
bicycle = cv2.imread('bicycle.png')
#add them with a weight, respectively, last parameter is a scalar added
dst = cv2.addWeighted(dolphin,0.7,bicycle,0.3,0)
#show
cv2.imshow('Blended Image',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
Note: As also mentioned in the previous link, it is important to notice that numpy
and OpenCV
addition are different, as numpy
has a modulo operation (%) while OpenCV
has a saturated operation (caps at a maximum), to clarify we have this extracted example from that link:
>>> x = np.uint8([250])
>>> y = np.uint8([10])
>>> print( cv2.add(x,y) ) # 250+10 = 260 => 255 , saturated
[[255]]
>>> print( x+y ) # 250+10 = 260 % 256 = 4 , modulo
[4]
Which is probably the reason why you get a white image by using the add()
method instead (all your pixels cap at 255 and show white color).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With