Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

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

2 Answers 2

Clip seems perfectly suited:

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

enter image description here

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).

share|improve this answer

As you note Binarize does just this:

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

enter image description here

Now we convert to an Image:

img = Image[m]

enter image description here

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}

enter image description here

If you wish to recover the numeric data use ImageData:

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

enter image description here

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.