Black and White Optical illusion in MATLAB
Last Updated :
17 Mar, 2022
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
A=imread( 'GFG.jpeg' );
B = uint8(zeros(size(A)));
A=im2bw(A);
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
figure
imshow(A);
figure
imshow(B);
|
Output:
Figure 1: Input image
Figure 2: Binary image of original RGB Image
Figure 3: The complemented image of Binary Image
Now we will try to work with another image.
Example 2:
Matlab
A=imread( 'Apple.jpeg' );
B=uint8(zeros(size(A)));
A=im2bw(A);
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
figure
imshow(A);
figure
imshow(B);
|
Output:
Figure 4: Input image
Figure 5: Binary Image of original RGB Image
Figure 6: Complemented Image of Binary Image
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...