# Conditionally binarizing matrices

I want to (fastly) convert matrices with values that are <= a threshold to binary matrices.

I used a call to Binarize, but I don't like the Image and ImageData conversions as they obfuscate the code. This code is also meant to be didactical and I obtain the matrices from real images in the real use case.

I couldn't write a faster thing using conditionals.

Suggestions?

-
Boole[Map[#<=95&,mat,{2}]]? – IPoiler Jan 22 at 1:31
Please post correctly formatted, copy-and-pastable Mathematica code instead of screenshots (at 581 rep, you must have heard this by now, right?). – march Jan 22 at 3:20

mat = {{209, 64, 112}, {8, 96, 253}, {65, 200, 95}};
Unitize[mat, 95];


This is fast, but not faster than your version:

mat = RandomInteger[{1, 300}, {1000, 1000}];
Unitize[mat, 95]; // AbsoluteTiming // First
ImageData[Binarize[Image[mat], 94]]; // AbsoluteTiming // First
UnitStep[mat - 95]; // AbsoluteTiming // First
Boole[Map[# <= 95 &, mat, {2}]]; // AbsoluteTiming // First
Sign[mat - 95] /. {-1 -> 0}; // AbsoluteTiming // First


and

mat = RandomInteger[{1, 300}, {10000, 10000}];
Unitize[mat, 95]; // AbsoluteTiming // First
ImageData[Binarize[Image[mat], 94]]; // AbsoluteTiming // First
UnitStep[mat - 95]; // AbsoluteTiming // First


-
The only potential issue with Unitize is numbers less than -t will be 1, not 0. But if OP's matrices have nonnegative elements, it's not a problem. – Chip Hurst Jan 22 at 16:16
@ChipHurst. Yeah, I actually always forget about that behavior of Unitize. I imagine in this case it's good, since he obtains the data from images. – march Jan 22 at 16:48

I think this does what you're asking for.

t = 95;
M = {{209, 64, 112}, {8, 96, 253}, {65, 200, 95}};

UnitStep[M - t]

{{1, 0, 1}, {0, 1, 1}, {0, 1, 1}}

-

You can also use the Sign function, though you have to replace the -1 with 0

Sign[m - t] /. {-1 -> 0}

-