MATLAB Answers


Display gray color only from grayscale image

Asked by Demons
on 17 Jan 2013

Hi all

Apology for my ignorance as this is quite new to me.

I'm currently working on MRI images and have tried numerous times using some thresholding methods to display gray area of MRI image/s but to no avail.

Any pixel with grayscale value (0-255) of less than 5 & more than 250 will be eliminated and thus only showing pixels within 6-249.

Any helps are much appreciated.

Regards Demon


The places where those pixels were: do you need those places to be transparent?

on 17 Jan 2013

transparent or black if that matter.


No products are associated with this question.

3 Answers

Answer by Image Analyst
on 17 Jan 2013
 Accepted answer

You can alter the image to mask out (set to zero) those pixels with gray levels outside 5 and 250 inclusive:

darkPixels = grayImage <= 5;
lightPixels = grayImage >= 250;
pixelsToExclude = darkPixels  | lightPixels;
grayImage(pixelsToExclude) = 0;

Is that what you want to do?


Here, run this demo and see what it does. I think you'll like it. I believe it does what you asked me for. Copy, paste, change the filename and folder, then run.

clc;    % Clear the command window.
close all;  % Close all figures (except those of imtool.)
imtool close all;  % Close all imtool figures.
clear;  % Erase all existing variables.
workspace;  % Make sure the workspace panel is showing.
fontSize = 20;
format compact
% Read in a demo image.
folder = 'C:\Users\Mark\Documents\Temporary';
baseFileName = 'bodyslice.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);
grayImage = imread(fullFileName);
% Get the dimensions of the image.  
% numberOfColorBands should be = 1.
[rows columns numberOfColorBands] = size(grayImage)
if numberOfColorBands > 1
	% Convert to grayscale.
	grayImage = rgb2gray(grayImage);
% Display the original gray scale image.
subplot(2, 3, 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') 
% Let's compute and display the histogram.
[pixelCount grayLevels] = imhist(grayImage);
% Suppress the lowest bin
pixelCount(1) = 0;
subplot(2, 3, 2); 
grid on;
title('Histogram of original image', 'FontSize', fontSize);
xlim([0 grayLevels(end)]); % Scale x axis manually.
% Threshold the image.
binaryImage = grayImage >= 200;
% Display the image.
subplot(2, 3, 3);
imshow(binaryImage, []);
title('Binary Image', 'FontSize', fontSize);
% Get their areas
labeledImage = bwlabel(binaryImage);
blobMeasurements = regionprops(binaryImage, 'Area');
% Now I'll demonstrate how to select certain blobs based using the ismember function.
% Let's say that we wanted to find only thh largest blob.
allBlobAreas = [blobMeasurements.Area];
% Get a list of the blobs that meet our criteria and we need to keep.
[areaOfLargestBlob, labelOfLargestBlob] = max(allBlobAreas)
% Extract only those blobs that meet our criteria, and
% eliminate those blobs that don't meet our criteria.
% Note how we use ismember() to do this.
keeperBlobsImage = ismember(labeledImage, labelOfLargestBlob);
% Display the image.
subplot(2, 3, 4);
imshow(keeperBlobsImage, []);
title('Largest Blob in Binary Image', 'FontSize', fontSize);
% Let's fill interior holes.
binaryImage = imfill(keeperBlobsImage, 'holes');
% Display the image.
subplot(2, 3, 5);
imshow(binaryImage, []);
title('Binary Image, filled and dilated', 'FontSize', fontSize);
% Get rid of everything outside the largest blob
% by taking the inverse of the convex hull
convexHull = bwconvhull(binaryImage);
% We'll hang on to this.  We will use it later on the gray scale image.
% Let's enlarge it a little.
binaryImage = imdilate(binaryImage, true(31));
% Display the image.
subplot(2, 3, 5);
imshow(binaryImage, []);
title('Binary Image, filled and dilated', 'FontSize', fontSize);
% Combine convex hull and largest blob to get the pixels to erase.
pixelsToErase = ~convexHull | binaryImage;
% Display the image.
subplot(2, 3, 6);
imshow(pixelsToErase, []);
title('Pixels to Erase', 'FontSize', fontSize);
promptMessage = sprintf('Now we will erase these pixels in the lower right from the original image.');
titleBarCaption = 'Continue?';
button = questdlg(promptMessage, titleBarCaption, 'OK', 'Cancel', 'OK');
if strcmpi(button, 'Cancel')
% Use this binary image to mask out the original image.
grayImage(pixelsToErase) = 0;
% Display the image.
subplot(2, 3, 6);
imshow(grayImage, []);
title('Gray Image, no Adipose', 'FontSize', fontSize);
uiwait(helpdlg('Done with demo! Thanks Image Analyst!'));
on 18 Jan 2013

One word man - WOW!

This will save at least a good few weeks of my life. Really appreciate your effort.

If you happen to drop in Manchester someday, let me know.

You're welcome. The closest I get is Newcastle. But good luck with your project.

Answer by Amith Kamath
on 17 Jan 2013

For most tasks of analysing pixel values and thresholding, I've found very useful.

You could use:

[levelLow bwLow] = thresh_tool(IM); 
[levelHi bwHi] = thresh_tool(IM);
%to get the mask for each of the lower and upper level in bw.

depending on the datatype of your image, you can then just do an and operation between your image and the bw images.

  1 Comment

on 17 Jan 2013

Hi buddy

Thanks for your response. Appreciate that.

But gosh that was huge! Have you any idea of a much simpler one?

Answer by Jurgen
on 17 Jan 2013

imshow(I,[6 249]) 

if it's a 2D image slice you want to visualize.

  1 Comment

on 17 Jan 2013

hi bud

i've tried that before and nothing changed.

Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!