Remove white padding from image

조회 수: 10 (최근 30일)
YT
YT 2018년 10월 14일
댓글: Nate Roberts 2020년 4월 1일
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.

채택된 답변

Walter Roberson
Walter Roberson 2018년 10월 14일
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)
  댓글 수: 3
Walter Roberson
Walter Roberson 2018년 10월 14일
"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);
Nate Roberts
Nate Roberts 2020년 4월 1일
This is exactly what I was looking for. I made a little script that can do this for an RBG image, assuming you only want to remove the padding, and not the white space within an image.
function im2 = removeWhitePadding(im1, dim)
if nargin<2
dim = 0;
end
WhitePixels = all(im1 == 255, 3);
maskr = ~all(WhitePixels, 2);
maskc = ~all(WhitePixels, 1);
if dim==1
im2 = im1(find(maskr, 1, 'first'):find(maskr, 1, 'last'),:,:);
elseif dim==2
im2 = im1(:,find(maskc, 1, 'first'):find(maskc, 1, 'last'),:);
else
im2 = im1(find(maskr, 1, 'first'):find(maskr, 1, 'last'),find(maskc, 1, 'first'):find(maskc, 1, 'last'),:);
end
end

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2018년 10월 14일
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);

Community Treasure Hunt

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

Start Hunting!

Translated by