在imshow中出现一个错误?

mpe*_*kov 5 python matplotlib

我正在绘制PGM图像: 在此输入图像描述 这是我正在使用的数据.

问题是一些显示的像素是错误的.例如:

  • 图像顶部附近的三个灰色框的值为11(所以它们应该是红色,而不是红色)
  • 顶行中的两个黄色像素 - 它们的值为8,因此它们应该是黄绿色而不是黄色

任何人都能解释这些差异以及如何解决这些问题吗?

这是我的来源:

from pylab import *
import numpy    
LABELS = range(13)
NUM_MODES = len(LABELS)
def read_ascii_pgm(fname):
    """
    Very fragile PGM reader.  It's OK since this is only for reading files
    output by my own app.
    """
    lines = open(fname).read().strip().split('\n')
    assert lines[0] == 'P2'
    width, height = map(int, lines[1].split(' '))
    assert lines[2] == '13'
    pgm = numpy.zeros((height, width), dtype=numpy.uint8)
    for i in range(height):
        cols = lines[3+i].split(' ')
        for j in range(width):
            pgm[i,j] = int(cols[j])
    return pgm
def main():
    import sys
    assert len(sys.argv) > 1
    fname = sys.argv[1]
    pgm = read_ascii_pgm(fname)
    # EDIT: HACK!
    pgm[0,0] = 12
    cmap = cm.get_cmap('spectral', NUM_MODES)
    imshow(pgm, cmap=cmap, interpolation='nearest')
    edit = True
    if edit:
        cb = colorbar()
    else:
        ticks = [ (i*11./NUM_MODES + 6./NUM_MODES) for i in range(NUM_MODES) ]
        cb = colorbar(ticks=ticks)
        cb.ax.set_yticklabels(map(str, LABELS))
    savefig('imshow.png')
if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

编辑

我现在看到这里发生了什么.基本上,imshow似乎这样做:

  • 确定动态范围(如 [ min(image), max(image) ]
  • 使用颜色图中指定的颜色数(13种颜色)表示

我想要它做的是:

  • 使用我在创建颜色图时指定的动态范围(13)
  • 使用颜色映射中的13种颜色表示这一点

我可以通过强制图像的动态范围为13来验证这一点(参见标记的行HACK).有一个更好的方法吗?

这是一张更新的图片: 在此输入图像描述

sam*_*ias 5

解决方案是设置im.set_clim(vmin, vmax).基本上,图像中的值被翻译为覆盖整个颜色范围.例如,如果3是数据中的最大值,则会为其分配最大颜色值.

相反,您需要告诉它这max_nodes是最高值(在您的情况下为13),即使它没有出现在数据中,例如im.set_clim(0, 13).

我稍微更改了您的代码以使用具有不同值的其他数据文件num_modes:

import numpy
from pylab import *

def read_ascii_pgm(fname):
    lines = open(fname).read().strip().split('\n')
    assert lines[0] == 'P2'
    width, height = map(int, lines[1].split(' '))
    num_modes = int(lines[2])
    pgm = numpy.zeros((height, width), dtype=numpy.uint8)
    for i in range(height):
        cols = lines[3+i].split(' ')
        for j in range(width):
            pgm[i,j] = int(cols[j])
    return pgm, num_modes + 1

if __name__ == '__main__':
    import sys
    assert len(sys.argv) > 1
    fname = sys.argv[1]
    pgm, num_modes = read_ascii_pgm(fname)
    labels = range(num_modes)
    cmap = cm.get_cmap('spectral', num_modes)
    im = imshow(pgm, cmap=cmap, interpolation='nearest')
    im.set_clim(0, num_modes)
    ticks = [(i + 0.5) for i in range(num_modes)]
    cb = colorbar(ticks=ticks)
    cb.ax.set_yticklabels(map(str, labels))
    savefig('imshow_new.png')
Run Code Online (Sandbox Code Playgroud)

一些更简单的测试数据来说明.请注意,该num_modes值为10,但没有数据点达到该级别.这显示了值如何索引到色彩映射1:1:

P2
5 3
10
0 1 0 2 0
3 0 2 0 1
0 1 0 2 0
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述