-2

I have a grayscale image that only has the values 60 and 117. How can I convert the image to only black and white without graylevels?

I tried the matlab function gray2ind, but didn't get the expected output.

Thanks.

Oleg
  • 9,719
  • 1
  • 26
  • 55
Simplicity
  • 41,347
  • 81
  • 231
  • 358

1 Answers1

4

Try im2bw(img, level) with level = 0.5.

This is a matlab function that takes a grayscale image img, applies a threshold of level (a value between [0,1]) and returns a black and white image.

This function is part of the Image Processing Toolbox. Your case is simple enough that you could also try something like:

bwImg = false(size(img));
bwImg(img == 117) = true;

I edited the above to set values equal to false/true to more closely mimic Matlab's im2bw() which returns a matrix of logical values rather than ints.

2nd Edit: Modified the code block to reflect improvements suggested by @Amro

Ryan J. Smith
  • 1,130
  • 8
  • 15
  • Or use [`grathresh()`](http://www.mathworks.co.uk/help/images/ref/graythresh.html) to determine `level`. – Oleg Apr 27 '13 at 12:39
  • 1
    since the image has only two levels, you can simplify as: `bwImg = (img==117);`. btw initialize with `false(size(img))` instead of `zeros` to get logical matrix – Amro Apr 27 '13 at 15:38
  • Thanks for your replies. Can I extend that to 3,4,5,...etc values? My question here: http://stackoverflow.com/questions/16252146/converting-a-grayscale-image-to-black-and-white – Simplicity Apr 27 '13 at 16:01
  • You should be able to extend it to any number of values by changing `bwImg(img == 117) = true` to `bwImg(img > threshold) = true` for any value you choose for `threshold`. – Ryan J. Smith Apr 27 '13 at 16:02
  • @Ryan J. Smith. How would one choose the threshold? Is it empirical? Say we have three values for the pixels in an image: 17, 56, and 180. What may be a suitable threshold for that? Would it be suitable for instance to set the threshold as the maximum value between pixels? Thanks – Simplicity Apr 27 '13 at 16:25
  • 1
    The choice of threshold is completely dependent upon your intentions in converting an image to black and white to begin with. In your example you really only have 2 meaningful values to threshold at (17, 56). Thresholding below 17 or above 180 would result in an uninteresting image. In a broader application you might examine a histogram of your original pixel values via `hist(img)` to get a better idea for a threshold value. – Ryan J. Smith Apr 27 '13 at 16:34