Borrar filtros
Borrar filtros

Convert RAW File (images) to .img

5 visualizaciones (últimos 30 días)
Nalini
Nalini el 26 de En. de 2014
Editada: Image Analyst el 26 de En. de 2014
Hello,
I wish to convert RAW file to .img But I am not sure of how to do this conversion. Can you please help me?
Thanks a lot in advance

Respuestas (2)

Image Analyst
Image Analyst el 26 de En. de 2014
If you don't know the format, you're stuck making guesses. If you guessed the number of rows and columns wrong, the the image may look sheared or look like there's 2 or 3 images shifted and overlaid. If you guessed at the header length wrong, then you will have garbage at the top loef of your image. Do you know the format? Is it just plain pixel values and nothing else? Or is there an actual format to it?
  3 comentarios
Image Analyst
Image Analyst el 26 de En. de 2014
Here's some code to get you started.
% Read_RAW_3DArray
% Reads a RAW file from disk into a 3D array with control over cropping and subsampling.
%
% Usage:
% [data3D, stHeader] = Read_RAW_3DArray(fullFileName, stInputParameters);
%
% Inputs:
% fullFileName - full path and filename of the RAW file.
% stInputParameters - a MATLAB structure that is dynamically created.
% defaults get applied for the missing structure members.
% See example below.
% Output:
% data3D - 3-D array of voxel values, either uint8 or uint16.
%
% Example usage:
% Create a MATLAB structure dynamically to hold the parameters.
% stInputParameters.XStart = 1;
% stInputParameters.XEnd = 1024;
% stInputParameters.YStart = 1;
% stInputParameters.YEnd = 1024;
% stInputParameters.ZStart = 10;
% stInputParameters.ZEnd = 50;
% stInputParameters.Subsample = 4;
% fullFileName_RAW = 'SimulatedData_Distance8Bit.RAW';
% [data3D, stHeader] = Read_RAW_3DArray(fullFileName_RAW, stInputParameters);
%
% Written by Image Analyst, 7-30-2007
%------------------------------------------------------------------------------
function [data3D, stHeader] = Read_RAW_3DArray(fullFileName, stInputParameters)
% Check syntax. Must have two arguments.
if (nargin ~= 2)
error('Usage: [data3D, stHeader] = Read_RAW_3DArray(fullFileName, stInputParameters)');
end
if (ischar(fullFileName) ~= 1)
error('Requires a string filename as an argument.');
end
if ~exist(fullFileName, 'file')
error('Error: file passed in to Read_RAW_3DArray\n%s\ndoes not exist.', fullFileName);
end
% Read in header and get 3D image array dimensions.
stHeader = Read_RAW_Header(fullFileName);
% Extract out sizes to more conveniently-named local variables.
% Note: fread() requires that x_size and y_size be doubles.
x_size = double(stHeader.x_size);
y_size = double(stHeader.y_size);
z_size = double(stHeader.z_size);
% They passed in a structure for stInputParameters. Make sure they passed in valid numbers.
% Assign defaults to any fields in stInputParameters that they didn't set.
% Make sure the starting and ending parameters they passed in (via stInputParameters)
% are in range 1 to x_size, 1 to y_size, and 1 to z_size.
stValidParameters = ValidateInputParameters(stInputParameters, x_size, y_size, z_size);
% Get size of output array. It may be subsampled and be a different size than the input array.
if stValidParameters.Subsample ~= 1
subsampledXSize = ceil(double(stValidParameters.XEnd - stValidParameters.XStart + 1) / double(stInputParameters.Subsample));
subsampledYSize = ceil(double(stValidParameters.YEnd - stValidParameters.YStart + 1) / double(stInputParameters.Subsample));
subsampledZSize = ceil(double(stValidParameters.ZEnd - stValidParameters.ZStart + 1) / double(stInputParameters.Subsample));
else
subsampledXSize = stValidParameters.XEnd - stValidParameters.XStart + 1;
subsampledYSize = stValidParameters.YEnd - stValidParameters.YStart + 1;
subsampledZSize = stValidParameters.ZEnd - stValidParameters.ZStart + 1;
end
% Open the image data file for reading.
fileHandle = fopen(fullFileName, 'rb', stHeader.EndianArg);
if (fileHandle == -1)
error(['Read_RAW_3DArray() reports error opening ', fullFileName, ' for input.']);
end
% Skip past header of stHeader.HeaderSize bytes.
bytesToSkip = int32(stHeader.HeaderSize);
% Now, additionally, skip past (ZStart - 1) slices before the ZStart slice begins
% so that we end up at the beginning byte of the slice that we want, which is ZStart.
bytesToSkip = bytesToSkip + int32(x_size * y_size * stHeader.BytesPerVoxel * (stValidParameters.ZStart - 1));
fseek(fileHandle, bytesToSkip, 'bof');
if(stHeader.BytesPerVoxel == 1)
dataLengthString = '*uint8'; % You need the *, otherwise fread returns doubles.
% Initialize a 3D data array.
data3D = uint8(zeros([subsampledXSize, subsampledYSize, subsampledZSize]));
elseif(stHeader.BytesPerVoxel == 2)
dataLengthString = '*uint16'; % You need the *, otherwise fread returns doubles.
% Initialize a 3D data array.
data3D = uint16(zeros([subsampledXSize, subsampledYSize, subsampledZSize]));
else
error('Unsupported BytesPerVoxel %d', stHeader.BytesPerVoxel);
end
bytesPerVoxel = stHeader.BytesPerVoxel;
% We'll always first read in the full slice.
% Now determine if we need to subsample or crop that full slice.
if subsampledXSize ~= x_size || subsampledYSize ~= y_size || subsampledZSize ~= z_size
needToCropOrSubsample = 1;
else
needToCropOrSubsample = 0;
end
% Read in data slice by slice to avoid out of memory error.
% We'll build up the 3D array slice by slice along the Z direction.
sliceNumber = 1;
for z = stValidParameters.ZStart : stValidParameters.Subsample : stValidParameters.ZEnd
% Read in slice z from input image and put into slice sliceNumber of output image.
% Reads from the current file pointer position.
% Note: fread requires that x_size and y_size be doubles.
oneFullSlice = fread(fileHandle, [x_size, y_size], dataLengthString);
if needToCropOrSubsample == 1
% Crop it and subsample it.
croppedSlice = oneFullSlice(stValidParameters.XStart:stValidParameters.Subsample:stValidParameters.XEnd, stValidParameters.YStart:stValidParameters.Subsample:stValidParameters.YEnd);
% Assign it, but don't transpose it like in some other formats.
data3D(:, :, sliceNumber) = croppedSlice;
else
% Take the full slice, (not transposed like in some other formats).
data3D(:, :, sliceNumber) = oneFullSlice;
end
%disp(['Read in slice ' num2str(z) ' of input, slice ' num2str(sliceNumber) ' of output']);
% Skip the next slices if we are subsampling.
% For example, if we just read slice 1 and the subsampling is 3, the next slice we should
% read is 4, so we need to skip slices 2 and 3 (skip subsampling-1 slices).
if stValidParameters.Subsample > 1
% Calculate how many bytes to skip.
bytesToSkip = int32(x_size * y_size * bytesPerVoxel * (stValidParameters.Subsample - 1));
% Skip that many past the current position, which is at the end of the slice we just read.
fseek(fileHandle, bytesToSkip, 'cof');
end
% Increment the slice we are on in the output array.
sliceNumber = sliceNumber + 1;
end
% Close the file.
fclose(fileHandle);
Image Analyst
Image Analyst el 26 de En. de 2014
Editada: Image Analyst el 26 de En. de 2014
Here's another function that reads a header. The code is well commented so study it first. Don't just immediately say "I don't understand it can you explain it to me." If it doesn't work for you right out of the box (which it won't ) then you need to look at how the header is constructed and adapt it to work with whatever format header you have.
% Read_RAW_Header
% Returns the image header information and some extra information
% for our raw image file.
% Usage: stHeader = Read_RAW_Header(filename)
% Input
% filename - RAW format file name
% Output
% stHeader - header structure containing information on the data
% Header is 44 bytes.
% The header of an RAW file will look something like this:
% stHeader.TotalVoxels: Array size - total size of the array (not the whole file) - number of voxels.
% stHeader.NumberOfDimensions: Number of dimensions - 3 for a 3D image.
% stHeader.x_size: Size (number of voxels) in the X direction.
% stHeader.y_size: Size (number of voxels) in the Y direction.
% stHeader.z_size: Size (number of voxels) in the Z direction.
% stHeader.XStart: Position of the center of the first pixel in the X direction - it's 0.
% stHeader.YStart: Position of the center of the first pixel in the Y direction - it's 0.
% stHeader.ZStart: Position of the center of the first pixel in the Z direction - it's 0.
% stHeader.XEnd: Position of the center of the last pixel in the X direction - it's voxelWidth * (sizeX - 1).
% stHeader.Yend: Position of the center of the last pixel in the Y direction - it's voxelWidth * (sizeY - 1).
% stHeader.ZEnd: Position of the center of the last pixel in the Z direction - it's voxelWidth * (sizeZ - 1).
% Following the header in the data file, are the voxel values, but of course we do not return these in the header.
%
% I also add these fields to the returned header argument:
% stHeader.HeaderSize = 44;
% stHeader.BytesPerVoxel
% stHeader.FileSizeInBytes
% stHeader.DataSizeInBytes
% stHeader.Endian
% stHeader.EndianArg
%
% Example usage:
% fullFileName_RAW = fullfile(cd, 'SimulatedData_Distance.RAW')
% stHeader = Read_RAW_Header(fullFileName_RAW)
%
% Revised by Image Analyst, 7/25/2007
%------------------------------------------------------------------------------
function stHeader = Read_RAW_Header(fullFilename)
% Check syntax. Must have at least one input argument, the full filename.
if (nargin ~= 1)
error('Usage: stHeader = Read_RAW_Header(fullFilename)');
end
if (ischar(fullFilename)~=1)
error('Requires a string filename as an argument.');
end
% These aren't in the header specification for this type of file,
% but other formats use it and it's a useful thing to add to the header.
stHeader.Endian = 'Big';
stHeader.EndianArg = 'ieee-be';
% Open the file for reading.
fileHandleID = fopen(fullFilename, 'rb', stHeader.EndianArg);
if (fileHandleID == -1)
error(['Error opening ', fullFilename, ' for input.']);
end
% Go to the beginning of the file.
% Shouldn't be necessary, but can't hurt.
fseek(fileHandleID, 0, 'bof');
% Read the total number of voxels in the image.
% Read bytes 1-4.
stHeader.TotalVoxels = fread(fileHandleID, 1, '*int32');
% Note: this may be unreliable, and can be zero!
% Better to take the x, y, and z sizes and multiply them together.
% The next 4 bytes are the number of dimensions - 2 or 3.
% Read bytes 5-8.
stHeader.NumberOfDimensions = fread(fileHandleID, 1, 'int32');
% Read in the dimensions for the different directions.
% They'll be in bytes 9-20.
stHeader.x_size = fread(fileHandleID, 1, '*int32');
stHeader.y_size = fread(fileHandleID, 1, '*int32');
stHeader.z_size = fread(fileHandleID, 1, '*int32');
stHeader.TotalVoxels = stHeader.x_size * stHeader.y_size * stHeader.z_size;
% Read in the position of the center of the first pixel.
% They'll be in bytes 21-32.
stHeader.XStart = fread(fileHandleID, 1, '*float');
stHeader.YStart = fread(fileHandleID, 1, '*float');
stHeader.ZStart = fread(fileHandleID, 1, '*float');
% Read in the position of the center of the last pixel.
% They'll be in bytes 33-44.
stHeader.XFieldOfView = fread(fileHandleID, 1, '*float');
stHeader.YFieldOfView = fread(fileHandleID, 1, '*float');
stHeader.ZFieldOfView = fread(fileHandleID, 1, '*float');
% Note: the fields of view are based on (pixel center) - to - (pixel center).
% Calculate the voxel width.
stHeader.VoxelWidth = stHeader.XFieldOfView / single(stHeader.x_size - 1);
% Assign some other useful information.
% It's not in the header but may come in useful anyway.
% Assign the bytes per voxel.
%fileInfo = imfinfo(fullFilename); % Note: doesn't work!
% fileSizeInBytes = fileInfo.FileSize;
% This works:
fileInfo = dir(fullFilename);
% MATLAB returns the information in a structure with fields:
% name
% date
% bytes
% isdir
% datenum
stHeader.HeaderSize = 44;
fileSizeInBytes = fileInfo.bytes;
dataSizeInBytes = double(fileSizeInBytes) - double(stHeader.HeaderSize);
stHeader.BytesPerVoxel = int32(round(dataSizeInBytes / double(stHeader.TotalVoxels)));
stHeader.FileSizeInBytes = fileSizeInBytes;
stHeader.DataSizeInBytes = dataSizeInBytes;
% Close the file.
fclose(fileHandleID); % Close the file.
%=========================================================================
% Make sure the parameters they passed in are in range of 1 to the max dimension in the direction.
% The fields of structure stInputParameters that are checked are:
% XStart, XEnd, YStart, YEnd, ZStart, ZEnd, Subsampling.
% Returns valid parameters in return structure stValidParameters
% The input structure stInputParameters is not changed.
% Image Analyst, 7-17-2007
%------------------------------------------------------------------------------
function stValidParameters = ValidateInputParameters(stInputParameters, x_size, y_size, z_size)
% They passed in a structure. Extract out what values we can.
% Get the starting and stopping columns (X direction).
if isfield(stInputParameters, 'XStart')
% They initialized stInputParameters with a field called "XStart"
% Take the value they passed in, but limit it to the proper range.
% If XStart is outside the range of 1 to x_size (no matter whether above or below), set it equal to 1.
stValidParameters.XStart = LimitToRange(stInputParameters.XStart, 1, x_size, 'XStart', 'min');
else
stValidParameters.XStart = 1; % Assign the default value because they didn't set this field.
end
if isfield(stInputParameters, 'XEnd')
% They initialized stInputParameters with a field called "XEnd"
% Take the value they passed in, but limit it to the proper range.
% If XStart is outside the range of 1 to x_size (no matter whether above or below), set it equal to x_size.
stValidParameters.XEnd = LimitToRange(stInputParameters.XEnd, 1, x_size, 'XEnd', 'max');
else
stValidParameters.XEnd = x_size; % Assign the default value because they didn't set this field.
end
% Get the starting and stopping rows (Y direction).
if isfield(stInputParameters, 'YStart')
% They initialized stInputParameters with a field called "YStart"
% Take the value they passed in, but limit it to the proper range.
% If YStart is outside the range of 1 to y_size (no matter whether above or below), set it equal to 1.
stValidParameters.YStart = LimitToRange(stInputParameters.YStart, 1, y_size, 'YStart', 'min');
else
stValidParameters.YStart = 1; % Assign the default value because they didn't set this field.
end
if isfield(stInputParameters, 'YEnd')
% They initialized stInputParameters with a field called "YEnd"
% Take the value they passed in, but limit it to the proper range.
% If YStart is outside the range of 1 to y_size (no matter whether above or below), set it equal to y_size.
stValidParameters.YEnd = LimitToRange(stInputParameters.YEnd, 1, y_size, 'YEnd', 'max');
else
stValidParameters.YEnd = y_size; % Assign the default value because they didn't set this field.
end
% Get the starting and stopping slice numbers (Z direction).
if isfield(stInputParameters, 'ZStart')
% They initialized stInputParameters with a field called "ZStart"
% Take the value they passed in, but limit it to the proper range.
% If ZStart is outside the range of 1 to z_size (no matter whether above or below), set it equal to 1.
stValidParameters.ZStart = int32(LimitToRange(stInputParameters.ZStart, 1, z_size, 'ZStart', 'min'));
else
stValidParameters.ZStart = int32(1); % Assign the default value because they didn't set this field.
end
if isfield(stInputParameters, 'ZEnd')
% They initialized stInputParameters with a field called "ZEnd"
% Take the value they passed in, but limit it to the proper range.
% If ZEnd is outside the range of 1 to z_size (no matter whether above or below), set it equal to z_size.
stValidParameters.ZEnd = LimitToRange(stInputParameters.ZEnd, 1, z_size, 'ZEnd', 'max');
else
stValidParameters.ZEnd = z_size; % Assign the default value because they didn't set this field.
end
% Make sure the start values are always less than or equal to the end values.
stValidParameters = SortValues(stValidParameters);
% Get the Subsampling.
smallestDimension = min([x_size y_size z_size]); % min must be all lower case.
if isfield(stInputParameters, 'Subsample')
% Take the value they passed in, but limit it to the proper range.
if smallestDimension == 1
% Just a flat image, not a 3D image.
stValidParameters.Subsample = LimitToRange(stInputParameters.Subsample, 1, 1, 'Subsample', 'clip');
else
% A 3D image.
stValidParameters.Subsample = LimitToRange(stInputParameters.Subsample, 1, smallestDimension - 1, 'Subsample', 'clip');
end
else
stValidParameters.Subsample = 1; % Assign the default value because they didn't set this field.
end
return; % ValidateInputParameters
%=========================================================================
% Make sure that inputValue is in range [lowestAllowableValue, highestAllowableValue] (inclusive).
% Returns outputValue that is guaranteed to be in that range.
% If it's outside the range, no matter whether it is high or low, it will be reset according to the "action" argument:
% action = 'min' outputValue well be set equal to lowestAllowableValue
% action = 'max' outputValue well be set equal to highestAllowableValue
% action = 'clip' outputValue well be set equal to lowestAllowableValue if below the range
% and outputValue well be set equal to highestAllowableValue if above the range.
% inputValue is not changed.
% Tell them if it was out of range but do not throw an error (which would stop the program) -
% just correct it according to the "action" argument.
% Image Analyst, 7-17-2007
function outputValue = LimitToRange(inputValue, lowestAllowableValue, highestAllowableValue, name, action)
% For starters, assume it's OK.
outputValue = inputValue;
if outputValue < lowestAllowableValue
% Decide if they want to limit the value or set to a specific value.
if strcmpi(action, 'min')
newValue = lowestAllowableValue;
elseif strcmpi(action, 'max')
newValue = highestAllowableValue;
else % 'clip' to the nearest value.
newValue = lowestAllowableValue;
end
% Tell them in the command window that it was outside the allowable range.
% message = sprintf('%s has a value of %f which is below the minimum allowable value of %f.\nIt will be set to %f.', name, inputValue, lowestAllowableValue, newValue);
% disp(message);
% Clip it to the minimum allowable value.
outputValue = newValue;
end
if outputValue > highestAllowableValue
% Decide if they want to limit the value or set to a specific value.
if strcmpi(action, 'min')
newValue = lowestAllowableValue;
elseif strcmpi(action, 'max')
newValue = highestAllowableValue;
else % 'clip' to the nearest value.
newValue = highestAllowableValue;
end
% Tell them in the command window that it was outside the allowable range.
% message = sprintf('%s has a value of %f which is above the maximum allowable value of %f.\nIt will be set to %f.', name, inputValue, highestAllowableValue, newValue);
% disp(message);
% Clip it to the maximum allowable value.
outputValue = newValue;
end
%====================================================================
% Make sure the start values are always less than the end values.
function stSortedInputParameters = SortValues(stInputParameters)
stSortedInputParameters = stInputParameters;
if stSortedInputParameters.XStart > stSortedInputParameters.XEnd
% They're reversed, so switch them.
stSortedInputParameters.XStart = stInputParameters.XEnd;
stSortedInputParameters.XEnd = stInputParameters.XStart;
end
if stSortedInputParameters.YStart > stSortedInputParameters.YEnd
% They're reversed, so switch them.
stSortedInputParameters.YStart = stInputParameters.YEnd;
stSortedInputParameters.YEnd = stInputParameters.YStart;
end
if stSortedInputParameters.ZStart > stSortedInputParameters.ZEnd
% They're reversed, so switch them.
stSortedInputParameters.ZStart = stInputParameters.ZEnd;
stSortedInputParameters.ZEnd = stInputParameters.ZStart;
end
return;

Iniciar sesión para comentar.


Walter Roberson
Walter Roberson el 26 de En. de 2014
We are not sure how to do the conversion either.
RAW files are not all the same format. They depend upon the manufacturer and model. Most of them are proprietary formats. We cannot be of further assistance without knowing which manufacturer and model produced the file.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by