You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MATLAB中手动按图像对应颜色的RGB值添加图例颜色?

How to Add Custom RGB Colors to an Image Legend in MATLAB

Got it, let's walk through exactly how to set custom RGB-based colors for your image legend in MATLAB. The key here is to use "dummy" plot objects to carry your custom colors, since direct legend customization for imshow outputs isn't straightforward. Here's a step-by-step guide with code examples:

Step 1: Display Your Image

First, load and show your image (replace the example code with your actual image loading logic):

% Load and display your image
img = imread('your_image_file.png'); % Swap with your image path
figure;
imshow(img);
hold on; % Keep the plot active to add dummy objects

Step 2: Define Your Custom RGB Colors & Labels

Specify the exact RGB values you want (note: MATLAB uses 0-1 normalized values, not 0-255—divide by 255 if your RGB is in 0-255 range):

% Example custom RGB colors (normalized 0-1)
custom_rgb = [0.15 0.7 0.2; 0.8 0.2 0.1; 0.3 0.3 0.8]; 
% Corresponding legend labels
legend_labels = {'Vegetation', 'Urban Area', 'Water Body'};

If your RGB values are in 0-255 format, convert them like this:

rgb_255 = [38, 178, 51; 204, 51, 26; 77, 77, 204];
custom_rgb = rgb_255 ./ 255; % Normalize to 0-1

Step 3: Create Dummy Objects for the Legend

We'll create invisible patch objects (you can also use lines) to hold our custom colors—these won't show up in your image, but will define the legend entries:

dummy_handles = [];
for i = 1:length(custom_rgb)
    % Create a tiny, off-screen patch (so it doesn't interfere with your image)
    h = patch([-10 -10 -10 -10], [-10 -10 -10 -10], custom_rgb(i,:));
    dummy_handles = [dummy_handles, h];
end

Step 4: Add & Customize the Legend

Now use the dummy handles to create your legend, and tweak its appearance if needed:

% Add the legend with your custom colors and labels
lgd = legend(dummy_handles, legend_labels);

% Optional: Adjust legend marker style/size
for i = 1:length(dummy_handles)
    set(dummy_handles(i), ...
        'Marker', 's', ...          % Square marker
        'MarkerSize', 12, ...       % Larger marker
        'MarkerFaceColor', custom_rgb(i,:), ...
        'MarkerEdgeColor', 'none'); % Remove marker border
end

% Optional: Set legend text color (e.g., white for dark backgrounds)
set(lgd.Text, 'Color', 'white');

Key Notes

  • Always normalize RGB values to 0-1: MATLAB doesn't recognize 0-255 color values directly for plot objects.
  • Dummy objects are the workaround here because imshow returns an image object that doesn't play nicely with direct legend color customization.
  • You can use line instead of patch if you prefer line-style legend entries—just adjust the Color property of the line objects instead.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:44:55