Crop part of an image

Hi there.
i've an image : (120 * 160 px)
I want to crop part of that image where number is.
Finally result must be : (22 * 39 px)
Thank you for your help.

Answers (1)

Jan
Jan on 18 Apr 2013
Edited: Jan on 18 Apr 2013
You did not explain the type of the image variable. It might be a gray-scale image of type UINT8. Row a 3D array of an RGB image the procedure must be modified.
[row, col] = find(img);
cropped = img(min(col):max(col), min(row):max(row));
Note that the image might be transposed when it is displayed, so perhaps you have to swap row and col.

6 Comments

Hamed
Hamed on 18 Apr 2013
Edited: Hamed on 18 Apr 2013
When i tried :
img = imread('f:\en\2.jpg');
img = rgb2gray(img);
[row, col] = find(img);
and then this :
cropped = img(min(col):max(col), min(row):max(row));
I get error "Index exceeds matrix dimensions."
When swap row and col :
[col, row] = find(img);
Does't get any errors but 'cropped' variable does't crop that image!
Hamed
Hamed on 19 Apr 2013
Any body ?
I=imread('136626633118722_2.jpg');
img=rgb2gray(I);
[col, row] = find(img<250);
cropped = I(min(col):max(col), min(row):max(row));
imshow(cropped,'InitialMagnification','fit')
Ehsan R
Ehsan R on 19 Apr 2013
hi
i want to do the same thing for binary images
thanks a lot
Jan's code works for binary images. An alternate method would be to use regionprops() to get the bounding box, then use imcrop().
Flipped row & col.
>> z = blkdiag(zeros(1,3),[1 2; 3 0], zeros(3,1))
z =
0 0 0 0 0 0
0 0 0 1 2 0
0 0 0 3 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
>> [row, col]=find(z)
row =
2
3
2
col =
4
4
5
>> z(min(row):max(row), min(col):max(col))
ans =
1 2
3 0

Sign in to comment.

Tags

Asked:

on 18 Apr 2013

Commented:

on 21 Jun 2016

Community Treasure Hunt

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

Start Hunting!