开发者

bitxor operation in MATLAB

开发者 https://www.devze.com 2023-01-03 20:05 出处:网络
I am trying to understand why the original image is not coming with this code. The resulting image receive is yellowish in color, instead of being similar to the image Img_new.

I am trying to understand why the original image is not coming with this code. The resulting image receive is yellowish in color, instead of being similar to the image 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 开发者_StackOverflow社区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);

What am I doing wrong?


There are several problems in your code.

  1. MATLAB is case sensitive so end and End is not the same. Same goes for receive, and send.
  2. MATLAB has a lot of matrix-based operations so please use for loops as a last resort since most of these operations can be executed by MATLAB's optimized routines for matrices.
  3. MATLAB's xor returns the logical xor so when it sees two values (or matrices of values) it doesn't matter if it's 234 xor 123 or 12 xor 23 since it is equivalent to 1 xor 1 and 1 xor 1. You're looking for bitxor which does the bitwise xor on each element of the matrix and I've used it in my code below. This is the only way you can retrieve the information with the pixel == xor(xor(pixel,key),key) operation (assuming that's what you want to do).

  4. rand returns a real value from 0 - 1 ; therefore, to do a successful bitwise xor, you need numbers from 0 - 255. Hence, in my code, you'll see that mask has random values from 0-255.

Note: I've used peppers.png since it's available in MATLAB. Replace it with 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]);

Update:

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

If instead, you choose to make everything uint8 instead of double, then I urge you to check if you are losing data anywhere. img is uint8 so there is no loss, but if any of the values of mask is greater than 255 then making it double will lead to a loss in data.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号