Matlab - How to binarize a grayscale image with multiple thresholds?

1.5k views Asked by At

I am trying to convert a grayscale image into a binary image with two thresholds:

  • img = a grayscale image
  • b = the output binary image
  • if (img > t1) or (img < t2) then b = 1
  • otherwise b = 0
t1 = 200;
t2 = 100;
src = imread('an rgb image');
img = reg2gray(src);
b1 = imbinarize(img, t1);
b2 = imbinarize(img, -t2);
b = imadd(b1,b2);

but this code doesn't work. Is there a way to set multiple thresholds at the same time?

2

There are 2 answers

2
MichaelTr7 On BEST ANSWER

A conditional statement can be applied to the array. When the condition is true the values of the initialized array are set to 1 and the rest of the cells of the array are set to 0.

Binarize Image

RGB_Image = imread("RGB_Image.png");
Grayscale_Image = rgb2gray(RGB_Image);

imshow(Grayscale_Image);
Threshold_1 = 220;
Threshold_2 = 100;

Binary_Image = ((Grayscale_Image > Threshold_1) | (Grayscale_Image < Threshold_2));

subplot(1,2,1); imshow(RGB_Image);
title("RGB Image");
subplot(1,2,2); imshow(Binary_Image);
title("Binary Image");
3
Ander Biguri On

Use logical matrices.

b=(img>t1) | (img<t2);