我注意到 MATLAB 有时会错误地显示我的颜色。我不确定这是我这边的编程错误,还是 MATLAB 中的实际错误。在过去一年左右的时间里,我注意到这种行为具有一定的规律性。
这一次,我决定对有问题的图形进行快照(在 64 位 Windows 7 上的 MATLAB 2011b 上拍摄):
显示相关图像的代码如下:
figure;
clf;
cla;
imshow(matrix, []);
colormap(cmap);
set(gca, 'Clim', [0 highest_index]);
哪里:
-
matrix
类型为uint32
(尽管我也曾尝试在调用matrix
之前明确地将double
转换为imshow
) matrix
中的值范围介于0
之间和900
-
cmap
有901
条目 -
highest_index
是900
值 259
的 RGB 条目在 matrix
是[1, 0, 0.1]
在上图中和颜色图数组中都是 cmap
,即 cmap(300, :) = [1, 0, 0.1]
(注意矩阵值 259
在颜色图中得到索引 300
,因为颜色图的第一个条目是矩阵值 0
)。
问题:
为什么会这样?这是一个错误吗?我做错了什么吗?
更新 1:
- 我尝试切换
CDataMapping
至direct
或scaled
,但这并没有什么不同。 - 我也试过使用
imagesc
而不是imshow
,但这并没有什么不同。 如果我先将图像转换为 RGB(即,将
indexed image
转换为true color
图像;see here 了解更多信息),即使用i_rgb = ind2rgb(i_indexed, cmap)
,错误消失并且图像显示正确。不幸的是,如果我显示
true color
图像数据提示不再显示每种颜色在原始矩阵中的索引,而只是显示 RGB 向量(即这是合乎逻辑的,因为 MATLAB 不再知道原始索引)。
更新 2:
下面是一些示例代码:
h_f = figure(1);
clf;
i_spiral = spiral(40);
h_i = image(i_spiral);
% Synthesize a colormap first in HSV and then transform it to RGB:
max_i_spiral = max(i_spiral(:));
m = max_i_spiral;
h = (0:m-1)'/max(m,1);
cmap_spiral = hsv2rgb([h ones(m,2)]);
colormap(cmap_spiral);
% If I comment out the following two lines or use imshow instead of image,
% it makes no difference (I still get the same error):
set(gca, 'Clim', [1 max_i_spiral]);
set(h_i, 'CDataMapping', 'direct');
上面的代码导致:
最佳答案
[由于这个答案与我之前的答案完全无关,所以我不编辑第一个]
您提到的链接 ( http://www.mathworks.com/help/matlab/creating_plots/image-types.html ) 说:
Note When using the painters renderer on the Windows platform, you should only use 256 colors when attempting to display an indexed image. Larger colormaps can lead to unexpected colors because the painters algorithm uses the Windows 256 color palette, which graphics drivers and graphics hardware are known to handle differently. To work around this issue, use the Zbuffer or OpenGL renderer, as appropriate. For more information regarding graphics renderers in MATLAB, see Technical Note 1201: The Technical Support Guide to Graphics Rendering and Troubleshooting.
所以看来问题是您的颜色图有超过 256 个值。它还解释了为什么如果您不使用索引图像,问题就会消失。按照注释中技术支持链接中的建议,尝试使用不同的渲染器:
set(gcf, 'Renderer', 'opengl')
或
set(gcf, 'Renderer', 'Zbuffer')
关于MATLAB:颜色显示不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7774342/