im2bw.m

来自「有关matlab的电子书籍有一定的帮助希望有用」· M 代码 · 共 97 行

M
97
字号
function bwout = im2bw(p1,p2,p3,level)
%IM2BW Convert image to binary image by thresholding.
%   IM2BW produces binary images from indexed, intensity, or RGB
%   images. To do this, it converts the input image to grayscale
%   format (if it is not already an intensity image), and then
%   converts this grayscale image to binary by thresholding. The
%   output binary image BW has values of 0 (black) for all pixels
%   in the input image with luminance less than LEVEL and 1
%   (white) for all other pixels. (Note that you specify LEVEL in
%   the range [0,1], regardless of the class of the input image.)
%  
%   BW = IM2BW(I,LEVEL) converts the intensity image I to black
%   and white.
%
%   BW = IM2BW(X,MAP,LEVEL) converts the indexed image X with
%   colormap MAP to black and white.
%
%   BW = IM2BW(RGB,LEVEL) converts the RGB image RGB to black and
%   white.
%
%   Class Support
%   -------------
%   The input image can be of class uint8 or double. The output
%   image BW is of class uint8.
%
%   Example
%   -------
%   load trees
%   BW = im2bw(X,map,0.4);
%   imshow(X,map), figure, imshow(BW)
%
%   See also IND2GRAY, RGB2GRAY.

%   Clay M. Thompson 10-5-92
%   Copyright 1993-1998 The MathWorks, Inc.  All Rights Reserved.
%   $Revision: 5.9 $  $Date: 1997/11/24 15:35:11 $

if nargin==0,
  error('Need input arguments.');
end
threeD = (ndims(p1)==3); % Determine if input includes a 3-D array

if ~islogical(p1)  % Make sure we didn't get a binary image
   
   if nargin==1, % im2bw(I) or im2bw(RGB)
      if threeD,
         a = rgb2gray(p1);
      else
         a = p1;
      end
      level = [];
      
   elseif nargin==2, % im2bw(I,level), im2bw(a,cm), or im2bw(RGB,level)
      if threeD,
         a = rgb2gray(p1);
         level = p2;
      elseif size(p2,2)==3, % It is a colormap
         a = ind2gray(p1,p2);
         level = [];
      else
         a = p1;
         level = p2;
      end
      
   elseif nargin==3, % im2bw(r,g,b) or im2bw(a,cm,level)
      if all(size(p1)==size(p3)),
         a = rgb2gray(p1,p2,p3);
         level = [];
      else
         a = ind2gray(p1,p2);
         level = p3;
      end
      
   elseif nargin==4, % im2bw(r,g,b,level)
      a = rgb2gray(p1,p2,p3);
   end
   
   if isempty(level), % Get level from user
      level = 0.5; % Use default for now
   end
   
   if isa(a, 'uint8')
      bw = a >= 255*level;
   else
      bw = uint8(a >= level);
   end
   
else   % The input was alread binary
   bw = p1;
end

if nargout==0, % Show results
   imshow(bw,2)
   return
end
bwout = bw;

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?