How to crop an image automatically?

12 views (last 30 days)
The following is my input Image. Here is there any possibility crop automatically that chromosome part? Because other parts are fully zero.

Accepted Answer

Image Analyst
Image Analyst on 30 Nov 2012
Try this:
clc;
close all;
workspace;
format longg;
format compact;
fontSize = 20;
% Read in a standard MATLAB gray scale demo image.
folder = 'C:\Users\Saba\Documents';
baseFileName = '24495081.jpg';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% File doesn't exist -- didn't find it there. Check the search path for it.
fullFileName = baseFileName; % No path this time.
if ~exist(fullFileName, '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
grayImage = imread(fullFileName);
% Get the dimensions of the image.
% numberOfColorBands should be = 1.
[rows columns numberOfColorBands] = size(grayImage)
% Display the original gray scale image.
subplot(2, 2, 1);
imshow(grayImage, []);
title('Original Grayscale Image', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Give a name to the title bar.
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')
% Get all rows and columns where the image is nonzero
[nonZeroRows nonZeroColumns] = find(grayImage);
% Get the cropping parameters
topRow = min(nonZeroRows(:));
bottomRow = max(nonZeroRows(:));
leftColumn = min(nonZeroColumns(:));
rightColumn = max(nonZeroColumns(:));
% Extract a cropped image from the original.
croppedImage = grayImage(topRow:bottomRow, leftColumn:rightColumn);
% Display the original gray scale image.
subplot(2, 2, 2);
imshow(croppedImage, []);
title('Cropped Grayscale Image', 'FontSize', fontSize);
  2 Comments
Joakim
Joakim on 18 Dec 2013
This works great, if I want to crop away a white Border can i just change the nonZeroRows/nonZeroColumns to some other value(if yes which?)
Image Analyst
Image Analyst on 18 Dec 2013
Yes. It depends on what rows and columns the border occurs in. If you have a binary (true/false) image, you can use imclearborder() to do it automatically.

Sign in to comment.

More Answers (1)

Nehal
Nehal on 3 Mar 2014
please send me this image which u have used. my email id is nehal7789@yahoo.com

Categories

Find more on Images in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!