Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opencv Different Outputs with imshow and imwrite

I read two images into numpy arrays using open cv. I tried two different equations for adding these images

Equation 1: img = (img_one/2) + (img_two/2)

Equation 2: img = (0.5*img_one) + (0.5*img_two)

Equation 1 outputs image as expected, but Equation 2 outputs an image completely unexpected.

Here's my code (python2):

import numpy as np
from cv2 import *

tiger = imread('tiger.jpg')
nature = imread('nature.jpg')

mul_img = 0.5*tiger + 0.5*nature
div_img = tiger/2 + nature/2

imshow('mul_image', mul_img) 
imshow('div_image', div_img)
waitKey(0)
destroyAllWindows()

Original images used:

Tiger image

enter image description here

The images generated are as follows:

division image

multiplication image

like image 897
Prabhat Doongarwal Avatar asked Jan 28 '26 04:01

Prabhat Doongarwal


1 Answers

The difference of output is not due to using operator * or /, but due to cv2.imshow(), In the first case when you use mul_img = 0.5*tiger + 0.5*nature The dtype of returned matrix implicitly converted to floar32, because you used floating number as one of the operands. But in the second case, The dtype of both the matrix and number is int only, So the dtype of the returned matrix from div_img = tiger/2 + nature/2 would be of type uint8.

Now cv2.imshow() has some serious issues while rendering 4-channel RGBA images, it ignores the alpha channel or rendering Mat with floating point numbers, etc. Now you are left with 2 solutions:

  • Use cv2.imwrite() to debug the images:

    cv.imwrite("path/to/img.jpg", mul_img)
    
  • Convert the image to uint8 before cv2.imshow()

    mul_img = mul_img.astype(np.uint8)
    
like image 98
ZdaR Avatar answered Jan 29 '26 19:01

ZdaR