以灰度保存 matplotlib 图

发布于 2024-11-07 17:05:05 字数 52 浏览 0 评论 0原文

我有一些彩色图需要以灰度保存。有没有一种简单的方法可以在不改变绘图格式的情况下做到这一点?

I have some color plots that I need to be saved in grayscale. Is there an easy way to do this without changing the plotting formats?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

偏爱自由 2024-11-14 17:05:05

有一个简单的解决方案:

plt.imsave(filename, image, cmap='gray')

There is an easy solution:

plt.imsave(filename, image, cmap='gray')
少跟Wǒ拽 2024-11-14 17:05:05

目前直接从 matplotlib 进行操作很尴尬,但在“未来”,他们计划支持对图形进行 set_gray(True) 调用(请参阅邮件列表线程 此处)。

最好的选择是将其保存为彩色并转换它,可以在 python 中使用 PIL:

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

或从命令行使用 imagemagick:

convert -type Grayscale color.png bw.png

It's currently awkward to do directly from matplotlib, but in "the future" they plan to support a set_gray(True) call on the figure (see the mailing list thread here).

Your best options will be to save it in color and convert it, either in python with PIL:

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

or from the command line with imagemagick:

convert -type Grayscale color.png bw.png
很酷不放纵 2024-11-14 17:05:05

其实这个问题之前就有人问过。这是一个非常好的答案,在谷歌上排名第二(截至今天):
使用 matplotlib 将图像显示为灰度

解决方案非常相似到 Suki 的...

哦,好吧,我很无聊,所以我在这里发布了一个完整的代码:

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()
ax1 = fig.add_subplot(111)
#adjustprops = dict(left=0.12, bottom=0.2, right=0.965, top=0.96, wspace=0.13, hspace=0.37)
#fig.subplots_adjust(**adjustprops)
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()
#ax1 = fig.add_subplot(111)
adjustprops = dict()
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')

这将生成一个彩色图表,然后读取它,将其转换为灰色缩放,并将保存 png 和 pdf。

Actually, this was asked before. Here is a pretty good answer, which comes 2nd on google (as of today):
Display image as grayscale using matplotlib

And the solution is VERY similar to Suki's...

Oh, well, I am bored, so I post here also a full blown code:

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()
ax1 = fig.add_subplot(111)
#adjustprops = dict(left=0.12, bottom=0.2, right=0.965, top=0.96, wspace=0.13, hspace=0.37)
#fig.subplots_adjust(**adjustprops)
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()
#ax1 = fig.add_subplot(111)
adjustprops = dict()
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')

This will produce a graph in color, than read it, convert it to gray scale, and will save a png and pdf.

無處可尋 2024-11-14 17:05:05

我也在这个问题上苦苦挣扎。据我所知,matplotlib不支持直接转换为灰度,但您可以保存彩色pdf,然后使用ghostscript将其转换为灰度:

gs -sOutputFile=gray.pdf -sDEVICE=pdfwrite -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray -dNOPAUSE -dBATCH -dAutoRotatePages=/None color.pdf

I am struggling with this issue too. As far as I can tell, matplotlib doesn't support direct conversion to grayscale, but you can save a color pdf and then convert it to grayscale with ghostscript:

gs -sOutputFile=gray.pdf -sDEVICE=pdfwrite -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray -dNOPAUSE -dBATCH -dAutoRotatePages=/None color.pdf
望笑 2024-11-14 17:05:05

添加到 Mu Mind 的解决方案中,

如果出于某种原因您想避免将其写入文件,您可以像文件一样使用 StringIO:


 import Image
 import pylab
 from StringIO import StringIO

 pylab.plot(range(10),[x**2 for x in range(10)])

 IO = StringIO()
 pylab.savefig(IO,format='png')
 IO.seek(0)

 #this, I stole from Mu Mind solution
 Image.open(IO).convert('L').show()

And to add to Mu Mind's solution

If for whatever reason you want to avoid writing it to a file you can use StringIO like a file:


 import Image
 import pylab
 from StringIO import StringIO

 pylab.plot(range(10),[x**2 for x in range(10)])

 IO = StringIO()
 pylab.savefig(IO,format='png')
 IO.seek(0)

 #this, I stole from Mu Mind solution
 Image.open(IO).convert('L').show()
相思碎 2024-11-14 17:05:05

根据 Ian Goodfellow 的回答开发,这里是一个 python 脚本,它生成并运行 Ghostscript 命令,将 PDF 转换为灰度。它比栅格化为 PNG 的答案更好,因为它保留了绘图的矢量表示。

import subprocess
import sys 

def pdf_to_grayscale(input_pdf, output_pdf):
    try:
        # Ghostscript command to convert PDF to grayscale
        ghostscript_cmd = [
            "gs",
            "-sDEVICE=pdfwrite",
            "-sColorConversionStrategy=Gray",
            "-sProcessColorModel=DeviceGray",
            "-dCompatibilityLevel=1.4",
            "-dNOPAUSE",
            "-dQUIET",
            "-dBATCH",
            f"-sOutputFile={output_pdf}",
            input_pdf
        ]

        # Execute Ghostscript command using subprocess
        subprocess.run(ghostscript_cmd, check=True)

        print("PDF converted to grayscale successfully.")
    except subprocess.CalledProcessError:
        print("Error occurred during PDF conversion to grayscale.")

if __name__ == "__main__":
    assert len(sys.argv) == 3, "Two args: input pdf and output pdf"    
    pdf_to_grayscale(sys.argv[1], sys.argv[2])

将其保存为 to_gray.py 并按如下方式运行:

python to_gray.py test.pdf gray.pdf

Developed from Ian Goodfellow's answer, here is a python script that generates and runs a ghostscript command that converts a PDF into grayscale. It is preferable to the answers that rasterise to PNG as it retains the vector representation of the plot.

import subprocess
import sys 

def pdf_to_grayscale(input_pdf, output_pdf):
    try:
        # Ghostscript command to convert PDF to grayscale
        ghostscript_cmd = [
            "gs",
            "-sDEVICE=pdfwrite",
            "-sColorConversionStrategy=Gray",
            "-sProcessColorModel=DeviceGray",
            "-dCompatibilityLevel=1.4",
            "-dNOPAUSE",
            "-dQUIET",
            "-dBATCH",
            f"-sOutputFile={output_pdf}",
            input_pdf
        ]

        # Execute Ghostscript command using subprocess
        subprocess.run(ghostscript_cmd, check=True)

        print("PDF converted to grayscale successfully.")
    except subprocess.CalledProcessError:
        print("Error occurred during PDF conversion to grayscale.")

if __name__ == "__main__":
    assert len(sys.argv) == 3, "Two args: input pdf and output pdf"    
    pdf_to_grayscale(sys.argv[1], sys.argv[2])

Save it as to_gray.py and run it like this:

python to_gray.py test.pdf gray.pdf
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文