file='peppers.png';
Img=imread(file);%% 波段分离
[m,n,p]=size(Img);
red=Img(:,:,1);
green=Img(:,:,2);
blue=Img(:,:,3);%% 按行或列合并矩阵
BIL=[];BIP=[];for i=1:m
BIL=[BIL;red(i,:);green(i,:);blue(i,:)];
end
for i=1:n
BIP=[BIP,red(:,i),green(:,i),blue(:,i)];
end
%% 按图片格式保存
imwrite(BIL,'BIL.jpg');imwrite(BIP,'BIP.jpg');%% 按二进制保存
filename1 ='peppers_bil.data';
fid =fopen(filename1,'wb');fwrite(fid,BIL,class(BIL));fclose(fid);
filename2 ='peppers_bip.data';
fid =fopen(filename2,'wb');fwrite(fid,BIP,class(BIP));fclose(fid);% 显示结果
figure(1)imshow(BIL);title('BIL');figure(2)imshow(BIP);title('BIP');
程序二 读取BIL和BIP格式的图像
disp('start........')
m =384;
n =512;
p =3;%% 读取并显示BIL文件
% read binary data
filename ='peppers_bil.data';
fid =fopen(filename,'rb');if fid<0error('can not open file');
end
bil =fread(fid,[m*p,n],'uint8=>uint8');fclose(fid);%分割(分割步骤不影响后面的合并操作)
Img2=zeros(m,n,p,'uint8');
red=bil(1:p:p*m,:);
green=bil(2:p:p*m,:);
blue=bil(3:p:p*m,:);%合并
for i=0:m-1for j=1:n
Img2(i+1,j,:)=[bil(p*i+1,j),bil(p*i+2,j),bil(p*i+3,j)];
end
end
%显示结果
figure(1)% define figure
subplot(2,2,1);%subplot(x,y,n)x表示显示的行数,y表示列数,n表示第几幅图片
imshow(red);title('red');subplot(2,2,2);imshow(green);title('green');subplot(2,2,3);imshow(blue);title('blue');subplot(2,2,4);imshow(Img2);title('bil to color');%% 读取并显示BIP文件
filename ='peppers_bip.data';
fid =fopen(filename,'rb');if fid<0error('can not open file');
end
bip =fread(fid,[m,n*p],'uint8=>uint8');fclose(fid);%分割
red=bip(:,1:3:n*p);
green=bip(:,2:3:n*p);
blue=bip(:,3:3:n*p);%合并
Img3=zeros(m,n,p,'uint8');for i=0:n-1Img3(:,i+1,:)=[bip(:,i+1),bip(:,i+2),bip(:,i+3)];
end
figure(2)% define figure
subplot(2,2,1);%subplot(x,y,n)x表示显示的行数,y表示列数,n表示第几幅图片
imshow(red);title('red');subplot(2,2,2);imshow(green);title('green');subplot(2,2,3);imshow(blue);title('blue');subplot(2,2,4);imshow(Img2);title('bip to color');