create an black and white image in matlab

To create a black and white image in Matlab, there are multiple ways, some of which are listed below:

Method 1: Using the rgb2gray function

The rgb2gray function converts an RGB image to a grayscale image by taking the weighted average of the red, green, and blue components. A grayscale image has only one color channel (a.k.a., intensity channel) but it has the same width and height as the original image.

main.m
% Read an RGB image
rgbImage = imread('peppers.png');

% Convert to grayscale using rgb2gray function
grayImage = rgb2gray(rgbImage);

% Display the grayscale image
imshow(grayImage);
184 chars
9 lines

Method 2: Using the im2bw function

The im2bw function converts a grayscale image to a black and white image by applying a threshold to the pixel values. All pixels with values below the threshold are set to 0 (black) and all pixels with values above the threshold are set to 1 (white).

main.m
% Read a grayscale image
grayImage = imread('cameraman.tif');

% Convert to black and white using im2bw function
bwImage = im2bw(grayImage);

% Display the black and white image
imshow(bwImage);
195 chars
9 lines

Method 3: Using logical indexing

You can create a black and white image from scratch by defining a binary matrix of values either 0 or 1. You can then use logical indexing to set the corresponding pixels in your original image to black or white.

main.m
% Read an RGB image
rgbImage = imread('peppers.png');

% Create a binary matrix of size equal to the image
bwMatrix = false(size(rgbImage,1), size(rgbImage,2));

% Define a threshold for red, green, and blue components
redThreshold = 100;
greenThreshold = 120;
blueThreshold = 70;

% Set the corresponding pixels to 1 based on the threshold
bwMatrix(rgbImage(:,:,1) > redThreshold & rgbImage(:,:,2) > greenThreshold & rgbImage(:,:,3) < blueThreshold) = true;

% Display the black and white image
imshow(bwMatrix);
514 chars
17 lines

gistlibby LogSnag