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

6 views (last 30 days)
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)

Accepted Answer

jonas
jonas on 28 Sep 2018
Edited: jonas on 28 Sep 2018
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 Comments
jonas
jonas on 28 Sep 2018
Edited: jonas on 28 Sep 2018

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.

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 29 Sep 2018
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)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by