how to crop an image

5 次查看(过去 30 天)
Dhandapani.S
Dhandapani.S 2015-1-23
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
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
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.

类别

Help CenterFile Exchange 中查找有关 Image Processing Toolbox 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by