Reputation: 473
I wish to crop this original image
to a new image which will contain only the bag with minimum white pixels (essentially reducing the size image to the bag borders)
Therefore I decided to first convert it to a binary image
but I do not know how to find the bag corner coordinates [xmin ymin width height] in order to use them with imcrop(I,rect).
Any help will be great.
The script:
clc;
close all;
url='http://oi65.tinypic.com/i19md1.jpg' ;
rgbImage = imread(url);
grayImage = rgb2gray(rgbImage);
binaryImage = grayImage < 250;
imshow(binaryImage);
Upvotes: 2
Views: 576
Reputation: 104503
That's a very easy task to perform. Since binaryImage
contains a mask that you want to use to crop the image, you can find the top-left corner (xmin,ymin)
of where you want to crop by finding the smallest column and row coordinate respectively that is non-zero in the mask, then to find width and height, find the bottom-right corner that is non-zero, then subtract the two x
coordinates for the width and the two y
coordinates for the height. You'll need to add 1 to each difference to account for self-distances (i.e. if you had a width that was 1 pixel wide, you should get a width of 1, not 0). You can use find
to help you find the row and column locations that are non-zero. However, imcrop
requires that the x
coordinates reflect horizontal behaviour and y
coordinates reflect vertical behaviour where find
returns row and column locations respectively. That's why you'll have to flip them when you call find
:
[y,x] = find(binaryImage); %// Find row and column locations that are non-zero
%// Find top left corner
xmin = min(x(:));
ymin = min(y(:));
%// Find bottom right corner
xmax = max(x(:));
ymax = max(y(:));
%// Find width and height
width = xmax - xmin + 1;
height = ymax - ymin + 1;
You can now go ahead and crop the image:
out = imcrop(rgbImage, [xmin ymin width height]);
imshow(out);
I get this for your cropped image:
Upvotes: 2