how to crop an image

4 vues (au cours des 30 derniers jours)
Dhandapani.S
Dhandapani.S le 23 Jan 2015
I have an image like the one below. i have to crop the image eliminating the extra white space outside the black rectangle box. so that i can also reduce the size of the image. i have to crop until i encounter the first pixel row and column wise.
it should be like this attachement after cropping

Réponses (2)

Matz Johansson Bergström
Matz Johansson Bergström le 23 Jan 2015
Modifié(e) : Matz Johansson Bergström le 23 Jan 2015
In my answer I throw away the green and blue channels of the PNG, because it is black/white. If you want to use a color image, the technique is similar.
im = imread('cropp.png');
image(im)
im2 = 255 - im(:,:,1); %check only red component and map white=0
%x limits
xlim = sum(im2); %sum the columns
x(1) = find(xlim, 1, 'first') %x min
x(2) = find(xlim, 1, 'last') %x max
%y limits
ylim = sum(im2, 2); %sum the rows
y(1) = find(ylim, 1, 'first') %y min
y(2) = find(ylim, 1, 'last') %y max
%verification: line([x(1), x(2), x(2), x(1), x(1)], [y(1),y(1),y(2),y(2),y(1)],... 'color','red','linewidth',1)
%the cropping in practice: cropped = im(y(1):y(2), x(1):x(2));
figure
image(cropped)
I basically just find the limits of the image by summing along the x and y axis and finding the index of the non-zero first and last occurance of these elements.
I just added a call to "line" In my example, so you can follow.
  2 commentaires
Image Analyst
Image Analyst le 23 Jan 2015
Yes, but I'd avoid using xlim and ylim for variable names since these are built in functions and if you use them for variable names, you will blow away those useful functions. I'd call them horizontalProfile and verticalProfile, respectively.
Matz Johansson Bergström
Matz Johansson Bergström le 24 Jan 2015
Yes, good point. I named a variable sum once and it got very confusing very quickly.

Connectez-vous pour commenter.


Shoaibur Rahman
Shoaibur Rahman le 23 Jan 2015
I don't see any image attached. Anyway, you can try with:
roipoly to select the image region and crop manually, or imcrop to let the program to do that if you already know the image 'coordinates' to crop.

Community Treasure Hunt

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

Start Hunting!

Translated by