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 日
編集済み: 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.

カテゴリ

Help Center および File ExchangeImage Processing Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by