如何使用matplotlib/numpy将数组另存为灰度图像? [英] how to save an array as a grayscale image with matplotlib/numpy?

查看:1841
本文介绍了如何使用matplotlib/numpy将数组另存为灰度图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将尺寸为128x128像素的Numpy数组保存到灰度图像中. 我只是以为pyplot.imsave函数可以完成这项工作,但事实并非如此,它以某种方式将我的数组转换为RGB图像. 我尝试在转换过程中将颜色图强制设置为灰度",但是即使保存的图像以灰度显示,其尺寸仍为128x128x4. 这是我编写的显示此行为的代码示例:

I am trying to save a numpy array of dimensions 128x128 pixels into a grayscale image. I simply thought that the pyplot.imsave function would do the job but it's not, it somehow converts my array into an RGB image. I tried to force the colormap to Gray during conversion but eventhough the saved image appears in grayscale, it still has a 128x128x4 dimension. Here is a code sample I wrote to show the behaviour :

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mplimg
from matplotlib import cm

x_tot = 10e-3
nx = 128

x = np.arange(-x_tot/2, x_tot/2, x_tot/nx)

[X, Y] = np.meshgrid(x,x)
R = np.sqrt(X**2 + Y**2)

diam = 5e-3
I = np.exp(-2*(2*R/diam)**4)

plt.figure()
plt.imshow(I, extent = [-x_tot/2, x_tot/2, -x_tot/2, x_tot/2])

print I.shape

plt.imsave('image.png', I)
I2 = plt.imread('image.png')
print I2.shape

mplimg.imsave('image2.png',np.uint8(I), cmap = cm.gray)
testImg = plt.imread('image2.png')
print testImg.shape

在两种情况下,打印"功能的结果均为(128,128,4).

In both cases the results of the "print" function are (128,128,4).

有人能解释为什么我的输入数组是亮度类型时,imsave函数为什么要创建这些尺寸吗? 当然,有人可以将阵列保存为标准灰度格式吗?

Can anyone explain why the imsave function is creating those dimensions eventhough my input array is of a luminance type? And of course, does anyone have a solution to save the array into a standard grayscale format?

谢谢!

推荐答案

对于PIL,它应该像这样

import Image

I8 = (((I - I.min()) / (I.max() - I.min())) * 255.9).astype(np.uint8)

img = Image.fromarray(I8)
img.save("file.png")

这篇关于如何使用matplotlib/numpy将数组另存为灰度图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆