Program for Threshold in MATLAB
In this post, we implement image thresholding in MATLAB. Thresholding is one of the simplest and most widely used segmentation techniques. It converts a grayscale image into a binary image by comparing each pixel's intensity against a threshold value: pixels below the threshold are set to 0 (black) and pixels at or above the threshold are set to 255 (white). This cleanly separates foreground objects from the background. MATLAB Code % Image Thresholding in MATLAB % Converts a grayscale image to binary using a user-supplied threshold. % Pixels below the threshold -> 0 (black) % Pixels >= threshold -> 255 (white) clc; % Clear the command window clear all; % Clear all workspace variables % --- Load image --- % Place your image in the MATLAB working directory. originalImage = imread('sample.jpg'); % Read the colour image grayImage = rgb2gray(originalImage); % Convert to grayscale imageSize = size(grayImage); % [rows, cols] % --- Get threshold from user --- thresholdValue = input('Enter threshold value (0-255) : '); % e.g. 128 % --- Apply threshold --- binaryImage = grayImage; % Copy to preserve border pixels for i = 1 : imageSize(1) for j = 1 : imageSize(2) if grayImage(i, j) black else binaryImage(i, j) = 255; % At or above threshold -> white end end end % --- Display results --- subplot(1, 2, 1); imshow(grayImage); title('Original Grayscale Image'); subplot(1, 2, 2); imshow(binaryImage); title(['Thresholded at ', num2str(thresholdValue)]);