在Python中绘制不规则间隔的RGB图像 [英] Plotting an irregularly-spaced RGB image in Python
问题描述
我想使用matplotlib在一组轴上绘制多个RGB图像.我最初尝试使用imshow进行此操作,但是它似乎无法在一组具有不同范围的轴上处理两个图像(当我绘制第二个图像时,它会使第一个图像消失).我认为答案是使用pcolormesh,例如
I want to plot several RGB images on one set of axes with matplotlib. I initially tried using imshow for this, but it doesn't seem to handle two images on one set of axes with different extents (when I plot the second, it makes the first disappear). I think the answer here is to use pcolormesh, like in How to plot an irregular spaced RGB image using python and basemap?
但是,这似乎对我不起作用-来自可映射的颜色(即,我传递给pcolormesh的数据数组和我指定的cmap的颜色)会覆盖我指定的面部颜色.网格的边缘确实具有正确的颜色,但表面没有.
However, this doesn't seem to work for me - the color coming from the mappable (i.e. the data array I pass to pcolormesh, and the cmap I specify) overrides the face color I specify. The edges of the grid do have the right color, but not the faces.
有人知道如何直接设置面孔的颜色吗?理想情况下,我会使用一个采用n * m * 3数组的pcolormesh来替代n * m,就像imshow ...
Does anyone know how to set the color of the faces directly? Ideally I'd use a pcolormesh that takes an n*m*3 array as an alternative to n*m, just like imshow...
我希望它如何工作的最小示例: 将numpy导入为np 导入matplotlib.pyplot作为plt
A minimal example of how I'd like it to work: import numpy as np import matplotlib.pyplot as plt
#make some sample data
x, y = np.meshgrid(np.linspace(0,255,1),np.linspace(0,255,1))
r, g = np.meshgrid(np.linspace(0,255,100),np.linspace(0,255,120))
b=255-r
#this is now an RGB array, 100x100x3 that I want to display
rgb = np.array([r,g,b]).T
m = plt.pcolormesh(x, y, rgb/255.0, linewidth=0)
plt.show()
问题在于,使用
numRows, numCols = C.shape
ValueError: too many values to unpack
我猜这是因为它想要一个2D数组,而不是最后一个维度为3的3D数组.
I guess this is because it wants a 2D array, not a 3D array with the last dimension being 3 long.
推荐答案
解决方案非常简单:我要做的一件事不是我链接到的问题是删除数组 strong>来自网格物体.一个最小的示例,以防对他人有所帮助:
The solution was very simple: the one thing I needed to do that wasn't in the question I linked to was to remove the array from the mesh object. A minimal example, in case it's helpful to others:
import numpy as np
import matplotlib.pyplot as plt
#make some sample data
r, g = np.meshgrid(np.linspace(0,255,100),np.linspace(0,255,100))
b=255-r
#this is now an RGB array, 100x100x3 that I want to display
rgb = np.array([r,g,b]).T
color_tuple = rgb.transpose((1,0,2)).reshape((rgb.shape[0]*rgb.shape[1],rgb.shape[2]))/255.0
m = plt.pcolormesh(r, color=color_tuple, linewidth=0)
m.set_array(None)
plt.show()
我猜color_tuple行可能不是很明显:本质上,我们需要将(n,m,3)数组转换为(n * m,3)数组.我认为转置是使所有内容正确匹配所必需的.还值得注意的是,我们传入的颜色必须为0到1之间的浮点.
I guess the color_tuple line might be non-obvious: essentially we need to turn the (n, m, 3) array into an (n*m, 3) array. I think the transpose is necessary to get everything to match up correctly. It's also worth noting that the colors we pass in need to be floating-point, between 0 and 1.
这篇关于在Python中绘制不规则间隔的RGB图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!