Matplotlib中的空,零和非零像素表示 [英] empty, zero and non-zero pixels representation in Matplotlib

查看:100
本文介绍了Matplotlib中的空,零和非零像素表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在matplotlib中绘制像素值变为非"-1"值的光线跟踪路径.换句话说,我有下面的2D数组,它代表4条光线路径.光线穿过的每个像素都具有随机值.除这些相交的像素外,其余均为"-1".我想以白色或不可见(不存在)显示值"-1".怎么可能?

I am trying to plot ray traced path where pixel value gets non "-1" value in matplotlib. In other words, I have following 2D array which represents 4 rays paths. Each pixel crossed by ray has random value. Except these intersected pixels, the rest of them are "-1". I want to show value "-1" in a white color or non-visible (no exist). How is it possible?

import numpy as np
import scipy as sp
import pylab as pl

M = np.array([[ 0. , -1., -1., -1., -1., -1.],
          [ 0.25, -1.,-1.,-1.,-1.,-1.],
          [ 0.25, -1., -1., -1.,-1.,-1.],
          [ 0.22, -1., -1., -1., -1.,-1.],
          [ 0.16, -1., -1., -1., -1.,-1.],
          [ 0.16, -1., -1., -1., -1.,-1.],
          [ 0.13, -1., -1., -1., -1.,-1.],
          [ 0.10, -1., -1., -1., -1.,-1.],
          [-1., 0.06, 0.14, 0.087, 0.079,0.],
          [ 0., 0.16, 0.10, 0.15, 0.16, 0.],
          [-1., -1., 0., 0.004,-1., -1.]])

pl.subplot(111)
pl.imshow(M, origin='lower', interpolation='nearest')
pl.show()

推荐答案

替代方法是使用颜色映射表的set_underset_overset_bad属性

An alternate way to do this is to use the set_under, set_over and set_bad properties of color maps (doc)

from copy import copy

# normalize data between vmin and vmax
my_norm = matplotlib.colors.Normalize(vmin=.25, vmax=.75, clip=False)
# clip=False is important, if clip=True, then the normalize function
# clips out of range values to 0 or 1 which defeats what we want to do here.

my_cmap = copy(cm.get_cmap('gray')) # make a copy so we don't mess up system copy
my_cmap.set_under('r', alpha=.5) # make locations over vmax translucent red
my_cmap.set_over('w', alpha=0)   # make location under vmin transparent white
my_cmap.set_bad('g')             # make location with invalid data green

test_data = np.random.rand(10, 10) # some random data between [0, 1]
test_data[5, 5] = np.nan           # add one NaN
# plot!
imshow(test_data, norm=my_norm, cmap=my_cmap, interpolation='nearest')

我认为这是一种比手工制作遮罩阵列更好的方法,因为您让matplotlib为您完成工作,并且可以让您分别显式设置三种不同条件的颜色.

I would argue this is a better way than making a mask array by hand as you let matplotlib do the work for you and it lets you explicitly set the color of the three different conditions independently.

这篇关于Matplotlib中的空,零和非零像素表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆