Convert a grayscale image into a black-white image in MATLAB without im2bw

In MATLAB there is a function ‘im2bw’ which converts an input image into a black&white image. You can provide the function with a level of thresholding otherwise the default value is 0.5.

Here I show you how to implement the same functionality in a few lines of code. Check out the following function:

function S = my_im2bw(Ig,level)
S = Ig;
S(Ig > level) = 1;
S(Ig <= level) = 0;
end

Now let’s compare this function with the one of MATLAB:

Ig = rgb2gray(im2double(imread('test.png')));
level = 0.4;
B1 = im2bw(Ig,level);
B2 = my_im2bw(Ig,level);

The result is shown here:

test_im2bw

 

About machinelearning1

This weblog is about Machine Learning and all related topics that one needs to challenge real world with artificial intelligence.
This entry was posted in Linux, Machine Learning, MATLAB, OpenCV, Optimization, programming, Software, Ubuntu and tagged , , , , , , , , , , , , , , , , , , , , , , , , , , , . Bookmark the permalink.

2 Responses to Convert a grayscale image into a black-white image in MATLAB without im2bw

  1. Haider says:

    you need to elaborate more about this .

    • In a grayscale image each pixel has a value between 0 and 1 (or scaled to 0 and 255 in some cases). In a black and white image, each pixel is either white or black (1 or 0). So converting a grayscale image to an BW image is actually deciding which pixels should be black and which ones should become white. So you define a threshold and then use an If-else statement. I hope this clarifies the post.

Leave a comment