2017-02-26 21 views

回答

2

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

开始通过加载图像和分离颜色:

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

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

only_green = green & ~(red | blue) 

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

要将生成的矩阵显示为图像,请使用imshow

1

为了使事情更有趣,我建议以下解决方案:

  1. 从RGB转换输入图像HSV。
  2. 标记HSV色彩空间中的绿色像素(在HSV色彩空间中,您可以选择其他颜色,如黄色(不仅是原色:红色,绿色,蓝色))。

为了强调环保,我设置多种颜色的灰度:

这里是我的代码:

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 as 1:
enter image description here

绿色和灰色:
enter image description here

相关问题