![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/2cf5e0fe9925bc314a654a4758df8db1cb137030?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)
function [r,p] = colorreplace(fn,c1,c2,cc)
% 将名为 fn 的图片的RGB颜色 c1 替换为 c2
% fn: 带路径的图片文件名
% c1,c2: RGB颜色 [r g b];
% cc: 容差,c1 颜色的容许漂移范围
% p: 源图片
% r: 替换后图片
p = imread(fn);
c10 = fix(c1-(1-cc)*c1);
c11 = c1+(1-cc)*c1;
c11(c11==0) = (1-cc)*255;
c11(c11>255) = 255;
r = p;
[m,n,k] = size(p);
if k==3
L = logical(ones(m,n));
for i = 1:k
a = r(:,:,i);
l = a>=c10(i) & a<=c11(i);
L = L & l;
end
for i = 1:k
a = r(:,:,i);
a(L) = c2(i);
r(:,:,i) = a;
end
end
% 调用并显示
fn = '000.jpg';
c1 = [255 0 0];
c2 = [0 0 0];
cc = 0.5;
[r,p] = colorreplace(fn,c1,c2,cc);
subplot(121); imshow(p);
subplot(122); imshow(r);