Matlab 边界内图像区域的提取

Matlab 边界内图像区域的提取,matlab,image-segmentation,Matlab,Image Segmentation,我必须做一个项目,使用二维CT图像和分割肝脏和肿瘤使用Matlab(仅)。起初,我必须单独分割肝脏区域。我使用区域生长进行肝脏分割。它获取种子点作为输入 输出是一个带有肝脏区域边界的图像。现在我需要一个仅由边界包围的区域 我的程序有一个主程序和一个regionRowing.m函数。因为我是新用户,所以不允许发布图片。如果你需要图片,我会寄给你。请帮帮我 % mainreg.m IR=imread('nfliver5.jpg'); figure, imshow(IR), hold a

我必须做一个项目,使用二维CT图像和分割肝脏和肿瘤使用Matlab(仅)。起初,我必须单独分割肝脏区域。我使用区域生长进行肝脏分割。它获取种子点作为输入

输出是一个带有肝脏区域边界的图像。现在我需要一个仅由边界包围的区域

我的程序有一个主程序和一个regionRowing.m函数。因为我是新用户,所以不允许发布图片。如果你需要图片,我会寄给你。请帮帮我

  % mainreg.m

  IR=imread('nfliver5.jpg');
  figure, imshow(IR), hold all
  poly = regionGrowing(IR,[],15,1200); % click somewhere inside the liver
  plot(poly(:,1), poly(:,2), 'LineWidth', 2, 'Color', [1 1 1])

%regionRowing.m
函数[P,J]=区域行(cIM、initPos、thresVal、maxDist、tfMean、tfFillHoles、tfSimplify)
%二维/三维灰度图像的区域生长算法
%
%语法:
%P=区域划船();
%P=区域划船(cIM);
%P=区域划行(cIM,initPos)
%P=区域划船(…,thresVal,maxDist,tfMean,tfFillHoles,tfSimpl)
%[P,J]=区域划船(…);
%
%投入:
%cIM:2D/3D灰度矩阵{当前图像}
%initPos:初始种子位置{ginput position}的坐标
%thresVal:包含的绝对阈值水平{5%的最大最小值}
%maxDist:到[px]{Inf}中初始位置的最大距离
%tfMean:将初始值更新为区域平均值(慢){false}
%tfFillHoles:填充二进制掩码{true}中的封闭孔
%tfSimplify:减少顶点数{true,如果dpsimplify存在}
%
%产出:
%P:VxN数组(顶点数为V,维度数为N)
%P是所有相关像素/体素的封闭多边形
%J:二进制掩码(与输入图像大小相同)指示
%1(真)表示相关像素/体素,0(假)表示外部
%   
%示例:
%%2D示例
%负载示例
%图,imshow(cIM,[0 1500]),保留所有
%多边形=区域划船(cIM,[],300);%点击肺部的某个地方
%绘图(多边形(:,1),多边形(:,2),“线宽”,2)
%   
%%3D示例
%负荷磁共振成像
%多边形=区域划船(挤压(D),[66,55,13],60,Inf,[],真,假);
%绘图3(多边形(:,1),多边形(:,2),多边形(:,3),“x”,“线宽”,2)
%
%要求:
%适用于BWbounders()和axes2pix()的MathWorks图像处理工具箱
%可选:由Wolfgang Schwanghart简化线路,以减少
%多边形顶点数(请参见MATLAB文件交换)
%
%备注:
%队列未预先分配,区域平均值计算缓慢。
%我还没有为服务器实现预分配或队列计数器
%然而,为了清楚起见,这当然会更有效率。
%
%作者:
%Daniel Kellner,2011,谷歌邮箱.com
%历史记录:v1.00:2011/08/14
%检查输入参数时出错
如果nargin>7
错误('输入参数的数目错误!')
结束
如果~exist('cIM','var')
himage=findobj('Type','image');
如果I空(himage)| |长(himage)>1
错误('请定义一个当前图像!')
结束
cIM=get(himage,'CData');
结束
if~exist('initPos','var')| | isempty(initPos)
himage=findobj('Type','image');
如果我是空的(他的年龄)
himage=imshow(cIM,[]);
结束
%初始位置的图形用户输入
p=ginput(1);
%获取与当前轴坐标相关的像素位置
initPos(1)=round(axes2pix(大小(cIM,2),get(himage,'XData'),p(2));
initPos(2)=圆形(axes2pix(大小(cIM,1),get(himage,'YData'),p(1));
结束
if~exist('thresVal','var')| | isempty(thresVal)
thresVal=double(max(cIM(:)-min(cIM(:)))*0.05;
结束
if~exist('maxDist','var')| | isempty(maxDist)
maxDist=Inf;
结束
如果~exist('tfMean','var')| |为空(tfMean)
tfMean=false;
结束
if~exist('tfFillHoles','var')
tfFillHoles=true;
结束
如果相等(ndims(cIM),2)
initPos(3)=1;
elseif isequal(ndims(cIM),1)| | ndims(cIM)>3
错误('只允许使用二维图像和三维图像集!')
结束
[nRow、nCol、nSli]=大小(cIM);
如果initPos(1)<1 | | initPos(2)<1 | |。。。
initPos(1)>nRow | | initPos(2)>nCol
错误('初始位置超出范围,请重试!')
结束
如果thresVal<0 | | maxDist<0
错误('阈值和最大距离值必须为正!')
结束
if~isempty(which('dpsimplify.m'))
if~exist('tfSimplify','var')
tfSimplify=true;
结束
公差=1;
其他的
tf=false;
结束
%初始像素值
regVal=double(cIM(initPos(1)、initPos(2)、initPos(3));
%带有初始参数的文本输出
disp(['RegionRowing开口:初始位置('num2str(初始位置(1))。。。
“|”num2str(initPos(2))”|“num2str(initPos(3))”)与“。。。
num2str(regVal)'作为初始像素值!'])
%预分配阵列
J=假(nRow、nCol、nSli);
%将初始像素添加到队列中
队列=[initPos(1)、initPos(2)、initPos(3)];
%%%区域生长算法的开始
而大小(队列,1)
%第一个队列位置确定新值
xv=队列(1,1);
yv=队列(1,2);
zv=队列(1,3);
% .. 并删除第一个队列位置
队列(1,:)=[];
%检查邻居的当前位置
对于i=-1:1
对于j=-1:1
对于k=-1:1
如果xv+i>0&&xv+i0&&yv+j0&&zv+k0));%-->慢点!
结束
结束
结束
结束
结束
结束
%%%区域结束增长算法
%循环通过每个切片,填充孔并提取多边形顶点
P=[];
对于cSli=1:nSli
如果有(J(:,:,cSli))
持续
结束
%使用bwBounders()提取封闭多边形
如果TF填充孔
%把面具里面的洞填满
J(:,:,cSli)=imfill(J(:,:,cSli),‘孔’);
B=边界(J(:,:,cSli),8个“无孔”);
其他的
B=边界(J(:,:,cSli));
结束
新顶点=[B{1}(:,2),B{1}(:,1)];
%通过直线简化简化多边形
如果简化
newVertices=dpsimplify(newVertices,simplifyToleran
%regionGrowing.m

function [P, J] = regionGrowing(cIM, initPos, thresVal, maxDist, tfMean, tfFillHoles, tfSimplify)
% REGIONGROWING Region growing algorithm for 2D/3D grayscale images
%
% Syntax:
%   P = regionGrowing();
%   P = regionGrowing(cIM);
%   P = regionGrowing(cIM, initPos)
%   P = regionGrowing(..., thresVal, maxDist, tfMean, tfFillHoles, tfSimpl)
%   [P, J] = regionGrowing(...);
%
% Inputs:
%          cIM: 2D/3D grayscale matrix                      {current image}
%      initPos: Coordinates for initial seed position     {ginput position}
%     thresVal: Absolute threshold level to be included     {5% of max-min}
%      maxDist: Maximum distance to the initial position in [px]      {Inf}
%       tfMean: Updates the initial value to the region mean (slow) {false}
%  tfFillHoles: Fills enclosed holes in the binary mask              {true}
%   tfSimplify: Reduces the number of vertices {true, if dpsimplify exists}
%
% Outputs:
%   P: VxN array (with V number of vertices, N number of dimensions)
%      P is the enclosing polygon for all associated pixel/voxel
%   J: Binary mask (with the same size as the input image) indicating
%      1 (true) for associated pixel/voxel and 0 (false) for outside
%   
% Examples:
%   % 2D Example
%   load example
%   figure, imshow(cIM, [0 1500]), hold all
%   poly = regionGrowing(cIM, [], 300); % click somewhere inside the lungs
%   plot(poly(:,1), poly(:,2), 'LineWidth', 2)
%   
%   % 3D Example
%   load mri
%   poly = regionGrowing(squeeze(D), [66,55,13], 60, Inf, [], true, false);
%   plot3(poly(:,1), poly(:,2), poly(:,3), 'x', 'LineWidth', 2)
%
% Requirements:
%   TheMathWorks Image Processing Toolbox for bwboundaries() and axes2pix()
%   Optional: Line Simplification by Wolfgang Schwanghart to reduce the 
%             number of polygon vertices (see the MATLAB FileExchange)
%
% Remarks:
%   The queue is not preallocated and the region mean computation is slow.
%   I haven't implemented a preallocation nor a queue counter yet for the
%   sake of clarity, however this would be of course more efficient.
%
% Author:
%   Daniel Kellner, 2011, braggpeaks{}googlemail.com
%   History: v1.00: 2011/08/14


% error checking on input arguments
if nargin > 7
    error('Wrong number of input arguments!')
end

if ~exist('cIM', 'var')
    himage = findobj('Type', 'image');
    if isempty(himage) || length(himage) > 1
        error('Please define one of the current images!')
    end

    cIM = get(himage, 'CData');
end

if ~exist('initPos', 'var') || isempty(initPos)
    himage = findobj('Type', 'image');
    if isempty(himage)
        himage = imshow(cIM, []);
    end

    % graphical user input for the initial position
    p = ginput(1);

    % get the pixel position concerning to the current axes coordinates
    initPos(1) = round(axes2pix(size(cIM, 2), get(himage, 'XData'), p(2)));
    initPos(2) = round(axes2pix(size(cIM, 1), get(himage, 'YData'), p(1)));
end

if ~exist('thresVal', 'var') || isempty(thresVal)
    thresVal = double((max(cIM(:)) - min(cIM(:)))) * 0.05;
end

if ~exist('maxDist', 'var') || isempty(maxDist)
    maxDist = Inf;
end

if ~exist('tfMean', 'var') || isempty(tfMean)
    tfMean = false;
end

if ~exist('tfFillHoles', 'var')
    tfFillHoles = true;
end

if isequal(ndims(cIM), 2)
    initPos(3) = 1;
elseif isequal(ndims(cIM),1) || ndims(cIM) > 3
    error('There are only 2D images and 3D image sets allowed!')
end

[nRow, nCol, nSli] = size(cIM);

if initPos(1) < 1 || initPos(2) < 1 ||...
   initPos(1) > nRow || initPos(2) > nCol
    error('Initial position out of bounds, please try again!')
end

if thresVal < 0 || maxDist < 0
    error('Threshold and maximum distance values must be positive!')
end

if ~isempty(which('dpsimplify.m'))
    if ~exist('tfSimplify', 'var')
        tfSimplify = true;
    end
    simplifyTolerance = 1;
else
    tfSimplify = false;
end


% initial pixel value
regVal = double(cIM(initPos(1), initPos(2), initPos(3)));

% text output with initial parameters
disp(['RegionGrowing Opening: Initial position (' num2str(initPos(1))...
      '|' num2str(initPos(2)) '|' num2str(initPos(3)) ') with '...
      num2str(regVal) ' as initial pixel value!'])

% preallocate array
J = false(nRow, nCol, nSli);

% add the initial pixel to the queue
queue = [initPos(1), initPos(2), initPos(3)];


%%% START OF REGION GROWING ALGORITHM
while size(queue, 1)
  % the first queue position determines the new values
  xv = queue(1,1);
  yv = queue(1,2);
  zv = queue(1,3);

  % .. and delete the first queue position
  queue(1,:) = [];

  % check the neighbors for the current position
  for i = -1:1
    for j = -1:1
      for k = -1:1

        if xv+i > 0  &&  xv+i <= nRow &&...          % within the x-bounds?
           yv+j > 0  &&  yv+j <= nCol &&...          % within the y-bounds?          
           zv+k > 0  &&  zv+k <= nSli &&...          % within the z-bounds?
           any([i, j, k])       &&...      % i/j/k of (0/0/0) is redundant!
           ~J(xv+i, yv+j, zv+k) &&...          % pixelposition already set?
           sqrt( (xv+i-initPos(1))^2 +...
                 (yv+j-initPos(2))^2 +...
                 (zv+k-initPos(3))^2 ) < maxDist &&...   % within distance?
           cIM(xv+i, yv+j, zv+k) <= (regVal + thresVal) &&...% within range
           cIM(xv+i, yv+j, zv+k) >= (regVal - thresVal) % of the threshold?

           % current pixel is true, if all properties are fullfilled
           J(xv+i, yv+j, zv+k) = true; 

           % add the current pixel to the computation queue (recursive)
           queue(end+1,:) = [xv+i, yv+j, zv+k];

           if tfMean
               regVal = mean(mean(cIM(J > 0))); % --> slow!
           end

        end        
      end
    end  
  end
end
%%% END OF REGION GROWING ALGORITHM


% loop through each slice, fill holes and extract the polygon vertices
P = [];
for cSli = 1:nSli
    if ~any(J(:,:,cSli))
        continue
    end

    % use bwboundaries() to extract the enclosing polygon
    if tfFillHoles
        % fill the holes inside the mask
        J(:,:,cSli) = imfill(J(:,:,cSli), 'holes');    
        B = bwboundaries(J(:,:,cSli), 8, 'noholes');
    else
        B = bwboundaries(J(:,:,cSli));
    end

    newVertices = [B{1}(:,2), B{1}(:,1)];

    % simplify the polygon via Line Simplification
    if tfSimplify
        newVertices = dpsimplify(newVertices, simplifyTolerance);        
    end

    % number of new vertices to be added
    nNew = size(newVertices, 1);

    % append the new vertices to the existing polygon matrix
    if isequal(nSli, 1) % 2D
        P(end+1:end+nNew, :) = newVertices;
    else                % 3D
        P(end+1:end+nNew, :) = [newVertices, repmat(cSli, nNew, 1)];
    end
end

% text output with final number of vertices
disp(['RegionGrowing Ending: Found ' num2str(length(find(J)))...
      ' pixels within the threshold range (' num2str(size(P, 1))...
      ' polygon vertices)!'])
BW2 = imfill(BW,'holes');
% Outputs:
%   J: Binary mask (with the same size as the input image) indicating
%      1 (true) for associated pixel/voxel and 0 (false) for outside
  IR=imread('nfliver5.jpg');
  figure, imshow(IR), hold all
  [poly im] = regionGrowing(IR,[],15,1200); % click somewhere inside the liver
  imshow(im,[])
SEG = IR.*im;
imshow(SEG,[]) 
%Example coordinates, 
coordinates = [100 100 5] 
poly = regionGrowing(squeeze(IR), coordinates, 60, Inf, [], true, false);