在Matlab中仅颜色图像的一个片段 [英] Color only a segment of an image in Matlab

查看:1058
本文介绍了在Matlab中仅颜色图像的一个片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Matlab中只对图像的一段进行着色。例如,我加载一个RGB图像,然后我用Otsu的方法( graythresh )获得一个掩码。在将 im2bw 应用于 1 > graythresh 作为阈值。例如:

  image = imread('peppers.png'); 
thr = graythresh(image);
bw = im2bw(image,thr);

使用此代码,我获得以下二进制映像:





我的目标是以保持白色像素的颜色。



谢谢!

解决方案

我有另一个建议,如何替换我们不关心的像素。这通过为 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) / p>



请注意 NaN 转换为 0 ,用于


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!

解决方案

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:

这篇关于在Matlab中仅颜色图像的一个片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆