您的问题错过了“并用黑色替换其余部分”。这里有两种方法:
一个紧凑的解决方案:使用bsxfun:
newImage = bsxfun(@times, Image, cast(bw, 'like', Image));
虽然我对上一个很满意,但您也可以看看这个循序渐进的方法:
% separate the RGB layers:
R = image(:,:,1);
G = image(:,:,2);
B = image(:,:,3);
% change the values to zero or your desired color wherever bw is false:
R(~bw) = 0;
G(~bw) = 0;
B(~bw) = 0;
% concatenate the results:
newImage = cat(3, R, G, B);
这可以为您提供黑色区域的不同替换:
更新:
根据 cmets,bw 的false 区域应该替换为相同输入的灰度图像。这是实现它的方法:
image = imread('peppers.png');
thr = graythresh(image);
bw = im2bw(image, thr);
gr = rgb2gray(image); % generate grayscale image from RGB
newImage(repmat(~bw, 1, 1, 3)) = repmat(gr(~bw), 1, 1, 3); % substitude values
% figure; imshow(newImage)
有了这个结果: