getobjectcrop.m

来自「This code can parse any image in matlab.」· M 代码 · 共 54 行

M
54
字号
function [crop,imgCrop,mask] = getObjectCrop(object, img)
% Compute object crop
% [crop,imgCrop,mask] = getObjectCrop(object, img)
% Input:
%   object:  D{:}.annotation.object(i) or D(:).annotation.object(i).parts(j)
%   img:     input image to be cropped
% 
% Output:
%   crop:    [4*1] matrix denote the crop boundary
%   imCrop:  cropped image
%   mask:    0/1 mask of the object


[nrows ncols c] = size(img);
X=[];Y=[];
Nregions = length(object.regions);
for i=1:Nregions
    [a,b] = getLHIpoints(object.regions(i));
    X = [X;a]; Y = [Y;b];
end

Nsubgraphs = length(object.subgraphs);
for i=1:Nsubgraphs
    Ncurves = length(object.subgraphs(i).curves);
    for j=1:Ncurves
        [a,b] = getLHIpoints(object.subgraphs(i).curves(j));
        X = [X;a]; Y = [Y;b];
    end
end
crop(1) = max(min(X)-2,1);
crop(2) = min(max(X)+2,ncols);
crop(3) = max(min(Y)-2,1);
crop(4) = min(max(Y)+2,nrows);
crop = round(crop);

if nargout > 1
    imgCrop = img(crop(3):crop(4), crop(1):crop(2), :);
end

%% A slow way to compute mask, a faster version is to make use of the labelmap
% Segmentation mask 
if nargout > 2 
    disp('Begin computing mask, it may take a few minutes if image is large');
    mask = logical(zeros(size(imgCrop,1),size(imgCrop,2)));
    [x,y] = meshgrid(1:size(imgCrop,2),1:size(imgCrop,1));
    for i=1:Nregions
        [a,b] = getLHIpoints(object.regions(i));
        a = a-crop(1);
        b = b-crop(3);
        mask = mask | logical(inpolygon(x, y, a, b));
    end
end

⌨️ 快捷键说明

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