MATLAB中的bitxor操作

时间:2010-06-13 15:50:39

标签: matlab image-processing

我试图理解为什么原始图像没有附带此代码。生成的图片receive颜色为黄色,而不是与图片Img_new相似。

Img=imread(‘lena_color.tif’);
Img_new=rgb2gray(img);
Send=zeroes(size(Img_new);
Receive= zeroes(size(Img_new);
Mask= rand(size(Img_new);
for i=1 :256
    for j=1:256
        Send(i,j)=xor( Img_new(i,j),mask(i,j));
    End
End

image(send);
imshow(send);

for i=1 :256
    for j=1:256
        receive(i,j)=xor( send(i,j),mask(i,j));
    End
End

image(receive);
imshow(receive);

我做错了什么?

1 个答案:

答案 0 :(得分:5)

您的代码中存在几个问题。

  1. MATLAB区分大小写,因此endEnd不一样。 receivesend也是如此。
  2. MATLAB有很多基于矩阵的操作,所以使用for循环作为最后的手段,因为大多数这些操作都可以由MATLAB优化的矩阵例程执行。
  3. MATLAB的xor返回逻辑xor,因此当它看到两个值(或值的矩阵)时,无论是234 xor 123还是12 xor 23都无关紧要因为它相当于1 xor 11 xor 1您正在寻找 bitxor,它在矩阵的每个元素上执行按位xor,我在下面的代码中使用了它。这是您使用pixel == xor(xor(pixel,key),key)操作检索信息的唯一方法(假设您想要这样做)。

  4. rand返回0 - 1的实际值;因此,要成功按位xor,您需要0 - 255中的数字。因此,在我的代码中,您会看到mask具有来自0-255的随机值。

  5. 注意:我使用过peppers.png因为它在MATLAB中可用。将其替换为lena_color.tif

    %%# Load and convert the image to gray
    img = imread('peppers.png');
    img_new = rgb2gray(img);
    
    %%# Get the mask matrix
    mask = uint8(rand(size(img_new))*256);
    
    %%# Get the send and receive matrix
    send   = bitxor(img_new,mask);
    receive = bitxor(send,mask);
    
    %%# Check and display
    figure;imshow(send,[0 255]);
    figure;imshow(receive,[0 255]);
    

    更新

    %%# Get mask and img somehow (imread, etc.)
    img = double(img);
    mask_rgb = double(repmat(mask,[1 1 3]));
    bitxor(img,mask);
    

    如果相反,您选择将所有内容uint8而不是双倍,那么我建议您检查是否在任何地方丢失数据。 imguint8,因此没有任何损失,但如果mask的任何值大于255,则将其double设为{{1}}将导致损失在数据中。