## Matplotlib如何实现灰度图？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (124)

### 2 个回答

```import numpy as np
import pylab as p
xv=np.ones(4)*.5
yv=np.arange(0,4,1)
xv1=np.ones(4)*-.5
yv1=np.arange(0,4,1)

#red vertical line on the right
yv2=np.arange(0,1.5,0.1)
xv2=np.ones_like(yv2)*.7

#red vertical line on the left
yv3=np.arange(0,2,0.01)
xv3=np.ones_like(yv3)*-0.7

###
xc=np.arange(-1.4,2,0.05)
yc=np.ones_like(xc)*1

fig = p.figure()
#adjustprops = dict(left=0.12, bottom=0.2, right=0.965, top=0.96, wspace=0.13, hspace=0.37)
ax1.plot(xv,yv, color='blue', lw=1, linestyle='dashed')
ax1.plot(xv1,yv1, 'green', linestyle='dashed')
ax1.plot(np.r_[-1:1:0.2],np.r_[-1:1:0.2],'red')
ax1.plot(xc,yc, 'k.', markersize=3)

p.savefig('colored_image.png')

import matplotlib.image as mpimg
import matplotlib.cm as cm
import Image

figprops = dict(figsize=(10,10), dpi=100)
fig1 = p.figure(**figprops)
#fig1 = p.figure()
image=Image.open('colored_image.png').convert("L")
arr=np.asarray(image)
p.figimage(arr,cmap=cm.Greys_r)
p.savefig('grayed.png')
p.savefig('grayed.pdf',papertype='a4',orientation='portrait')```

```import Image
Image.open('color.png').convert('L').save('bw.png')```

`convert -type Grayscale color.png bw.png`