我试图在Matlab中仅为图像的一部分着色。 例如,我加载一个RGB图像,然后我用Otsu的方法( graythresh )获得一个掩码。 我想在应用im2bw并将graythresh作为阈值后,仅将颜色保留在值为1的像素中。 例如:
image = imread('peppers.png'); thr = graythresh(image); bw = im2bw(image, thr);使用此代码,我获得以下二进制图像:
我的目标是将颜色保持在白色像素中。
谢谢!
I'm trying to color only a segment of an image in Matlab. For example, I load an RGB image, then I obtain a mask with Otsu's method (graythresh). I want to keep the color only in the pixels that have value of 1 after applying im2bw with graythresh as the threshold. For example:
image = imread('peppers.png'); thr = graythresh(image); bw = im2bw(image, thr);With this code I obtain the following binary image:
My goal is to keep the color in the white pixels.
Thanks!
最满意答案
关于如何更换我们不关心的像素,我有另一个建议。 这通过为bw图像中存在黑色像素的每个切片创建线性索引来工作。 find的结果是因为bw是image一个“切片”的大小,这就是我们获得其他2个切片的索引的方式。
启动MATLAB 2016b:
image(find(~bw)+[0 numel(bw)*[1 2]]) = NaN;在旧版本中:
image(bsxfun(@plus,find(~bw),[0 numel(bw)*[1 2]])) = NaN;然后imshow(image)给出:
请注意,对于整数类 , NaN将转换为0 。
在澄清其他像素应保持灰色版本后,请参阅以下代码:
% Load image: img = imread('peppers.png'); % Create a grayscale version: grayimg = rgb2gray(img); % Segment image: if ~verLessThan('matlab','9.0') && exist('imbinarize.m','file') == 2 % R2016a onward: bw = imbinarize(grayimg); % Alternatively, work on just one of the color channels, e.g. red: % bw = imbinarize(img(:,:,1)); else % Before R2016a: thr = graythresh(grayimg); bw = im2bw(grayimg, thr); end output_img = repmat(grayimg,[1 1 3]); colorpix = bsxfun(@plus,find(bw),[0 numel(bw)*[1 2]]); output_img(colorpix) = img(colorpix); figure; imshow(output_img);仅使用红色通道进行二值化时的结果:
I have another suggestion on how to replace the pixels we don't care about. This works by creating linear indices for each of the slices where black pixels exist in the bw image. The summation with the result of find is done because bw is the size of just one "slice" of image and this is how we get the indices for the other 2 slices.
Starting MATLAB 2016b:
image(find(~bw)+[0 numel(bw)*[1 2]]) = NaN;In older versions:
image(bsxfun(@plus,find(~bw),[0 numel(bw)*[1 2]])) = NaN;Then imshow(image) gives:
Note that NaN gets converted to 0 for integer classes.
Following the clarification that the other pixels should be kept in their gray version, see the below code:
% Load image: img = imread('peppers.png'); % Create a grayscale version: grayimg = rgb2gray(img); % Segment image: if ~verLessThan('matlab','9.0') && exist('imbinarize.m','file') == 2 % R2016a onward: bw = imbinarize(grayimg); % Alternatively, work on just one of the color channels, e.g. red: % bw = imbinarize(img(:,:,1)); else % Before R2016a: thr = graythresh(grayimg); bw = im2bw(grayimg, thr); end output_img = repmat(grayimg,[1 1 3]); colorpix = bsxfun(@plus,find(bw),[0 numel(bw)*[1 2]]); output_img(colorpix) = img(colorpix); figure; imshow(output_img);The result when binarizing using only the red channel:
更多推荐
发布评论