Why "grey level slicing image with background" is not showing any image in this code?

35 views (last 30 days)
%grey level slicing with background
p=imread('cameraman.tif');
z=double(p);
[m,n]=size(p);
for i=1:m
for j=1:n
if((z(i,j))>50)&&(z(i,j)<150)
z(i,j)=255;
else
z(i,j)=p(i,j); %condition for grey level slicing with background
end
end
end
figure(1);
imshow(p)
title('orignal image')
figure(2);
imshow(z)
title('grey level slicing with background')

Accepted Answer

Walter Roberson
Walter Roberson on 6 Sep 2015
Edited: Walter Roberson on 6 Sep 2015
Initialize
z = p;
and then only modify the pixels that need to be changed to 255. You may wish to use logical indexing. For example
R(R>1234) = 789;

More Answers (2)

Image Analyst
Image Analyst on 6 Sep 2015
This is just thresholding and then masking. As Walter said, you can do it more simply (with no for loop) by:
mask = (z > 50) & (z < 150);
z(mask) = 255;
Of course your display statement
imshow(z);
will show only white because, for some unknown reason, you converted z to double. For double images beyond the range of 0-1, you must use [] to have them display:
imshow(z, []);
If by "grey level slicing with background" you meant that you want to view certain bit planes (0, 1, 2, 3, 4, 5, 6, or 7), then see my attached demo (below this image it creates).
  1 Comment
Suparna Kumar
Suparna Kumar on 26 Jan 2017
Thank you so much for answering! I had the exact same question. Turns out I didn't use the square brackets in imshow

Sign in to comment.


Olivier
Olivier on 25 Jan 2022
Increasing the contrast within the region of interest only.
based on 'Image Analyst' (see above)
% open the image coins.png
I=imread('coins.png');
%Use imtool with the matrix containing the image grey level to identify the range of grey levels within the coins.
% imtool(I)
% Most pixels are between 100 and 240
MinPixel = 90, MaxPixel =255
MinPixel = 90
MaxPixel = 255
% to improve use median filter on the background only to remove light grey
% pixels
% initialise your output images
ImgSliced=I;
CoinsEnhanced=0*I;
% find all the coins based on pixel values
CoinsMask = (I>= MinPixel) & ( I <=MaxPixel);
% set pixels inside the coin to white
ImgSliced(CoinsMask) = 255;
% increase the contrast within the coins
CoinsEnhanced(CoinsMask) =round((I(CoinsMask)-MinPixel)*1.7); % could be any transform
% and set the background to another grey level
CoinsEnhanced(~CoinsMask) =230; % could be any value or another transform
% note that having a single grey level as background does not feel 'right'
% for human vision.
figure(1)
clf
subplot(221),imshow(I),title('original image')
subplot(222),imshow(ImgSliced),title('grey level slicing mask')
subplot(223),imshow(CoinsEnhanced),title('coins enhanced')

Community Treasure Hunt

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

Start Hunting!