用另一种颜色替换图像中的某种颜色 Matlab

Replace a certain color in an image with another color Matlab

我有一张使用 imshow 在 Matlab 中打开的图像,我想用新颜色 (150,57,80) 替换值 (140,50,61) 的每个像素的颜色.如果有人可以告诉我该怎么做。

假设A是输入图像数据,这可能是一种方法-

%// Initialize vectors for old and new pixels tuplets
oldval = [140,50,61]
newval = [150,57,80]

%// Reshape the input array to a 2D array, so that each column would
%// reprsent one pixel color information. 
B = reshape(permute(A,[3 1 2]),3,[])

%// Find out which columns match up with the oldval [3x1] values
matches  = all(bsxfun(@eq,B,oldval(:)),1)
%// OR matches = matches = ismember(B',oldval(:)','rows')

%// Replace all those columns with the replicated versions of oldval
B(:,matches) = repmat(newval(:),1,sum(matches))

%// Reshape the 2D array back to the same size as input array
out = reshape(permute(B,[3 2 1]),size(A))

样本运行-

>> A
A(:,:,1) =
   140   140   140
    40   140   140
A(:,:,2) =
    50    20    50
    50    50    50
A(:,:,3) =
    61    65    61
    61    61    61
>> out
out(:,:,1) =
   150   140   150
    40   150   150
out(:,:,2) =
    57    20    57
    50    57    57
out(:,:,3) =
    80    65    80
    61    80    80

bsxfun 是我解决它的方式。但是,如果您不熟悉它,您可以从图像中提取每个通道,为每个通道使用三个逻辑掩码,然后使用 logical AND 将它们全部组合起来。执行 AND 将在您的图像中找到那些寻找特定 RGB 三元组的像素。

因此,我们相应地设置每个通道的输出并重建图像以产生输出。

因此,根据您的输入图像 A,可以这样做:

red = A(:,:,1); green = A(:,:,2); blue = A(:,:,3);
mred = red == 140; mgreen = green == 50; mblue = blue == 61;
final_mask = mred & mgreen & mblue;
red(final_mask) = 150; green(final_mask) = 57; blue(final_mask) = 80;
out = cat(3, red, green, blue);