clear
M=256;
N=256;
a=1;
p=0.3;
A=imread('girl2.tif');
RA=A(:,:,1);
GA=A(:,:,2);
BA=A(:,:,3);
B=imread('bz.tif');
B=rgb2gray(B);
B=double(B);
RA=double(RA);
GA=double(GA);
BA=double(BA);
for i=1:M/8
for j=1:N/8
RC=RA(((i-1)*8+1):(i*8),((j-1)*8+1):(j*8));
GC=GA(((i-1)*8+1):(i*8),((j-1)*8+1):(j*8));
BC=BA(((i-1)*8+1):(i*8),((j-1)*8+1):(j*8));
D=B(((i-1)*4+1):(i*4),((j-1)*4+1):(j*4));
RE=dct2(RC);GE=dct2(GC);BE=dct2(BC);
D=D-128;
D1=fix(D/16)-4;
D2=fix((D-fix(D/16)*16)/4)-2;
D3=D-(D1+4)*16-(D2+2)*4-2;
for k=1:8
RE(9-k,k)=RE(9-k,k)*(1+p*D1(k));GE(9-k,k)=GE(9-k,k)*(1+p*D2(k));BE(9-k,k)=BE(9-k,k)*(1+p*D3(k));
end
for q=1:7
RE(8-q,q)=RE(8-q,q)*(1+p*D1(q+8));GE(8-q,q)=GE(8-q,q)*(1+p*D2(q+8));BE(8-q,q)=BE(8-q,q)*(1+p*D3(q+8));
end
RE(5,5)=RE(5,5)*(1+p*D1(16));GE(5,5)=GE(5,5)*(1+p*D2(16));BE(5,5)=BE(5,5)*(1+p*D3(16));
RF=RE;GF=GE;BF=BE;
RG=idct2(RF);GG=idct2(GF);BG=idct2(BF);
Rx(((i-1)*8+1):(i*8),((j-1)*8+1):(j*8))=RG(1:8,1:8);
Gx(((i-1)*8+1):(i*8),((j-1)*8+1):(j*8))=GG(1:8,1:8);
Bx(((i-1)*8+1):(i*8),((j-1)*8+1):(j*8))=BG(1:8,1:8);
end
end
RX=uint8(Rx);GX=uint8(Gx);BX=uint8(Bx);
X=cat(3,RX,GX,BX);
imwrite(X,'JG.tif','tif');
% 以上为水印的嵌入
% 以下是水印的提取
Y=imread('JG.tif');
RY=Y(:,:,1);
GY=Y(:,:,2);
BY=Y(:,:,3);
I=imread('girl2.tif');
RI=I(:,:,1);
GI=I(:,:,2);
BI=I(:,:,3);
RY=double(RY);GY=double(GY);BY=double(BY);
RI=double(RI);GI=double(GI);BI=double(BI);
for i=1:M/8
for j=1:N/8
RJ=RI(((i-1)*8+1):(i*8),((j-1)*8+1):(j*8));GJ=GI(((i-1)*8+1):(i*8),((j-1)*8+1):(j*8));BJ=BI(((i-1)*8+1):(i*8),((j-1)*8+1):(j*8));
RH=dct2(RJ);GH=dct2(GJ);BH=dct2(BJ);
Ry=RY(((i-1)*8+1):(i*8),((j-1)*8+1):(j*8));Gy=GY(((i-1)*8+1):(i*8),((j-1)*8+1):(j*8));By=BY(((i-1)*8+1):(i*8),((j-1)*8+1):(j*8));
Ry=dct2(Ry);Gy=dct2(Gy);By=dct2(By);
for k=1:8
Rz(k)=(Ry(9-k,k)/RH(9-k,k)-1)/p;Gz(k)=(Gy(9-k,k)/GH(9-k,k)-1)/p;Bz(k)=(By(9-k,k)/BH(9-k,k)-1)/p;
end
for q=1:7
Rz(q+8)=(Ry(8-q,q)/RH(8-q,q)-1)/p;Gz(q+8)=(Gy(8-q,q)/GH(8-q,q)-1)/p;Bz(q+8)=(By(8-q,q)/BH(8-q,q)-1)/p;
end
Rz(16)=(Ry(5,5)/RH(5,5)-1)/p;Gz(16)=(Gy(5,5)/GH(5,5)-1)/p;Bz(16)=(By(5,5)/BH(5,5)-1)/p;
u=(Rz(1:16)+4)*16+(Gz(1:16)+2)*4+Bz(1:16)+2+128;
P=reshape(u,4,4);
Z(((i-1)*4+1):(i*4),((j-1)*4+1):(j*4))=P(1:4,1:4);
end
end
Z=Z(1:M/2,1:N/2);
% MM=B-Z;
% MM=uint8(MM);
Z=uint8(Z);
A=uint8(A);
B=uint8(B);
imwrite(Z,'SYtwo.tif','tif');
subplot(2,2,1); imshow(A); title('原宿主图像');
subplot(2,2,2); imshow(B); title('水印图像');
subplot(2,2,3); imshow(X); title('嵌入水印后的图像');
subplot(2,2,4); imshow(Z); title('提取的水印图像');
% aaa=aaaa
% imshow(MM);
% D=213;
% D=D-128;
% D1=fix(D/16);
% D2=fix((D-fix(D/16)*16)/4);
% D3=D-D1*16-D2*4;
% a=dec2bin(D)
% b=dec2bin(D1)
% c=dec2bin(D2)
% d=dec2bin(D3)