how to crop an image

조회 수: 4 (최근 30일)
Dhandapani.S
Dhandapani.S 2015년 1월 23일
댓글: Matz Johansson Bergström 2015년 1월 24일
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

답변 (2개)

Matz Johansson Bergström
Matz Johansson Bergström 2015년 1월 23일
편집: Matz Johansson Bergström 2015년 1월 23일
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
Image Analyst
Image Analyst 2015년 1월 23일
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 2015년 1월 24일
Yes, good point. I named a variable sum once and it got very confusing very quickly.

댓글을 달려면 로그인하십시오.


Shoaibur Rahman
Shoaibur Rahman 2015년 1월 23일
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