How to crop out the object from the image and then store the objects in the image?

1 次查看(过去 30 天)
I able to detect centroid of each objects in the image, and I require to crop out each objects from the image THEN to store it in different variable.How to crop the objects and store it in different variable?? I need coding... thanks

采纳的回答

Anton Semechko
Anton Semechko 2012-2-6
Assuming you have Image Processing Toolbox you can try the code below. You can also easily modify it to suit your needs.
% Get the image
im=imread('http://i43.tinypic.com/2w1tlwh.jpg');
im=rgb2gray(im); % convert to gray scale
im=im>graythresh(im)*255; % covert to binary
siz=size(im); % image dimensions
% Label the disconnected foreground regions (using 8 conned neighbourhood)
L=bwlabel(im,8);
% Get the bounding box around each object
bb=regionprops(L,'BoundingBox');
% Crop the individual objects and store them in a cell
n=max(L(:)); % number of objects
ObjCell=cell(n,1);
for i=1:n
% Get the bb of the i-th object and offest by 2 pixels in all
% directions
bb_i=ceil(bb(i).BoundingBox);
idx_x=[bb_i(1)-2 bb_i(1)+bb_i(3)+2];
idx_y=[bb_i(2)-2 bb_i(2)+bb_i(4)+2];
if idx_x(1)<1, idx_x(1)=1; end
if idx_y(1)<1, idx_y(1)=1; end
if idx_x(2)>siz(2), idx_x(2)=siz(2); end
if idx_y(2)>siz(1), idx_y(2)=siz(1); end
% Crop the object and write to ObjCell
im=L==i;
ObjCell{i}=im(idx_y(1):idx_y(2),idx_x(1):idx_x(2));
end
% Visualize the individual objects
figure
for i=1:n
subplot(1,n,i)
imshow(ObjCell{i})
end
clear im L bb n i bb_i idx_x idx_y siz
  6 个评论
lingru celine
lingru celine 2012-2-8
@Anton Semechko
I could not understand,what's the meaning of
" if idx_x(1)<1, idx_x(1)=1; end
if idx_y(1)<1, idx_y(1)=1; end
if idx_x(2)>siz(2), idx_x(2)=siz(2); end
if idx_y(2)>siz(1), idx_y(2)=siz(1); end" ?
can explain for me ?
Anurag
Anurag 2016-9-28
The code works just fine. But I am concerned about the noise around the man. Why there are so many dots around it. Help me remove it please.

请先登录,再进行评论。

更多回答(1 个)

Image Analyst
Image Analyst 2012-2-6
I do cropping of objects to separate variables (images) in my BlobsDemo image segmentation tutuorial http://www.mathworks.com/matlabcentral/fileexchange/25157-blobsdemo

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by