作者maokejackson (百年难得发表文章)
看板PCCU-CS
标题[作业] 影像处理作业2
时间Thu May 17 13:13:58 2007
题目:实作bitmap的读取
本程式仅供参考,如欲使用请自便 XD
=================================================================
function [I M] = bmpread(filename)
% open file
fid = fopen(filename, 'r');
if fid == -1
error('File "%s" does not exist.', filename);
end
% reading header
Signature = fread(fid, 2, 'uchar');
if Signature(1) ~= 66 || Signature(2) ~= 77
fclose(fid);
error('Not a bitmap file.');
end
% continue reading header
FileSize = fread(fid, 1, 'uint32');
Reserved = fread(fid, 1, 'uint32');
DataOffset = fread(fid, 1, 'uint32');
Size = fread(fid, 1, 'uint32');
Width = fread(fid, 1, 'uint32');
Height = fread(fid, 1, 'uint32');
Planes = fread(fid, 1, 'uint16');
BitCount = fread(fid, 1, 'uint16');
Compression = fread(fid, 1, 'uint32');
ImageSize = fread(fid, 1, 'uint32');
HorizontalRes = fread(fid, 1, 'uint32');
VerticalRes = fread(fid, 1, 'uint32');
ColorsUsed = fread(fid, 1, 'uint32');
ImportantColors = fread(fid, 1, 'uint32');
% reading color map
if DataOffset > 54
tmp = fread(fid, DataOffset-54, 'uint8');
tmp = reshape(tmp, 4, 2^BitCount)';
tmp(:,4) = [];
ColorMap = fliplr(tmp) / 255;
else
ColorMap = [];
end
% reading bitmap data
if Compression == 0
if BitCount == 1 || BitCount == 4 || BitCount == 8
cmd = sprintf('fread(fid, (FileSize-DataOffset)*8/BitCount,
''ubit%d=>uint8'')', BitCount);
tmp = eval(cmd);
tmp = reshape(flipud(reshape(tmp, 8/BitCount, [])), Width, Height);
Image = rot90(tmp);
elseif BitCount == 16
Image = uint8(zeros(Height, Width, 3));
tmp = fread(fid, (FileSize-DataOffset)/2, 'uint16=>uint16');
tmp = reshape([bitshift(tmp,-10) mod(bitshift(tmp,-5),2^5)
mod(tmp,2^5)]', 3, Width, Height);
tmp = 255 * tmp / (2^5-1); % normalise
tmp = shiftdim(tmp,1); % shift rgb to 3rd dimension
Image(:,:,1) = rot90(tmp(:,:,1));
Image(:,:,2) = rot90(tmp(:,:,2));
Image(:,:,3) = rot90(tmp(:,:,3));
elseif BitCount == 24
Image = uint8(zeros(Height, Width, 3));
tmp = fread(fid, FileSize-DataOffset, 'uint8=>uint8');
tmp = reshape(tmp, 3, Width, Height);
tmp = shiftdim(tmp,1); % shift rgb to 3rd dimension
Image(:,:,1) = rot90(tmp(:,:,3));
Image(:,:,2) = rot90(tmp(:,:,2));
Image(:,:,3) = rot90(tmp(:,:,1));
else
fclose(fid);
error('File type does not support.');
end
else
fclose(fid);
error('Compressed bitmap does not support.');
end
fclose(fid);
if nargout == 0
imshow(Image, ColorMap);
else
I = Image;
M = ColorMap;
end
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 220.133.89.82
1F:嘘 lingpxs:嘘你 贴太慢了 过期很久了啦 长老~~~~ 05/17 15:39
2F:推 lingpxs:不过念在你有心~ 推回来 05/17 15:50
3F:→ maokejackson:= =" 05/17 16:07
4F:推 hairless:吼~华冈青年不要乱嘘人~原来这是圣杰哥喔?? 05/17 20:36