MATLAB: Crop greyscale image using matlab

image analysisimage processingImage Processing Toolbox

hello. I have a greyscale image (512x512x3) which is attached below. i want to crop it. it has 512 x 512 pixels however the data i am interested in is the middle of the image (non-white area). I tried the imcrop command but it only allowed me to crop in rectangular areas. How can i crop such that all pixels with intensity of 255 are cropped from the image? I think doing so will crop the image such along the border of the non-white area of the image. I have verified using impixelinfo that the intensities of the region of interest are all less that 255.

Best Answer

Try this:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
%===============================================================================
% Read in a standard MATLAB gray scale demo image.
folder = pwd;
baseFileName = 'PAR1_1.jpg';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% The file doesn't exist -- didn't find it there in that folder.
% Check the entire search path (other folders) for the file by stripping off the folder.
fullFileNameOnSearchPath = baseFileName; % No path this time.
if ~exist(fullFileNameOnSearchPath, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
rgbImage = imread(fullFileName);
% Get the dimensions of the image.
% numberOfColorChannels should be = 1 for a gray scale image, and 3 for an RGB color image.
[rows, columns, numberOfColorChannels] = size(rgbImage);
% Display the image.


subplot(2, 2, 1);
imshow(rgbImage, []);
title('Original Color Image', 'FontSize', fontSize, 'Interpreter', 'None');
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0, 1, 1]);
% Get rid of tool bar and pulldown menus that are along top of figure.
% set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
grayImage = rgb2gray(rgbImage);
binaryImage = imfill(grayImage ~= 255, 'holes');
binaryImage = bwareafilt(binaryImage, 1); % Extract only the largest.
% Display the image.
subplot(2, 2, 2);
imshow(binaryImage, []);
title('Binary Image', 'FontSize', fontSize, 'Interpreter', 'None');
labeledImage = bwlabel(binaryImage);
props = regionprops(labeledImage, 'BoundingBox');
% Crop the image
croppedImage = imcrop(grayImage, props.BoundingBox);
% Display the image.
subplot(2, 2, 3:4);
imshow(croppedImage, []);
title('Cropped Image', 'FontSize', fontSize, 'Interpreter', 'None');
Related Question