【问题标题】:How to plot a gray image and save it?如何绘制灰色图像并保存?
【发布时间】:2023-03-14 23:20:01
【问题描述】:

我正在使用 matplotlib 绘制函数图,例如,正弦函数:

t = np.arange(0., 5., 0.2)
plt.plot(t, np.sin(t))

但它有 3 个频道。我应该如何制作灰度图像(只有一个通道)并将其保存为形状高度 * 宽度 * 1 的 numpy 数组。谢谢!

【问题讨论】:

  • 渠道是什么意思?
  • 色彩缤纷。所以我认为它有RGB通道。 @比尔
  • 用你的 plot 命令试试cmap='gray'
  • 当我尝试plt.plot(t, f(t), cmap="gray") 时,它报告错误:'Line2D' object has no property 'cmap' @MarkSetchell

标签: python image matplotlib grayscale


【解决方案1】:

使用 skimage 库可以实现管道(它仍然是相当重量级的,但现在图像的质量会好得多)。

#import the required libraries and functions
import os
from skimage.io import imread
from skimage.color import rgb2gray, rgba2rgb

#create an image
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
plt.plot(x, y)

#save and image as a .png picture and then load 
plt.savefig('img.png')
img = imread('img.png')
#we do not need the colored picture, so remove it
os.remove('img.png')

#the loaded picture is initially rgba, convert it to the grayscale image
img = rgb2gray(rgba2rgb(img))
#if you want a flat array saved as binary, ravel() it and use np.save
np.save('test.npy', img.ravel())

【讨论】:

  • 我应该在哪里使用cmap='gray'?当我尝试plt.plot(t, f(t), cmap="gray") 时,它报告错误:'Line2D' 对象没有属性'cmap'。
  • @luw,对不起,我最初没有抓住你想要的东西。这个问题似乎更复杂。我想出了一个疯狂的解决方案,但正在工作
  • 嗨,我想要的是将灰度图存储为形状高度 * 宽度 * 1 的 numpy 数组。我已经尝试过您的代码,但是当我将其保存 plt.savefig('filename') 并使用 cv2. imread 阅读,原来保存的数组还是有形状 (288, 432, 3)。
  • 我现在明白你的想法了,直接用一个0-1的np数组来表示情节,这是个好主意,虽然情节可能不如plt.plot()准确。
  • 如果您解释了您提供的代码如何回答问题,这将是一个更好的答案。
猜你喜欢
  • 1970-01-01
  • 2013-04-06
  • 1970-01-01
  • 2011-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多