I have a matrix A = [0 1 4 2; 1 2 0 3; 0 1 1 0; 1 0 3 1]. How can i automatically set all pixels less than 3 to zero and pixels equal or greater than 3 to one.
MATLAB: Elimination based on threshold
threshold
Related Solutions
See my demo (simply copy and paste):
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;% Change the current folder to the folder of this m-file.
if(~isdeployed) cd(fileparts(which(mfilename)));end % Check that user has the Image Processing Toolbox installed.
hasIPT = license('test', 'image_toolbox');if ~hasIPT % User does not have the toolbox installed.
message = sprintf('Sorry, but you do not seem to have the Image Processing Toolbox.\nDo you want to try to continue anyway?'); reply = questdlg(message, 'Toolbox missing', 'Yes', 'No', 'Yes'); if strcmpi(reply, 'No') % User said No, so exit.
return; endend% Read in a standard MATLAB gray scale demo image.
folder = fullfile(matlabroot, '\toolbox\images\imdemos');baseFileName = 'cell.tif';fullFileName = fullfile(folder, baseFileName);% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);if ~exist(fullFileName, 'file') % 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.', fullFileName); uiwait(warndlg(errorMessage)); return; endendgrayImage = 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, 'Position', get(0,'Screensize')); set(gcf,'name','Demo by ImageAnalyst','numbertitle','off') % Threshold the image.
binaryImage = grayImage >= 70 & grayImage <= 130;% Display the binary image.
subplot(2, 2, 2);imshow(binaryImage, []);title('Binary Image', 'FontSize', fontSize);% Mask the image.
maskedImage = grayImage; % Initialize.
maskedImage(~binaryImage) = 0;% Display the masked image.
subplot(2, 2, 3);imshow(maskedImage, []);title('Masked Image', 'FontSize', fontSize);msgbox('Done with demo!');
GA solver is stochastic in nature, there should be no reason to expect the same results as that of linprog. Infact you may not even get the same results for two successive runs of GA.
However there are ways to make the results closer by including a hybrid solver. Change the opts as follows:
opts = gaoptimset('StallGenLimit',500,'Generations',500,'TolFun',1e-1,'HybridFcn',@fmincon);
More info here:
Best Answer