Black and White Optical illusion in MATLAB
MATLAB provides many toolboxes for different applications. The Image Processing Toolbox is one of the important toolboxes in MATLAB. The Black and White optical illusion in MATLAB happens when we compliment the pixel values in a black and white image and after staring at the center of the resultant image for a while and subsequently, we see the original black and white image.
The assumption being made here is that the input image is an RGB Image since that format is the most commonly used. For images defined in other color spaces, the first step would be to convert them to RGB and then implement the following approach.
Approach:
- Read the RGB Image.
- Find the size of the input image and then define another image using the dimensions obtained and initialize with zeros.
- Using the im2bw() method first convert the RGB Image to Binary Image.
- Using loops, complement the pixel values by writing condition statements. Pixels can be complemented using the unary NOT operator on each pixel as well.
- Display both the binary and complemented images.
We will implement the method using two images, first using the GFG Image. To successfully run the codes on the user’s local machine, it is essential that whatever image is being used as input must be in the same directory as the MATLAB Code file.
Example 1:
Matlab
% MATLAB code for Black and % White optical illusion % Reading RGB IMAGE A=imread( 'GFG.jpeg' ); % Finding dimensions of input image and % using that to define output image % dimensions and initialising with zeros. B = uint8(zeros(size(A))); % Converting RGB to Binary Image A=im2bw(A); % Loops for complementing pixel values. for i=1:size(A,1) for j=1:size(A,2) if (A(i,j)==0) B(i,j,:)=255; if (A(i,j)==255) B(i,j,:)=0; end end end end % Displaying both the binary % and complemented images. figure imshow(A); figure imshow(B); |
Output:
Now we will try to work with another image.
Example 2:
Matlab
% MATLAB code for Black & White illusion % Reading RGB IMAGE A=imread( 'Apple.jpeg' ); % Finding dimensions of input image % and using that to define output image % dimensions and initialising with zeros. B=uint8(zeros(size(A))); % Converting RGB to Binary Image A=im2bw(A); % Loops for complementing pixel values for i=1:size(A,1) for j=1:size(A,2) if (A(i,j)==0) B(i,j,:)=255; if (A(i,j)==255) B(i,j,:)=0; end end end end % Displaying both the input % and output images figure imshow(A); figure imshow(B); |
Output: