Search code examples
matlabimage-processingcropbounding-box

MATLAB Auto Crop


I am trying to automatically crop the image below to a bounding box. The background will always be the same colour. I have tried the answers at Find the edges of image and crop it in MATLAB and various applications and examples on Mathworks' file exchange but I get stuck at getting a proper boundingbox.

I was thinking to convert the image to black and white, converting it to binary and removing everything that's closer to white than black, but I'm not sure how to go about it.

PencilCase


Solution

  • Following the answer of Shai, I present a way to circumvent regionprops (image processing toolbox) just based on find on the black-white image.

    % load
    img = im2double(imread('https://i.sstatic.net/ZuiEt.jpg'));
    % black-white image by threshold on check how far each pixel from "white"
    bw = sum((1-img).^2, 3) > .5; 
    % show bw image
    figure; imshow(bw); title('bw image');
    
    % get bounding box (first row, first column, number rows, number columns)
    [row, col] = find(bw);
    bounding_box = [min(row), min(col), max(row) - min(row) + 1, max(col) - min(col) + 1];
    
    % display with rectangle
    rect = bounding_box([2,1,4,3]); % rectangle wants x,y,w,h we have rows, columns, ... need to convert
    figure; imshow(img); hold on; rectangle('Position', rect);