如何在保存图像时为图像添加彩条?

时间:2016-06-16 16:02:34

标签: python matplotlib data-visualization

我有一个2维矩阵,比如foreach(DataRow row in RowList) { if (importSetOfTables.Tables["MyTable"].Rows.Contains(row)) importSetOfTables.Tables["MyTable"].Rows.Remove(row); } 我希望使用img色彩图保存在图像中。以下代码

'hot'

允许我这样做。但是,我想将颜色条与图像一起保存,对我来说重要的是要知道每个像素的值是多少。我们假设我右边有很多空间。

我知道可以通过使用import matplotlib.pyplot as plt plt.imsave("out.jpg", img, cmap = 'hot') 创建图形,使用plt.imshow()添加颜色条然后使用plt.colorbar()保存颜色,以“简单”方式完成,但是还会在图形周围保存“灰色区域”,并且颜色条会单独显示。此外,如果涉及缩放,这在图形大小方面存在问题。我希望颜色条出现在图像上,结果输出图像与矩阵大小相同。

此外,如果有人有关于将矩阵可视化为图像的任何其他建议((其中值不受限制),他们将不胜感激。

1 个答案:

答案 0 :(得分:2)

我不确定如何在您保存之前为图像添加色条,我甚至不确定是否可能。但我可以为您提供一种绘制图像,添加颜色栏并保存图像的方法,但可以按照您希望的方式对其进行格式化。尝试类似下面的内容

import matplotlib.pyplot as plt

fig = plt.figure(figsize = (W,H)) # Your image (W)idth and (H)eight in inches
# Stretch image to full figure, removing "grey region"
plt.subplots_adjust(left = 0, right = 1, top = 1, bottom = 0)
im = plt.imshow('out.jpg') # Show the image
pos = fig.add_axes([0.93,0.1,0.02,0.35]) # Set colorbar position in fig
fig.colorbar(im, cax=pos) # Create the colorbar
plt.savefig('out.jpg')

我无法保证在没有测试的情况下可以正常使用,但它应该是正确的方向,以满足您的需求。