How can the colors of ones choice be added to the legends automatically in an image ?

5 次查看(过去 30 天)
I have an image with 16 classes. I wish to add legends (Class1, Class2,...,Class16) to this image corresponding to the color generated by imagesc colormap. The sample image can be displayed using the code below:
for i=1:16
for j=1:20
x(i,j)=i;
end
end
imagesc(x)

采纳的回答

jonas
jonas 2018-9-28
编辑:jonas 2018-9-28
usually when you have a 3d plot like that you use the colorbar instead of a legend. Try adding this:
colormap(parula(16))
colorbar
it will give you a colorbar with 16 distinct colors.
  2 个评论
jonas
jonas 2018-9-28
编辑:jonas 2018-9-28

You can change the labels of the yaxis to anything youd like. You can also make a fake legend with patches but that would require a bit of work.

If you draw a sketch of what you want then I might be able to give you some code.

This question from earlier today seems relevant. Actually, it is probably exactly what you are looking for.

https://se.mathworks.com/matlabcentral/answers/421247-colorbar-for-specified-color

I adapted the code for you

sg=1:16;
for i=1:length(sg)
  for j=1:20
   x(i,j)=i;
  end
end
imagesc(x)
cbp=colorbar('southoutside');
cbp.Visible='off';
p=cbp.Position;
w=p(3)/numel(sg)
cmap=colormap(jet(length(sg)))
str=sprintfc('\n Class %g',1:numel(sg))
for i=1:numel(sg)
annotation('textbox',[p(1)+w*(i-1) p(2) w*0.95 p(4)],'backgroundcolor',cmap(i,:),'string',str{i})
end

Also see my attached example for making the bar vertical. This is more complicated, as a break is automatically inserted when the text reaches the horizontal edges of the textbox. You will need to adapt the position properties to make it look good.

请先登录,再进行评论。

更多回答(1 个)

Image Analyst
Image Analyst 2018-9-29
Try this:
for i=1:16
x(i,1:20) = i;
ca{i} = sprintf('Class %d', i);
end
imshow(x, [], 'InitialMagnification', 1600);
axis('on', 'image');
cmap = hsv(16);
colormap(cmap);
colorbar('Ticks', 1:16, 'TickLabels', ca)

类别

Help CenterFile Exchange 中查找有关 Blue 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by