Remove white space from around image

77 views (last 30 days)
Martin
Martin on 14 Dec 2011
Answered: yanqi liu on 8 Nov 2021
Hello, I'm pretty new to MatLab, so I'm having a hard time doing some things with it. I have a grayscale jpg-image, with a very large white space around the actual image, which is dark. Is there an easy command, to remove the colors <250 from the image?
Regards, Martin

Answers (7)

DGM
DGM on 6 Nov 2021
Edited: DGM on 6 Nov 2021
It's never too late for reference answers ...
Reading the question, I assume that the intent is to crop the excess padding from the image, rather than to merely change it to black. I also assume that it's desired to do this automatically, or otherwise without the need to tediously calculate the RECT parameter for a call to imcrop() or direct subscript indexing.
There are a few tools on the File Exchange that can do this. @Reza Farrahi Moghaddam posted one which (as the name implies) can automatically crop off white padding. There is also this tool designed for cropping padding of uniform intensity. Lastly, MIMT has a function called cropborder() which can crop manually or automatically based on user-selected metrics. Let's demonstrate all three.
First, let's generate some test images. In each case, the image is displayed with a narrow black border simply so that it shows up against the awful white background of this webpage. The black border isn't part of the working image.
% original image
A = imread('peppers.png'); % 384x512
imshow(A);
% image with uniform-width solid white matting
B = padarray(A,[10 10],255,'both');
imshow(padarray(B,[2 2]));
% image with nonuniform-width solid white matting
C = padarray(A,[5 7],255,'pre');
C = padarray(C,[15 13],255,'post');
imshow(padarray(C,[2 2]));
% image with uniform-width solid gray matting
D = padarray(A,[10 10],200,'both');
imshow(padarray(D,[2 2]));
% image with noisy white padding
s = size(A);
E = uint8(randi([245 256],s(1)+20,s(2)+20,size(A,3)));
E(11:s(1)+10,11:s(2)+10,:) = A;
imshow(padarray(E,[2 2]));
If each of these images is passed to the aforementioned cropping tools, we can see what works and what doesn't. Again, the name implies that RemoveWhiteSpace() works only on white padding. It works well, but only if the padding is solid white.
% use RemoveWhiteSpace()
S1(1,:) = size(RemoveWhiteSpace(B)); % works fine for solid white padding
S1(2,:) = size(RemoveWhiteSpace(C)); % even uneven padding
S1(3,:) = size(RemoveWhiteSpace(D)); % but not unless it's white
S1(4,:) = size(RemoveWhiteSpace(E)); % and not unless it's solid
S1
S1 =
384 512 3
384 512 3
404 532 3
404 532 3
As its description suggests, crop_img() crops off padding of any solid color.
% use crop_img()
S2(1,:) = size(crop_img(B)); % works fine for uniform padding
S2(2,:) = size(crop_img(C)); % or nonuniform padding
S2(3,:) = size(crop_img(D)); % of any solid color
S2(4,:) = size(crop_img(E)); % but not unless it's solid
S2
S2 =
384 512 3
384 512 3
384 512 3
404 532 3
On the other hand, cropborder() looks for a change in edge variance when it searches for the image extents. It can crop noisy or patterned borders.
% use cropborder()
S3(1,:) = size(cropborder(B)); % works fine for uniform padding
S3(2,:) = size(cropborder(C,[NaN NaN NaN NaN])); % or nonuniform padding
S3(3,:) = size(cropborder(D)); % of any solid color
S3(4,:) = size(cropborder(E)); % or even patterned or noisy color
S3
S3 =
384 512 3
384 512 3
384 512 3
384 512 3

Sean de Wolski
Sean de Wolski on 14 Dec 2011
I(I>250) = 0; %sets them to black.
To to crop them you'll have to use a cropping tool such as imcrop or know the indices you wish to crop to.

Reza Farrahi Moghaddam
Reza Farrahi Moghaddam on 24 Feb 2012
You can try this tiny tool to remove white space around images:

hf fh
hf fh on 22 May 2018
Edited: Walter Roberson on 22 May 2018
But the problem is I have 20 images and I want to remove white space around images: How to apply 20 images to you the way I try but I can not..
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%dir folder
input_filename = '/Users/mac/Desktop/RemoveWhiteSpace/RemoveWhiteSpace/';
% % Check to make sure that folder actually exists. Warn user if it doesn't.
if ~isdir(input_filename)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', input_filename);
uiwait(warndlg(errorMessage));
return;
end
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(input_filename, '*.png'); % Change to whatever pattern you need.
theFiles = dir(filePattern);
for k = 1 :20
baseFileName = theFiles(k).name;
fullFileName = fullfile(input_filename, baseFileName);
u_in = mat2gray(imread(fullFileName));
imshow(u_in);
figure(k),
imshow(RemoveWhiteSpace(u_in));
RemoveWhiteSpace([], 'file', '*.png', 'output', 'test_out*.png');
saveas(figure(k),sprintf('%d.tif',k))
end

hf fh
hf fh on 22 May 2018
Edited: Walter Roberson on 22 May 2018
this good for 100 images
folder = '/Users/mac/Desktop/fiel2/RemoveWhiteSpace/RemoveWhiteSpace/semple';
%image3d = zeros(300, 300, 99, 'uint8');
for k = 1 : 99
% Read one image.
u_in = mat2gray(imread( fullfile(folder, sprintf('%d.tif', k) )));
%figure, imshow(u_in);
figure(k), imshow(RemoveWhiteSpace(u_in));
RemoveWhiteSpace([], 'file', sprintf('%d.tif', k) , 'output', sprintf('%d.png', k));
end

Image Analyst
Image Analyst on 7 Nov 2021
To remove a frame/border from a gray scale image you can simply use any() to determine which rows or columns are not part of the padding and extract only those rows:
grayImage = grayImage(any(grayImage~=paddingValue, 2), any(grayImage~=paddingValue, 1));
Here is a full demo with comment, displays, etc.:
% Demo by Image Analyst.
% Crop off uniform padding from outside border of image.
% This code is general enough to work with any padding value: 0, 255, or anything else.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clearvars;
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 16;
% Create the image padded with values of 162 all around. (Could be 255 or any value actually).
grayImage = imread('cameraman.tif');
% Pad the image
grayImage = padarray(grayImage, [15, 70], 162);
subplot(2, 2, 1)
imshow(grayImage);
impixelinfo
axis('on', 'image')
title('Original Padded Image')
% Determine the value of the padding by looking at the upper left pixel.
paddingGrayLevel = grayImage(1,1)
% Get a mask showing all pixels where the value is the padding value.
mask = grayImage == paddingGrayLevel;
subplot(2, 2, 2)
imshow(mask);
axis('on', 'image')
title('Mask of Padded Values')
% Find rows and columns where any of the values are NOT the padding gray level.
% If at least one value is not the padding value,
% then the row or column is not part of the padding/frame.
goodRows = any(~mask, 2);
goodColumns = any(~mask, 1);
% Extract the good rows and columns.
grayImage = grayImage(goodRows, goodColumns);
subplot(2, 2, 3)
imshow(grayImage);
axis('on', 'image')
title('Cropped Image with No Padding')
  4 Comments
DGM
DGM on 7 Nov 2021
That was kind of my point. I would expect something more like this from the first example:
A = imread('testmontage.png');
B = cropborder(A);
Whereas your example method will remove the padding between the images as well, since those vectors also have no non-padding content.
I think a bit of tolerance can help some with noisy edges if the contrast is good (it usually is for figure captures), but I went about it a bit differently due to the images I was dealing with at the time. The default method searches inward, looking for a significant increase in the variance of the image vectors parallel to the image boundary. It's not unbreakable, but that's why cropborder() has other available methods and an adjustable tolerance parameter. It also allows for use on images with obnoxious decorative patterned borders.
Image Analyst
Image Analyst on 7 Nov 2021
Edited: Image Analyst on 7 Nov 2021
Yes, different input images and different desired final appearances will require different code to be run.
For a common case of the user doing File/Save As... to save the figure (including a big white frame around it) as a PNG file, instead of using imwrite() to save the image alone, my original code will work fine.

Sign in to comment.


yanqi liu
yanqi liu on 8 Nov 2021
% I have a grayscale jpg-image, with a very large white space around the actual image,
% which is dark. Is there an easy command, to remove the colors <250 from the image?
clc; clear all; close all;
im = imread('https://ww2.mathworks.cn/matlabcentral/mlc-downloads/downloads/submissions/34898/versions/8/screenshot.png');
im2 = imcrop(im, [903 133 592 355]);
imt = im2;
im2 = rgb2gray(im2);
im2(im2>250) = median(im2(:));
figure('Color', 'c');
subplot(1,2,1); imshow(imt,[]);
subplot(1,2,2); imshow(im2,[]);

Community Treasure Hunt

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

Start Hunting!