Stav Alfi
Stav Alfi

Reputation: 13923

Emphasize the blue in an image

I'm using matplotlib to do it but for some reason, my code creates an unexpected image.

import numpy as np
import matplotlib.pyplot as plt
from scipy.misc import imread,imsave


# original image
image1=imread('img.jpg')
plt.imshow(image1)
plt.show()

# empesize the blue in that image
plt.imshow(image1*[0.95,0.95,1])
plt.show()

result:

The top image is the original one and the second (which is shown) is the unexpected result.

enter image description here

It seems that no matter what values I enter to the vector, I get the same strange result. Why?

Upvotes: 1

Views: 235

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339280

This question is closely related to Getting black plots with plt.imshow after multiplying image array by a scalar.

You may compare image1.dtype, which is uint8, to (image1*[0.95,0.95,1]).dtype, which is float.

Matplotlib imshow can plot integer values, in which case they need to be in the range [0, 255] or float values, in which case they need to be in the range [0.0, 1.0]. So while plotting the original image of integer values works fine, the multiplied image, which will consist of float values up to 255., exceeds the allowed range of [0.0, 1.0] by 25500%. Hence it is mostly white (because pixel values are cropped to 1.0).

The solution is either to cast the values back to uint after multiplication,

image2 = (image1*[0.95,0.95,1]).astype(np.uint8)

or to divide by 255.,

image2 = (image1*[0.95,0.95,1])/255.

You could also use plt.Normalize like

image2 = plt.Normalize(0,255)(image1*[0.95,0.95,1])

Upvotes: 2

Related Questions