如何在MATLAB中手动按图像对应颜色的RGB值添加图例颜色?
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
imshowreturns an image object that doesn't play nicely with direct legend color customization. - You can use
lineinstead ofpatchif you prefer line-style legend entries—just adjust theColorproperty of the line objects instead.
内容的提问来源于stack exchange,提问作者Shivam Pande

