我的代码读取一个RGB图像,处理后产生浮点数结果。如何在Matlab 7.6.0 (R2008a)中编写这些值作为图像,保持这些浮点数值?
我的代码读取一个RGB图像,处理后产生浮点数结果。如何在Matlab 7.6.0 (R2008a)中编写这些值作为图像,保持这些浮点数值?
实际上,可以将64位像素数据(即表示双精度浮点值所需的位数)装入特定的图像格式中,具体来说是PNG。而且你甚至可以完全恢复数据。关键是将所有内容编码为uint16
值,并使用真彩RGB图像(3个16位数据的颜色平面)以及一个alpha透明度映射(另外16位)。以下是编码步骤:
data = rand(4); % Just some sample data, a small 4-by-4 matrix
hexData = num2hex(data(:)); % Get the 16 digit hex codes for each pixel
C = mat2cell(hexData, numel(data), [4 4 4 4]); % Split the hex codes into 4 groups of 4
C = cellfun(@(c) {uint16(hex2dec(c))}, C); % Convert each hex value into a 16 bit integer
colorData = reshape([C{1:3}], [size(data) 3]); % 4-by-4-by-3 uint16 color data
alphaData = reshape(C{4}, size(data)); % 4-by-4 uint16 alpha data
imwrite(colorData, 'double_data.png', 'Alpha', alphaData); % Save image
[imColor, ~, imAlpha] = imread('double_data.png'); % Load image
imSize = size(imColor); % Get image size
imHex = [dec2hex(imColor(:, :, 1)) ... % Convert each uint16 to hex and concatenate
dec2hex(imColor(:, :, 2)) ...
dec2hex(imColor(:, :, 3)) ...
dec2hex(imAlpha)];
imdata = reshape(hex2num(imHex), imSize(1:2)); % Reproduce data
并进行相等性检查:
>> isequal(imdata, data)
ans =
logical
1 % it's the same!
以下函数将单精度灰度或RGB图像写入tif文件。而且你会发现这些天,如果像素值在(0,1)的范围内,Windows资源管理器可以很好地处理单精度图像。当你读取它时,可以像往常一样使用imread
。
function writeftif(outim,outfilename)
t = Tiff(outfilename,'w');
if size(outim,3)==3
t.setTag('Photometric',Tiff.Photometric.RGB);
elseif size(outim,3)==1
t.setTag('Photometric',Tiff.Photometric.MinIsBlack);
end
t.setTag('Compression',Tiff.Compression.None);
t.setTag('BitsPerSample',32);
t.setTag('SamplesPerPixel',size(outim,3));
t.setTag('SampleFormat',Tiff.SampleFormat.IEEEFP);
t.setTag('ImageLength',size(outim,1));
t.setTag('ImageWidth',size(outim,2));
t.setTag('PlanarConfiguration',Tiff.PlanarConfiguration.Chunky);
% Write the data to the Tiff object.
t.write(single(outim));
t.close();
可以使用TIFF图像格式编写具有浮点值的图像。以下是一个示例:
A=single(7.6*rand(10,10))
t = Tiff('test.tif', 'w');
tagstruct.ImageLength = size(A, 1);
tagstruct.ImageWidth = size(A, 2);
tagstruct.Compression = Tiff.Compression.None;
tagstruct.SampleFormat = Tiff.SampleFormat.IEEEFP;
tagstruct.Photometric = Tiff.Photometric.MinIsBlack;
tagstruct.BitsPerSample = 32;
tagstruct.SamplesPerPixel = 1;
tagstruct.PlanarConfiguration = Tiff.PlanarConfiguration.Chunky;
t.setTag(tagstruct);
t.write(A);
t.close();
B=imread('test.tif')
%// Assume an image called 'im' of type double.
%// First normalize to fall into [0,1].
im = im - min(im(:)); %// Save these numbers somewhere
im = im / max(im(:)); %// if you need to recover the original values later!
%// Best PNG quality.
imwrite(im,'image.png','bitdepth',16);
如果您需要更高的精度,您必须将图像保存为通用数据格式而不是专用图像格式。
当您保存图像时,查看器需要知道值的完整可能范围。通常的约定是,如果值为浮点数,则范围为[0..1],如果值为uint8,则范围为[0..255]等。
当您保存具有浮点值(如2.34)的图像时,您应该问自己,查看器将如何知道如何解释它?
我的答案是:您无法。您应该将您的值转换为有效范围,然后再保存它。例如,如果您的浮点范围为[0..10],则可以将所有值乘以1000并保存为uint16。这样,您就可以(几乎)保留浮点值的精度。