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

1 view (last 30 days)
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

Accepted Answer

Anton Semechko
Anton Semechko on 6 Feb 2012
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 Comments
lingru celine
lingru celine on 8 Feb 2012
@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 on 28 Sep 2016
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.

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 6 Feb 2012
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!