You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

MATLAB子图配色定制:如何让指定surf子图显示彩色,其余子图保持灰度

解决MATLAB子图混合灰度与彩色配色的问题

要实现你需要的效果,核心是为每个子图单独指定颜色映射(colormap)——MATLAB默认会让所有子图共享全局颜色映射,这就是之前所有子图都是灰度的原因。通过给目标子图单独设置配色,就能实现灰度图像子图和彩色曲面子图共存的效果。

具体实现思路

  • 对需要彩色的surf子图(位置3,3,23,3,53,3,8):绘制曲面后,为该子图的轴对象设置彩色配色(比如常用的彩虹色jet,也可以换成parulaviridis等其他彩色配色)。
  • 对需要灰度的图像子图:保持gray配色,同时指定到对应子图的轴,避免被其他配色设置干扰。

修改后的完整代码

img = imread('moon.tif'); 

% 灰度图像子图1:指定轴的灰度配色
ax1 = subplot(1,3,1); 
imagesc(ax1, img); 
colormap(ax1, gray); 
title('moon.tif'); 
axis tight; 
axis equal; 

% 彩色surf子图2:应用彩虹色配色
ax2 = subplot(3,3,2); 
sigma = 3; 
gaussianfilter = fspecial('gaussian', [90,90], sigma); 
surf(ax2, gaussianfilter); 
title(['Gaussian filter \sigma = ', num2str(sigma)]); 
colormap(ax2, jet); % 单独设置彩色配色
colorbar; % 可选:添加颜色条,直观展示曲面数值对应颜色

% 灰度图像子图3
ax3 = subplot(3,3,3); 
img_filtered = conv2(img, gaussianfilter, 'same'); 
imagesc(ax3, img_filtered); 
title('Filtered image'); 
colormap(ax3, gray); 
axis tight; 
axis equal; 

% 彩色surf子图5
ax5 = subplot(3,3,5); 
sigma = 9; 
gaussianfilter = fspecial('gaussian', [90,90], sigma); 
surf(ax5, gaussianfilter); 
title(['Gaussian filter \sigma = ', num2str(sigma)]); 
colormap(ax5, jet); 
colorbar;

% 灰度图像子图6
ax6 = subplot(3,3,6); 
img_filtered = conv2(img, gaussianfilter, 'same'); 
imagesc(ax6, img_filtered); 
title('Filtered image'); 
colormap(ax6, gray); 
axis tight; 
axis equal; 

% 彩色surf子图8
ax8 = subplot(3,3,8); 
sigma = 15; 
gaussianfilter = fspecial('gaussian', [90,90], sigma); 
surf(ax8, gaussianfilter); 
title(['Gaussian filter \sigma = ', num2str(sigma)]); 
colormap(ax8, jet); 
colorbar;

% 灰度图像子图9
ax9 = subplot(3,3,9); 
img_filtered = conv2(img, gaussianfilter, 'same'); 
image(ax9, img_filtered); 
title('Filtered image'); 
colormap(ax9, gray); 
axis tight; 
axis equal;

关键细节说明

  1. subplot返回轴对象(比如ax2 = subplot(3,3,2)),后续绘图和配色操作都指定这个轴,确保只修改目标子图。
  2. 通过colormap(ax, map)为单个轴设置颜色映射,不会影响其他子图的配色方案。
  3. 可选的colorbar命令能为彩色曲面图添加颜色条,方便观察高斯滤波器的数值分布规律。

内容的提问来源于stack exchange,提问作者livemyaerodream

火山引擎 最新活动