Find the edges of image and crop it in MATLAB

前端 未结 3 1319
孤街浪徒
孤街浪徒 2021-01-16 12:52

I have a RGB image. I have scanned the image. So the image occupies a small portion of an A4 size sheet.

I want to find the border of the image and crop it. I could

3条回答
  •  悲&欢浪女
    2021-01-16 12:57

    Since this is an rgb image, there will be apparent color in the gray areas, but there should be none in the white ones. You can make use of this to find the image, then you can get the bounding box.

    img = imread('http://i.stack.imgur.com/dEawA.jpg');
    %# instead of "==" you can check for similarity within a tolerance
    tt=img(:,:,1)==img(:,:,2) & img(:,:,2) == img(:,:,3);
    

    enter image description here

    %# invert tt so that it's 1 where there is signal
    tt = ~tt;
    
    %# clean up some of the smaller artifacts
    tto = imopen(~tt,strel('square',100));
    

    enter image description here

    %# get the areas and bounding box of the areas above threshold
    %# as an additional criterion, you could also use excentricity
    %# or you could simply remove the bottom 100 rows of the scan
    stats = regionprops(tto,'BoundingBox','Area');
    area = cat(1,stats.Area);
    [~,maxAreaIdx] = max(Area);
    bb = round(stats(maxAreaIdx).BoundingBox);
    
    %# note that regionprops switches x and y (it's a long story)
    croppedImage = img(bb(2):bb(2)+bb(4),bb(1):bb(1)+bb(3),:);
    

    enter image description here

    There is a bit of a border left due to rotation. You can use the mask tto above to set all non-image pixels to NaN before cropping, or you can use imrotate to fix your image.

提交回复
热议问题