%yeohyong
%2018.04.02
%龙格库塔加密和恢复
clc;
clear all; %清除所有变量
data = imread('yang2.jpg'); %读取图像,从默认路径读取图像到data,原图是彩色图像
[m,n,r] = size(data); %获取data图像矩阵的尺寸,
if r ~= 1 %当r>1时是彩色图像,r=1是灰度图像
data1 = rgb2gray(data); %彩色图像转成灰度图像
else
data1 = data; %data是灰度图像直接赋值給data1矩阵
end
figure(1); %图1
imshow(data1); %显示灰度图像data1
title('灰度图像');
%*********************龙格库塔算法******************************
%函数句柄定义
f1 = @(x, y, z, t)(10*(y-x));
f2 = @(x, y, z, t)(28 * x - x* z+ y);
f3 = @(x, y, z, t)(x* y - 8 /3 *z);
%定义4个1行100000列的矩阵,元素全部是0
x = zeros(1, 1000); %事先知道m和n相等,则需要保存n*n个像素点
y = zeros(1, 1000);
z = zeros(1, 1000);
t = zeros(1, 1000);
%初始值
h = 0.0005; %步长
t(1) = 0.001;
x(1) = 0.01;
y(1) = 0.02;
z(1) = 0.05;
for i = 2 : 1000 %共n*n+1-2+1=n*n个点
k11 = f1(x(i - 1), y(i - 1), z(i - 1), t(i-1));
k21 = f2(x(i - 1), y(i - 1), z(i - 1), t(i-1));
k31 = f3(x(i - 1), y(i - 1), z(i - 1), t(i-1));
k12 = f1(x(i - 1) + 0.5 * h * k11, y(i - 1) + 0.5 * h * k21, z(i - 1) + 0.5 * h * k31,t(i-1)+0.5*h);
k22 = f2(x(i - 1) + 0.5 * h * k11, y(i - 1) + 0.5 * h * k21, z(i - 1) + 0.5 * h * k31,t(i-1)+0.5*h);
k32 = f3(x(i - 1) + 0.5 * h * k11, y(i - 1) + 0.5 * h * k21, z(i - 1) + 0.5 * h * k31,t(i-1)+0.5*h);
k13 = f1(x(i - 1) + 0.5 * h * k12, y(i - 1) + 0.5 * h * k22, z(i - 1) + 0.5 * h * k32,t(i-1)+0.5*h);
k23 = f2(x(i - 1) + 0.5 * h * k12, y(i - 1) + 0.5 * h * k22, z(i - 1) + 0.5 * h * k32,t(i-1)+0.5*h);
k33 = f3(x(i - 1) + 0.5 * h * k12, y(i - 1) + 0.5 * h * k22, z(i - 1) + 0.5 * h * k32,t(i-1)+0.5*h);
k14 = f1(x(i - 1) + 0.5 * h * k13, y(i - 1) + 0.5 * h * k23, z(i - 1) + 0.5 * h * k33,t(i-1)+0.5*h);
k24 = f2(x(i - 1) + 0.5 * h * k13, y(i - 1) + 0.5 * h * k23, z(i - 1) + 0.5 * h * k33,t(i-1)+0.5*h);
k34 = f3(x(i - 1) + 0.5 * h * k13, y(i - 1) + 0.5 * h * k23, z(i - 1) + 0.5 * h * k33,t(i-1)+0.5*h);
t(i) = t(i - 1) + h;
x(i) = x(i - 1) + h*(1/6*k11 +1/3*k12+1/3*k13+1/6*k14);
y(i) = y(i - 1) + h*(1/6*k21 +1/3*k22+1/3*k23+1/6*k24);
z(i) = z(i - 1) + h*(1/6*k31 +1/3*k32+1/3*k33+1/6*k34);
end
%从上面算法中得到z(i),i=2、3、4.......1000,由已知得到z(1) = 0.05,所以i 取到1~1000
%计算z(n)的模
% a = z.*z;
% b = sum(a);
% c = sqrt(b);
for i = 1 : n
for j = 1 : n
temp = data1(i, j); % 提去(i, j)处的像素值,相当于取出矩阵data1中的元素
% temp1 = floor(double(temp)^0.5); %floor()取下整数
%temp1 = mod(floor(double(temp) ^ 2 * rand(1)), 256); % rand(1)随机加密
%key = mod(floor(256 ^ 3 * rand(1)), 256);
%key = mod(floor(c * (256 ^ 3)) , 256);
key = mod(floor(sqrt(sum(z.*z)) * (256 ^ 3)) , 256);
temp1 = bitxor(temp, key);% key必须是整数
data1(i, j) = temp1;
temp = bitxor(temp1, key);
data2(i, j) = temp;
end
end
% end
figure(2);
imshow(uint8(data1));
title('R-K加密');
imwrite(data2,'D:\Databank_Yeoh\Matlab_databank\Matlab_Path_Yeoh\yangyong3.jpg');
figure(3);
imshow(uint8(data2));
title('R-K加密恢复后的图像');
%imtool(uint8(data3)); %可以显示全图
评论0