MATLAB 中的黑白视错觉
MATLAB 为不同的应用程序提供了许多工具箱。 Image Processing Toolbox 是 MATLAB 中的重要工具箱之一。 MATLAB 中的黑白错觉发生在我们对黑白图像中的像素值进行补充时,在凝视结果图像的中心一段时间后,我们会看到原始的黑白图像。
这里的假设是输入图像是 RGB 图像,因为这种格式是最常用的。对于在其他颜色空间中定义的图像,第一步是将它们转换为 RGB,然后实现以下方法。
方法:
- 阅读 RGB 图像。
- 找到输入图像的大小,然后使用获得的尺寸定义另一个图像并用零初始化。
- 使用 im2bw() 方法首先将 RGB 图像转换为二进制图像。
- 使用循环,通过编写条件语句来补充像素值。也可以在每个像素上使用一元 NOT运算符对像素进行补码。
- 显示二进制和补充图像。
我们将使用两个图像来实现该方法,首先使用 GFG 图像。要在用户的本地机器上成功运行代码,任何用作输入的图像都必须与 MATLAB 代码文件位于同一目录中。
示例 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);
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);
输出:

图 1:输入图像

图 2:原始 RGB 图像的二值图像

图 3:二值图像的补充图像
现在我们将尝试使用另一个图像。
示例 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);
输出:

图 4:输入图像

图 5:原始 RGB 图像的二值图像

图 6:二值图像的互补图像