Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV python image washout

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)

Bycycle - original Dolphin - original

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.

Simple addition - washout areas

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

Adding images with division by 2

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: From Udacity course - two images added after dividing by 2

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?

like image 992
Omi Avatar asked Jul 11 '17 21:07

Omi


1 Answers

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).

like image 89
DarkCygnus Avatar answered Oct 20 '22 15:10

DarkCygnus