# Binarizing a matrix

I have an image with a few bright pixels with the remaining ones very dark. The difference is in orders of magnitude.

I want to binarize this matrix (corresponding to the image) making all values zero besides the few bright ones.

The function Binarize does what I want but it accepts only an image as an input. So indeed I can use the plot of the matrix as input but that messes up things because the image includes the axis, labels etc...

How can I do this? Any help will be appreciated.

-
What does your matrix look like? Binarize@Image[matrix] could work. – C. E. Jul 20 '14 at 0:35
@Pickett I chose to elaborate on that comment as there are unapparent details to be addressed. – Mr.Wizard Jul 20 '14 at 1:57
@Mr.Wizard That's a great answer. Very well written. +1. – C. E. Jul 20 '14 at 2:20

Clip seems perfectly suited:

mat = RandomReal[{0, 10}, {100, 100}];
Manipulate[
MatrixPlot[Clip[mat, {threshold, threshold}, {0, 1}]],
{threshold, 0, 10}
]


Here we use the form of Clip with three arguments:

Clip[mat, {threshold, threshold}, {0, 1}]


It takes everything below threshold and sets it to 0, and takes everything above threshold and sets it to 1. You can change both thresholds and the extreme values, eg

Clip[Range[10], {5, Infinity}, {0, 1}]


which sets everything below 5 to 0 and does nothing else (the 1 does nothing the way I wrote it).

-

As you note Binarize does just this:

Binarize[image,t]
creates a binary image by replacing all values above t with 1 and others with 0.

Therefore you merely need to convert your data into an Image. First some test data:

m = Array[Plus, {21, 21}, -10];
m // MatrixPlot


Now we convert to an Image:

img = Image[m]


Do not worry that the data already appears binarized; it is still there:

Image[data] by default allows any real number, but displays only values between 0 and 1.

We can still Binarize at any value within the range of the original array:

Binarize[img, #] & /@ {-18, -11, -4, 0, 4, 11, 18}


If you wish to recover the numeric data use ImageData:

Binarize[img, 11] // ImageData // MatrixPlot


-