How can I invert a binary image in MATLAB?

38,622

Solution 1

If you have a binary image binImage with just zeroes and ones, there are a number of simple ways to invert it:

binImage = ~binImage;
binImage = 1-binImage;
binImage = (binImage == 0);

Then just save the inverted image using the function IMWRITE.

Solution 2

You can use imcomplement matlab function. Say you have a binary image b then,

bc = imcomplement(b); % gives you the inverted version of b
b = imcomplement(bc); % returns it to the original b
imwrite(bc,'c:\...'); % to save the file in disk

Solution 3

In Matlab, by using not we can convert 1's into 0's and 0's into 1's.

inverted_binary_image = not(binary_image)
Share:
38,622
Ofir A.
Author by

Ofir A.

Bachelor in Computer Science Passionate about programming.

Updated on September 19, 2020

Comments

  • Ofir A.
    Ofir A. over 3 years

    I have a binary image and need to convert all of the black pixels to white pixels and vice versa. Then I need to save the new image to a file. Is there a way to do this without simply looping over every pixel and flipping its value?

  • mikkola
    mikkola over 8 years
    This is a very inefficient solution compared to those presented earlier, and does not even consider the requested saving of the image.
  • gnovice
    gnovice over 6 years
    The not function is exactly what's called when using the ~ operator.