MATLAB Answers

YT
0

Remove white padding from image

Asked by YT
on 14 Oct 2018 at 0:11
Latest activity Answered by Image Analyst
on 14 Oct 2018 at 15:19

I want to remove white padding from an image (see attachment). The size of the padding is random.

So I was thinking of reading in the image and then some looping to check if the entire row/column contains the value 255. However, looping is most of the time not the best way to do stuff. So I'm wondering if there's an easier way to do this, because I've found a similar question where the rows/columns contain 0, but I don't know if this can also be used for this case (with some adjustments).

Thanks in advance.

  0 Comments

Sign in to comment.

2 Answers

Answer by Walter Roberson
on 14 Oct 2018 at 4:03
 Accepted Answer

I = imread('test-image.jpg');
W = all(I == 255, 3);
maskc = all(W, 1);
maskr = all(W, 2);
J = I;
J(maskr,:,:) = 0;
J(:,maskc,:) = 0;
image(J)

  2 Comments

YT
on 14 Oct 2018 at 12:00

While I'll accept this answer because it helped me out, the result of your code will not remove the padding from the image but rather makes it black (changes 255 to 0).

With that being said, I combined this answer and the answer you provided in the question I mentioned earlier to fix the issue.

    %read image
    I = imread('test-image.jpg');
    [~,~,d] = size(I);
    %255 to 0
    W = all(I == 255, 3);
    maskc = all(W, 1);
    maskr = all(W, 2);
    J = I;
    J(maskr,:,:) = 0;
    J(:,maskc,:) = 0;
    % remove 0 rows/columns from R/G/B
    for i = 1:d
        K = J(:,:,i);
        K( ~any(K,2), : ) = [];  %rows
        K( :, ~any(K,1) ) = [];  %columns
        switch i
            case 1
                R = K;
            case 2
                G = K;
            case 3
                B = K;
            otherwise
                warning('Unexpected value');
        end
    end
    IM = cat(3, R, G, B);
    imshow(IM);

"remove white padding" is ambiguous as to whether it should be transformed to a different color or cropped out of the image.

I = imread('test-image.jpg');
W = all(I == 255, 3);
maskc = ~all(W, 1);
maskr = ~all(W, 2);
J = I(maskr, maskc);
imshow(IM);

Sign in to comment.


Answer by Image Analyst
on 14 Oct 2018 at 15:19

Try this:

rgbImage = imread('test-image.jpg');
subplot(2, 2, 1);
imshow(rgbImage);
title('Original RGB Image', 'FontSize', 20);
axis('on', 'image');
nonWhitePixels = any(rgbImage ~= 255, 3);
subplot(2, 2, 2);
imshow(nonWhitePixels)
title('Non-white Pixels Mask', 'FontSize', 20);
axis('on', 'image');
[maskRows, maskColumns] = find(nonWhitePixels);
% Crop image
croppedImage = rgbImage(min(maskRows):max(maskRows), min(maskColumns):max(maskColumns), :);
subplot(2, 2, 3);
imshow(croppedImage);
axis('on', 'image');
title('Cropped RGB Image', 'FontSize', 20);

  0 Comments

Sign in to comment.