MATLAB | Complement colors in a Binary image
Binary image is a digital image that has only two possible value for each pixel – either 1 or 0, where 0 represents white and 1 represents black. In the complement of a binary image, the image pixel having value zeros become ones and the image pixel having value ones become zeros; i.e white and black color of the image is reversed.
Complementing Binary image using MATLAB library function :
img=imread( 'geeksforgeeks.jpg' );
comp=imcomplement(img);
imshow(comp);
|
Complementing Binary image without using library function :
We can complement a binary image by subtracting each pixel value from maximum possible pixel value a binary image pixel can have (i.e 1 ), and the difference is used as the pixel value in the complemented image. It means if an image pixel have value 1 then, in complemented binary image same pixel will have value ( 1 – 1 ) = 0 and if Binary image pixel have value 0 then, in complemented binary image same pixel will have value ( 1 – 0 ) = 1.
Below is the Implementation of above idea-
function [complement] = complementBinary(img)
[x, y]=size(img);
complement=zeros(x, y);
for i=1:x
for j=1:y
complement(i, j) = 1-img(i, j);
end
end
end
img=imread( 'geeksforgeeks.jpg' );
comp=complementBinary(img);
imshow(result);
|
Alternate way :
In MATLAB, Arrays are basic data structure.They can be manipulated very easily. For example Array = 1 - Array ;
Above code will subtract each element of the array from 1. So, Instead of using two loops to subtract 1 to each pixel of binary image. We can directly write it as –
comp=1-img
Here ‘img’ is our binary image array.
Below code will also complement a binary Image
img=imread( 'geeksforgeeks.jpg' );
comp=1-img;
imshow(comp);
|
Input:
Output:
References : https://in.mathworks.com/help/images/ref/imcomplement.html
Last Updated :
12 Sep, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...