简体   繁体   中英

matplotlib image shows in black and white, but I wanted gray

I have a small code sample to plot images in matplotlib, and the image is shown as this :

在此输入图像描述

Notice the image in the black box has black background, while my desired output is this :

在此输入图像描述

My code to plot the image is this :

plt.subplot(111)
plt.imshow(np.abs(img), cmap = 'gray')
plt.title('Level 0'), plt.xticks([]), plt.yticks([])
plt.show()

My understanding is that cmap=grey should display it in grayscale. Below is a snippet of the matrix img being plotted :

[[ 192.77504036 +1.21392817e-11j  151.92357434 +1.21278246e-11j
   140.67585733 +6.71014111e-12j  167.76903747 +2.92050743e-12j
   147.59664180 +2.33718944e-12j   98.27986577 +3.56896094e-12j
    96.16252035 +5.31530804e-12j  112.39194666 +5.86689097e-12j....

What am I missing here ?

The problem seems to be that you have three channels while there should be only one, and that the data should be normalized between [0, 1] . I get a proper looking gray scaled image using this:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np

img = mpimg.imread('Lenna.png')
# The formula below can be changed -- the point is that you go from 3 values to 1
imgplot = plt.imshow(np.dot(img[...,:3], [0.33, 0.33, 0.33]), cmap='gray')
plt.show()

This gives me:

在此输入图像描述

Also, a snapshot of the data:

[[ 0.63152942  0.63152942  0.63800002 ...,  0.64705883  0.59658825 0.50341177]
 [ 0.63152942  0.63152942  0.63800002 ...,  0.64705883  0.59658825 0.50341177]
 [ 0.63152942  0.63152942  0.63800002 ...,  0.64705883  0.59658825 0.50341177]
 ...]

For my case, the color (gray) which I wanted is actually "negative" pixels. Subtracting 128 from the image matrix brings the range of pixels from 0-255 to -128 to +127. The negative pixels is displayed in the "gray" color by the package matplotlib.

val = np.subtract(imageMatrix,128)
plt.subplot('111')
plt.imshow(np.abs(val), cmap=plt.get_cmap('gray'),vmin=0,vmax=255)
plt.title('Image'), plt.xticks([]), plt.yticks([])
plt.show()

I will mark my own answer as accepted, as the answer accepted earlier does not talk about treating the pixels on negative scale.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM