Matplotlib显示灰度图

720 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路

引言

 matplotlib中的imshow()函数不能自动显示灰度图像,这一点应该是众所周知的,需要调用cmap=“gray"以进行设置,但是cmap="gray"实际上并不是如opencv中的imshow函数一样将单通道图显示为灰度图,私以为是引入了灰度图的灰度量化概念,但并不直接对应灰度,而是采纳了“灰阶”的概念,证明见正文。

一、测试

 首先设置一全1.0的图像(全白),和一全白背景叠加黑色条柱的图像,使用plt.imshow()显示。 代码:

import matplotlib.pyplot as plt
import numpy as np
white=np.ones((100,100),dtype=float)
bar=np.ones((100,100),dtype=float)
bar[40:50,:]=0
plt.figure(1)
plt.subplot(211)
plt.imshow(white,cmap='gray')
plt.title('white map')
plt.subplot(212)
plt.imshow(bar,cmap='gray')
plt.title('black bar')

结果如下图所示: 在这里插入图片描述 由此可以发现在值全为1.0时,图像显示为黑色,那么是否是dtype的原因呢?接着测试常用的uint8情况下,亮度为恒定值,结果是怎么样的。 代码为:

white1=np.ones((100,100),dtype=np.uint8)*255
white2=np.ones((100,100),dtype=np.uint8)*128
plt.figure((2))
plt.subplot(211)
plt.imshow(white1,cmap='gray')
plt.title('white1')
plt.subplot(212)
plt.imshow(white2,cmap='gray')
plt.title('white2')

结果如下图所示: 在这里插入图片描述 由此可以确定,这一显示“异常”与数据类型无关 。

二、解决方案

  使用vmin,vmax参数指定灰度范围,或者设定cmap为gray_r以使得灰度范围反转,后者只适用于想显示白色背景。 代码:

white1=np.ones((100,100),dtype=np.uint8)*255
white2=np.ones((100,100),dtype=np.uint8)*128
plt.figure((2))
plt.subplot(211)
plt.imshow(white1,cmap='gray_r')
plt.title('white1')
plt.subplot(212)
plt.imshow(white2,cmap='gray',vmin=0,vmax=255)
plt.title('white2')

结果如下图所示:

在这里插入图片描述