Steve on Image Processing

March 15th, 2006

Quick tip: Use the functions true and false

All I've been doing this week is writing. Unfortunately, I haven't been writing blog postings. Between my other work responsibilities and an upcoming trip, I have almost no time left for this blog until sometime next week.

Just to keep it going, though, here's a quick tip. I saw some code recently that looked something like this:

B = zeros(size(A));
B = logical(B);

The intent of the code was to initialize an all-zero binary image with the same size as A. Note, however, that the output of the zeros function in the first line is a double-precision array, which requires eight bytes per element. Logical arrays in MATLAB, on the other hand, use only one byte per element. It's quicker and more memory efficient to initialize B using the false function.

The functions true and false are most often seen without input arguments, in which case they return a scalar logical 1 or a scalar logical 0, respectively. But they also support an optional size input. So the following code works just as well for initializing the binary image:

B = false(size(A));

Note: The true and false functions were introduced in MATLAB 6.5.

Leave a Reply

Wrap code fragments inside <pre> tags, like this:

<pre class="code">
a = magic(3);
sum(a)
</pre>

If you have a "<" character in your code, either follow it with a space or replace it with "&lt;" (including the semicolon).


Steve Eddins manages the Image & Geospatial development team at The MathWorks and coauthored Digital Image Processing Using MATLAB. He writes here about image processing concepts, algorithm implementations, and MATLAB.

  • Sana: hi steve, could you explain to me how i would be able to use the dir function, to do a loop through a directory...
  • Nishtha: Sir, I have preprocessed the image in following steps: [1] adaptive histogram equalization [2] thresholding...
  • Kristof: I also strongly support the idea. I have just recently bumped into the problem that im2single was not...
  • Steve: David—I’ m glad you found it useful!
  • David Lalejini: I found your example very useful for finding connected nodes in a large set of input pairs. I start...
  • tommy: Dear Steve, I have a question,please if you are kind to help me regarding the accumulator array dimensions of...
  • Steve: Abc—I don’t know how to distinguish the faces. You might try posting your question in the MATLAB...
  • Manju: well if we have a few ovals within each other like in a cell how do we measure the distance from the center...
  • Steve: Manju—What do you mean? How is each region defined?
  • Manju: if we have 2-3 regions within each other how do we measure the regions of each one?

These postings are the author's and don't necessarily represent the opinions of The MathWorks.