这是我用来更改红色值的代码
pic=imread('farooq1.jpg');
[imr,imc,clr]=size(pic);
for row=1:imr
for col=1:imc
for k=1:clr
if(k==1)
img2(row,col,k)=bitxor(pic(row,col,k),66);
else
img2(row,col,k)=pic(row,col,k);
end
end
end
end
imwrite(img2,'farooq_scr.jpg');
imshow(img2);
但是当我在生成的文件上再次使用相同的代码撤消XORing时,结果与原始图片不匹配。
如果您知道更好的方法,请建议我。
答案 0 :(得分:2)
您无法恢复原始图像的原因与处理红色平面的代码无关,该代码可正常工作,但可以使用the vectorized code suggested by Jonas更有效,更简洁地完成:
img2 = pic;
img2(:,:,1) = bitxor(img2(:,:,1),66);
您遇到的问题实际上是您保存图片文件的格式的结果。默认情况下,使用JPEG image files保存的IMWRITE使用lossy compression进行保存以减少文件大小。这会导致图像信息丢失,导致在加载图像并重新应用处理时无法恢复原始图像。
您可以通过指定在保存JPEG图像时使用lossless compression来解决您的问题,如下所示:
imwrite(img2,'farooq_scr.jpg','Mode','lossless');
示例:强>
以下是使用图像处理工具箱附带的JPEG图像'greens.jpg'
的示例:
rawImg = imread('greens.jpg'); %# Load the original image
subplot(2,2,1);
imshow(rawImg); %# Display the original image
title('Original Image');
modImg = rawImg; %# Initialize a modified image
modImg(:,:,1) = bitxor(modImg(:,:,1),66); %# Modify the red plane of the image
subplot(2,2,2);
imshow(modImg); %# Display the modified image
title('Modified Image');
imwrite(modImg,'lossy_image.jpg'); %# Save with lossy compression
lossyImg = imread('lossy_image.jpg'); %# Reload the image
lossyImg(:,:,1) = bitxor(lossyImg(:,:,1),66); %# Reprocess the image
subplot(2,2,3);
imshow(lossyImg); %# Display the image
title({'Using Lossy Image' 'to Recover Original'});
imwrite(modImg,'lossless_image.jpg',... %# Save with lossless compression
'Mode','lossless');
losslessImg = imread('lossless_image.jpg'); %# Reload the image
losslessImg(:,:,1) = bitxor(losslessImg(:,:,1),66); %# Reprocess the image
subplot(2,2,4);
imshow(losslessImg); %# Display the image
title({'Using Lossless Image' 'to Recover Original'});
这是最终的图像集:
您可以看到,使用无损压缩保存图像可让您在重新应用处理步骤时恢复原始图像。您可以使用函数ISEQUAL确认您使用原始图像取回完全相同的图像:
>> isequal(rawImg,lossyImg) %# Lossy image doesn't match; returns false
ans =
0
>> isequal(rawImg,losslessImg) %# Lossless image matches exactly; returns true
ans =
1
答案 1 :(得分:0)
您必须确保新图像与旧图像属于同一类。此外,你可以摆脱一些循环
pic = imread('peppers.png');
%# initialize img2 to the same size and same class as pic
%# by making it a copy of pic
img2 = pic;
%# apply bitxor to the red channel
img2(:,:,1) = bitxor(pic(:,:,1),66);
%# write the data
imwrite(img2,'peppers_scr.png')
imshow(img2)
%# show that the reverse works
img3 = imread('peppers_scr.png');
img3(:,:,1) = bitxor(img3(:,:,1),66);
figure %# create new figure
imshow(img3)