Siddhartha rao
Siddhartha rao

Reputation: 487

matlplotlib with opencv gives a different image with the same pixel values

I've been trying to modify the pixels of an image slightly, but the colors are getting distorted. So, I multiplied every pixel with 1 and saw the result.enter image description here

Here's my code

import numpy as np
from matplotlib import pyplot as plt
import cv2

mud1 = cv2.imread('mud.jpeg')
print mud1.shape

mask = np.random.random_integers(1,1,size=(81,81,3))

print mask.shape
print mask[21][21][2]
print mud1[21][21][2]
mud1new = np.multiply(mud1,mask)
print mud1new[21][21][2]

plt.subplot(121),plt.imshow(mud1),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(mud1new),plt.title('Masked')
plt.xticks([]), plt.yticks([])
plt.savefig('problem.jpeg')
plt.show()

The pixels remain unchanged but somehow the image I see is different.

Upvotes: 1

Views: 122

Answers (1)

Suever
Suever

Reputation: 65430

The issue is because np.random.random_integers returns objects that are int64 whereas your loaded image is uint8 so when you multiply the two together, mud1new becomes an int64 array. When using imshow, it expects the following types

  • MxN – values to be mapped (float or int)
  • MxNx3 – RGB (float or uint8)
  • MxNx4 – RGBA (float or uint8)

To fix this, you should cast mud1new as a uint8 prior to display with imshow

mud1new = mud1new.astype(np.unit8)
plt.imshow(mud1new)

You could also convert mud1new to a float but that would require that all of your values should be between 0 and 1 so you'd have to divide everything by 255.

The value for each component of MxNx3 and MxNx4 float arrays should be in the range 0.0 to 1.0.

mud1new_float = mud1new.astype(np.float) / 255.0;
plt.imshow(mud1new_float)

Upvotes: 2

Related Questions