我有一些彩色图形需要保存为灰度。是否有一种简单的方法可以在不改变绘图格式的情况下完成?
有一个简单的解决方案:
plt.imsave(filename, image, cmap='gray')
set_gray(True)
的调用(请参见邮件列表线程here)。您最好的选择是将其保存为彩色并进行转换,可以使用PIL在python中实现:import Image
Image.open('color.png').convert('L').save('bw.png')
或者使用ImageMagick从命令行进行转换:
convert -type Grayscale color.png bw.png
实际上,这个问题之前已经被问过。以下是一个非常好的答案,它在谷歌搜索中排名第二(截至今天):
使用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')
我也遇到了这个问题。据我所知,matplotlib不支持直接转换为灰度图,但你可以保存为彩色pdf文件,然后使用ghostscript将其转换为灰度图:
gs -sOutputFile=gray.pdf -sDEVICE=pdfwrite -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray -dNOPAUSE -dBATCH -dAutoRotatePages=/None color.pdf
另外,补充一下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()
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
set_gray
属性。 - chlconvert -type Grayscale old.png new.png
我认为在SO上已经有相关内容了,参见链接。 - Pierre Guilbert