gusucode.com > 《matlab图像处理与界面编程宝典》秦襄培 编著,每章的MATLAB源代码程序 > 第24章/代码24-7.txt

    
RGB = imread('test.bmp');                     % 读入图像
figure,                                       % 新建窗口
imshow(RGB),                                  % 显示原始图像
title('Original Image');                      % 设置图像标题
GRAY = rgb2gray(RGB);                          % 图像灰度转换
figure,                                          % 新建窗口
imshow(GRAY),                                  % 显示处理后的图像
title('Gray Image');                               % 设置图像标题
threshold = graythresh(GRAY);                    % 阈值
BW = im2bw(GRAY, threshold);                     % 图像黑白转换
figure,                                          % 新建窗口
imshow(BW),                                      % 显示处理后的图像
title('Binary Image');                           % 设置图像标题
BW = ~ BW;                                       % 图像反色
figure,                                          % 新建窗口
imshow(BW),                                      % 显示处理后的图像
title('Inverted Binary Image');                  % 设置图像标题
 [B,L] = bwboundaries(BW, 'noholes');            % 寻找边界
STATS = regionprops(L, 'all'); % 其实只需要参数'BoundingBox'和'Extent',这样写程序简单点。
figure,                                            % 新建窗口
imshow(RGB),                                       % 显示原始图像
title('Results');                                  % 设置图像标题
hold on                                            % 继续绘图
for i = 1 : length(STATS)
  W(i) = uint8(abs(STATS(i).BoundingBox(3)-STATS(i).BoundingBox(4)) < 0.1);
  W(i) = W(i) + 2 * uint8((STATS(i).Extent - 1) == 0 );
  centroid = STATS(i).Centroid;
  switch W(i)
      case 1
          plot(centroid(1),centroid(2),'wO');
      case 2
          plot(centroid(1),centroid(2),'wX');
      case 3
          plot(centroid(1),centroid(2),'wS');
  end
end
return