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

9 visualizzazioni (ultimi 30 giorni)
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)

Risposta accettata

jonas
jonas il 28 Set 2018
Modificato: jonas il 28 Set 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 Commenti
Shivam Pande
Shivam Pande il 28 Set 2018
I wish to add the legends as Class1, Class2,..., Class16 in corresponding colors.
jonas
jonas il 28 Set 2018
Modificato: jonas il 28 Set 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.

Accedi per commentare.

Più risposte (1)

Image Analyst
Image Analyst il 29 Set 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)

Categorie

Scopri di più su Colormaps in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by