如何在Matlab中将绿色像素标记为1?

时间:2017-02-26 04:18:20

标签: matlab

我需要将图像加载到Matlab中,并将绿色标记为1,并将其作为0标记,并显示最终图像。我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

这取决于图像,以及确定像素何时为绿色的标准。像素必须只有绿色,但没有蓝色或红色?如果是这样,这是一种方式。

首先加载图像并分离颜色:

image = imread('your_image.jpg');
red = image(:,:,1);
green = image(:,:,2);
blue = image(:,:,3);

然后,找到绿色但不是红色或蓝色的像素:

only_green = green & ~(red | blue)

如果你对绿色像素有不同的定义,那么你可以相应改变第二步。

要将结果矩阵显示为图像,请使用imshow

答案 1 :(得分:1)

为了让事情变得更有趣,我建议采用以下解决方案:

  1. 将输入图像从RGB转换为HSV。
  2. 在HSV颜色空间中标记绿色像素(在HSV颜色空间中,您可以选择其他颜色,如黄色(不仅是主要颜色:红色,绿色,蓝色)。)
  3. 为了强调绿色,我将其他颜色设置为灰度:

    这是我的代码:

    RGB = imread('peppers.png');
    HSV = rgb2hsv(RGB); %Convert RGB to HSV.
    
    figure;imshow(RGB);title('Original');
    
    %Convert from range [0, 1] to [0, 255] (kind of more intuitive...)
    H = HSV(:, :, 1)*255;
    S = HSV(:, :, 2)*255;
    V = HSV(:, :, 3)*255;
    
    %Initialize to zeros.    
    Green = zeros(size(H));
    
    %Needed trial and error to find the correct range of green (after Google searching).  
    Green(H >= 38 & H <=160 & S >= 50 & V >= 30) = 1; %Set green pixels to 1
    
    figure;imshow(Green);title('Mark Green as 1');
    
    %Play with it a little...
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    Gray = rgb2gray(RGB); %Convert to gray-scale
    
    R = RGB(:, :, 1);
    G = RGB(:, :, 2);
    B = RGB(:, :, 3);
    
    Green = logical(Green);
    
    R(~Green) = Gray(~Green);
    G(~Green) = Gray(~Green);
    B(~Green) = Gray(~Green);
    
    RGB = cat(3, R, G, B);
    
    figure;imshow(RGB);title('Green and Gray');
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    

    结果:

    原始图片:
    enter image description here

    Mark Green为1:
    enter image description here

    绿色和灰色:
    enter image description here