% img-原始图像(灰度或彩色)
% label-目标标签(非负整数)
% color-每个类的颜色(大小为N*3的矩阵)
% alpha-每个类颜色的不透明度(N*1的矩阵)
function colorimg = drawlabel2image(img,label,color,alpha)
[row,col,dim] = size(img);
% 检测是灰度图还是彩色图
if dim==1
img = cat(3,img,img,img);
elseif dim==3
else
error('请输入灰度图或RGB图')
end
% 预处理
img = im2double(img);
label = uint16(label);
nlabel = max(label(:));
% color修正:如果"分类数量>提供的颜色",会利用循环自动增加颜色
while size(color,1)<nlabel
color = cat(1,color,color);
end
% color修正:如果"分类数量<<提供的颜色",会利用循环自动分配颜色
if size(color,1)>2*nlabel
gap = floor(size(color,1)/nlabel);
color = color(1:gap:end,:);
end
% alpha修正:如果"分类数量>提供的透明度",会利用循环自动增加透明度
alpha = alpha(:);
while length(alpha)<nlabel
alpha = cat(1,alpha,alpha);
end
% 保留背景(非目标部分)
mask = double(label>0);
bg = img.*double(~mask);
% 各label上色
obj = zeros(row,col,3,nlabel);
for idx = 1:nlabel
objmask = double(label==idx);
R = img(:,:,1).*objmask*(1-alpha(idx))+objmask*color(idx,1)*alpha(idx);
G = img(:,:,2).*objmask*(1-alpha(idx))+objmask*color(idx,2)*alpha(idx);
B = img(:,:,3).*objmask*(1-alpha(idx))+objmask*color(idx,3)*alpha(idx);
obj(:,:,:,idx) = cat(3,R,G,B);
end
colorimg = sum(obj,4)+bg;
end
测试代码
clear;clc;close all;
im = imread('./1.png');
label1 = imread('./2.png');
label2 = imread('./3.png');
label3 = imread('./4.png');
label4 = imread('./5.png');
label5 = imread('./6.png');
% 调色
color1 = [0 0.4470 0.7410];
alpha = 0.4;
colorimg1 = drawlabel2image(im,label1,color1,alpha);
color2 = [0.8500 0.3250 0.0980];
%color2 = [1,0,0; 0,1,0; 0,0,1; 1,1,0; 0,1,1];
colorimg2 = drawlabel2image(colorimg1,label2,color2,alpha);
color3 = [0.4940 0.1840 0.5560];
%color2 = [1,0,0; 0,1,0; 0,0,1; 1,1,0; 0,1,1];
colorimg3 = drawlabel2image(colorimg2,label3,color3,alpha);
color4 = [0.4660 0.6740 0.1880];
%color2 = [1,0,0; 0,1,0; 0,0,1; 1,1,0; 0,1,1];
colorimg4 = drawlabel2image(colorimg3,label4,color4,alpha);
color5 = [0.6350 0.0780 0.1840];
%color2 = [1,0,0; 0,1,0; 0,0,1; 1,1,0; 0,1,1];
colorimg5 = drawlabel2image(colorimg4,label5,color5,alpha);
% 显示
figure
subplot(1,1,1), imshow(colorimg5)
``
效果展示:
注:有参考 存档用