0

我在 MATLAB 中有一个我读入的 RGB 图像(M x N x 3 矩阵)。我还有一个用于图像的二进制掩码(M x N 矩阵),对于某些感兴趣的区域来说它只是 0,而在其他任何地方都是 1。

我试图弄清楚如何用该二进制掩码来掩码 RGB 图像。我尝试过更改数据类型(使用 double 或 uint8 来查看结果是否更改,但有时它们不会更改或我收到错误)并且我尝试使用各种函数,如 conv2、immultiply、imfilter 等.

我目前所做的是尝试将蒙版单独应用(因为它的大小为 M x N)到原始图像的每个 R、G 和 B 通道。在掩码为 0 的任何地方,我都希望在原始图像中准确地设为 0,而在掩码为 1 的任何地方,我只想不理会。

到目前为止,上述这些功能似乎都不起作用。显然,我知道可行的方法是,如果我刚刚经历并通过所有这些进行了 for 循环,但这将是可怕的,因为 MATLAB 有这些图像函数,但我似乎无法让它们工作。

有时 imfilter 或 immultiply (取决于我如何处理图像)只会让 MATLAB 完全停止并崩溃。有时他们很快就完成了,但我要么得到全白图像,要么得到全黑图像(通过 imshow 和 imagesc)。

我已经检查以确保我的图像通道的大小与蒙版匹配,并且我已经检查了图像和蒙版中的值,它们是正确的。我似乎无法让实际的掩蔽操作起作用。

请问有什么想法吗?也许我在 MATLAB 的规则中遗漏了一些东西?

这是当前的尝试:

% NOTE: The code may not be "elegant" but I\'ll worry about optimization later.
%
% Setup image and size
image = imread(im);
[numrows, numcols, temp] = size(image); % not used currently

% Request user polygon for ROI
bw = roipoly(image);

% Set up the mask -- it is indeed all 0's and 1's
t = double(imcomplement(bw));

% "Mask" the image
z = double(image);    % Double to match up with t as a double
z(:, :, 1) = imfilter(z(:, :, 1), t);
z(:, :, 2) = imfilter(z(:, :, 2), t);
z(:, :, 3) = imfilter(z(:, :, 3), t);
imshow(z); figure; imagesc(z);

==================

编辑

发现以下工作:

im_new = im_old .* repmat(mask, [1,1,3]);   % if both image and mask are uint8
imshow(im_new);
4

1 回答 1

5

你在imfilter()那里滥用。Imfilter 用于线性过滤操作,而不是用于掩蔽或阈值处理。最好这样做:

z = image;          % image() is also a function. 
                    % Overwriting this name should be avoided

% Request user polygon for ROI
bw = roipoly(z);

% Create 3 channel mask
mask_three_chan = repmat(bw, [1, 1, 3]);

% Apply Mask
z(~mask_three_chan) = 0;

% Display
imshow(z);
于 2013-09-14T20:51:55.903 回答