MATLAB: Threshold image code correction

codecorrectionthreshold

fact=0.1;
I=imread('8.jpg');
i=im2bw(I);
imax=max(max(i));
imin=min(min(i));
L=fact*(imax-imin)+imin;
thre=max(i,L.*ones(size(i)));
colormap(gray);
imagesc(i)
imagesc(thre)
I have to do thresholding of these sphere.. From this written code i get this secong figure.. it can't be done correctly even by changing factor.. So, help me.?

Best Answer

Try this:
clc;
clearvars;
close all;
imtool close all; % Close all imtool figures.
workspace;
format longg;
format compact;
fontSize = 20;
% Read in gray scale demo image.
folder = 'C:\Users\Lalit\Documents';
baseFileName = '8.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')
% Let's compute and display the histogram.
[pixelCount grayLevels] = imhist(grayImage);
subplot(2, 2, 2);
bar(pixelCount);
grid on;
title('Histogram of original image', 'FontSize', fontSize);
xlim([0 grayLevels(end)]); % Scale x axis manually.
% Threshold the image.
binaryImage = grayImage <= 50;
% Fill holes.
binaryImage = imfill(binaryImage, 'holes');
% Display the binary image.
subplot(2, 2, 3);
imshow(binaryImage, []);
title('Binary Image', 'FontSize', fontSize);
% Mask the image.
maskedImage = grayImage; % Initialize.
maskedImage(~binaryImage) = 0; % Do the masking.
% Display the masked image,
% scaling its intensity for better viewing.
subplot(2, 2, 4);
imshow(maskedImage, []);
title('Masked Image', 'FontSize', fontSize);