Added support for recording the RescaleIntecept and RescaleSlope from the dicome files and passing these values onto osgVolume::ImageLayer

This commit is contained in:
Robert Osfield 2009-09-01 10:48:32 +00:00
parent ea43bc7d52
commit 43e3089417
4 changed files with 460 additions and 318 deletions

View File

@ -91,8 +91,8 @@ struct ProcessRow
virtual ~ProcessRow() {}
virtual void operator() (unsigned int num,
GLenum source_pixelFormat, unsigned char* source,
GLenum dest_pixelFormat, unsigned char* dest) const
GLenum source_pixelFormat, unsigned char* source,
GLenum dest_pixelFormat, unsigned char* dest) const
{
switch(source_pixelFormat)
{
@ -100,7 +100,7 @@ struct ProcessRow
case(GL_ALPHA):
switch(dest_pixelFormat)
{
case(GL_LUMINANCE):
case(GL_LUMINANCE):
case(GL_ALPHA): A_to_A(num, source, dest); break;
case(GL_LUMINANCE_ALPHA): A_to_LA(num, source, dest); break;
case(GL_RGB): A_to_RGB(num, source, dest); break;
@ -110,7 +110,7 @@ struct ProcessRow
case(GL_LUMINANCE_ALPHA):
switch(dest_pixelFormat)
{
case(GL_LUMINANCE):
case(GL_LUMINANCE):
case(GL_ALPHA): LA_to_A(num, source, dest); break;
case(GL_LUMINANCE_ALPHA): LA_to_LA(num, source, dest); break;
case(GL_RGB): LA_to_RGB(num, source, dest); break;
@ -120,7 +120,7 @@ struct ProcessRow
case(GL_RGB):
switch(dest_pixelFormat)
{
case(GL_LUMINANCE):
case(GL_LUMINANCE):
case(GL_ALPHA): RGB_to_A(num, source, dest); break;
case(GL_LUMINANCE_ALPHA): RGB_to_LA(num, source, dest); break;
case(GL_RGB): RGB_to_RGB(num, source, dest); break;
@ -130,7 +130,7 @@ struct ProcessRow
case(GL_RGBA):
switch(dest_pixelFormat)
{
case(GL_LUMINANCE):
case(GL_LUMINANCE):
case(GL_ALPHA): RGBA_to_A(num, source, dest); break;
case(GL_LUMINANCE_ALPHA): RGBA_to_LA(num, source, dest); break;
case(GL_RGB): RGBA_to_RGB(num, source, dest); break;
@ -141,7 +141,7 @@ struct ProcessRow
}
///////////////////////////////////////////////////////////////////////////////
// alpha sources..
// alpha sources..
virtual void A_to_A(unsigned int num, unsigned char* source, unsigned char* dest) const
{
for(unsigned int i=0;i<num;++i)
@ -158,7 +158,7 @@ struct ProcessRow
*dest++ = *source++;
}
}
virtual void A_to_RGB(unsigned int num, unsigned char* source, unsigned char* dest) const
{
for(unsigned int i=0;i<num;++i)
@ -181,7 +181,7 @@ struct ProcessRow
}
///////////////////////////////////////////////////////////////////////////////
// alpha luminance sources..
// alpha luminance sources..
virtual void LA_to_A(unsigned int num, unsigned char* source, unsigned char* dest) const
{
for(unsigned int i=0;i<num;++i)
@ -199,7 +199,7 @@ struct ProcessRow
*dest++ = *source++;
}
}
virtual void LA_to_RGB(unsigned int num, unsigned char* source, unsigned char* dest) const
{
for(unsigned int i=0;i<num;++i)
@ -223,7 +223,7 @@ struct ProcessRow
}
///////////////////////////////////////////////////////////////////////////////
// RGB sources..
// RGB sources..
virtual void RGB_to_A(unsigned int num, unsigned char* source, unsigned char* dest) const
{
for(unsigned int i=0;i<num;++i)
@ -244,7 +244,7 @@ struct ProcessRow
source += 3;
}
}
virtual void RGB_to_RGB(unsigned int num, unsigned char* source, unsigned char* dest) const
{
for(unsigned int i=0;i<num;++i)
@ -268,7 +268,7 @@ struct ProcessRow
}
///////////////////////////////////////////////////////////////////////////////
// RGBA sources..
// RGBA sources..
virtual void RGBA_to_A(unsigned int num, unsigned char* source, unsigned char* dest) const
{
for(unsigned int i=0;i<num;++i)
@ -288,7 +288,7 @@ struct ProcessRow
*dest++ = *source++;
}
}
virtual void RGBA_to_RGB(unsigned int num, unsigned char* source, unsigned char* dest) const
{
for(unsigned int i=0;i<num;++i)
@ -330,8 +330,8 @@ void clampToNearestValidPowerOfTwo(int& sizeX, int& sizeY, int& sizeZ, int s_max
sizeZ = r_nearestPowerOfTwo;
}
osg::Image* createTexture3D(ImageList& imageList, ProcessRow& processRow,
unsigned int numComponentsDesired,
osg::Image* createTexture3D(ImageList& imageList, ProcessRow& processRow,
unsigned int numComponentsDesired,
int s_maximumTextureSize,
int t_maximumTextureSize,
int r_maximumTextureSize,
@ -348,11 +348,11 @@ osg::Image* createTexture3D(ImageList& imageList, ProcessRow& processRow,
{
osg::Image* image = itr->get();
GLenum pixelFormat = image->getPixelFormat();
if (pixelFormat==GL_ALPHA ||
pixelFormat==GL_INTENSITY ||
pixelFormat==GL_LUMINANCE ||
pixelFormat==GL_LUMINANCE_ALPHA ||
pixelFormat==GL_RGB ||
if (pixelFormat==GL_ALPHA ||
pixelFormat==GL_INTENSITY ||
pixelFormat==GL_LUMINANCE ||
pixelFormat==GL_LUMINANCE_ALPHA ||
pixelFormat==GL_RGB ||
pixelFormat==GL_RGBA)
{
max_s = osg::maximum(image->s(), max_s);
@ -365,9 +365,9 @@ osg::Image* createTexture3D(ImageList& imageList, ProcessRow& processRow,
osg::notify(osg::NOTICE)<<"Image "<<image->getFileName()<<" has unsuitable pixel format"<< std::hex<< pixelFormat << std::dec << std::endl;
}
}
if (numComponentsDesired!=0) max_components = numComponentsDesired;
GLenum desiredPixelFormat = 0;
switch(max_components)
{
@ -387,11 +387,11 @@ osg::Image* createTexture3D(ImageList& imageList, ProcessRow& processRow,
osg::notify(osg::NOTICE)<<"desiredPixelFormat = GL_RGBA" << std::endl;
desiredPixelFormat = GL_RGBA;
break;
}
}
if (desiredPixelFormat==0) return 0;
// compute nearest powers of two for each axis.
int s_nearestPowerOfTwo = 1;
int t_nearestPowerOfTwo = 1;
int r_nearestPowerOfTwo = 1;
@ -412,12 +412,12 @@ osg::Image* createTexture3D(ImageList& imageList, ProcessRow& processRow,
t_nearestPowerOfTwo = max_t;
r_nearestPowerOfTwo = total_r;
}
// now allocate the 3d texture;
osg::ref_ptr<osg::Image> image_3d = new osg::Image;
image_3d->allocateImage(s_nearestPowerOfTwo,t_nearestPowerOfTwo,r_nearestPowerOfTwo,
desiredPixelFormat,GL_UNSIGNED_BYTE);
unsigned int r_offset = (total_r<r_nearestPowerOfTwo) ? r_nearestPowerOfTwo/2 - total_r/2 : 0;
@ -430,18 +430,18 @@ osg::Image* createTexture3D(ImageList& imageList, ProcessRow& processRow,
{
osg::Image* image = itr->get();
GLenum pixelFormat = image->getPixelFormat();
if (pixelFormat==GL_ALPHA ||
pixelFormat==GL_LUMINANCE ||
pixelFormat==GL_INTENSITY ||
pixelFormat==GL_LUMINANCE_ALPHA ||
pixelFormat==GL_RGB ||
if (pixelFormat==GL_ALPHA ||
pixelFormat==GL_LUMINANCE ||
pixelFormat==GL_INTENSITY ||
pixelFormat==GL_LUMINANCE_ALPHA ||
pixelFormat==GL_RGB ||
pixelFormat==GL_RGBA)
{
int num_r = osg::minimum(image->r(), (image_3d->r() - curr_dest_r));
int num_t = osg::minimum(image->t(), image_3d->t());
int num_s = osg::minimum(image->s(), image_3d->s());
unsigned int s_offset_dest = (image->s()<s_nearestPowerOfTwo) ? s_nearestPowerOfTwo/2 - image->s()/2 : 0;
unsigned int t_offset_dest = (image->t()<t_nearestPowerOfTwo) ? t_nearestPowerOfTwo/2 - image->t()/2 : 0;
@ -456,7 +456,7 @@ osg::Image* createTexture3D(ImageList& imageList, ProcessRow& processRow,
}
}
}
}
}
return image_3d.release();
}
@ -466,14 +466,14 @@ struct ScaleOperator
ScaleOperator():_scale(1.0f) {}
ScaleOperator(float scale):_scale(scale) {}
ScaleOperator(const ScaleOperator& so):_scale(so._scale) {}
ScaleOperator& operator = (const ScaleOperator& so) { _scale = so._scale; return *this; }
float _scale;
inline void luminance(float& l) const { l*= _scale; }
inline void alpha(float& a) const { a*= _scale; }
inline void luminance_alpha(float& l,float& a) const { l*= _scale; a*= _scale; }
inline void luminance(float& l) const { l*= _scale; }
inline void alpha(float& a) const { a*= _scale; }
inline void luminance_alpha(float& l,float& a) const { l*= _scale; a*= _scale; }
inline void rgb(float& r,float& g,float& b) const { r*= _scale; g*=_scale; b*=_scale; }
inline void rgba(float& r,float& g,float& b,float& a) const { r*= _scale; g*=_scale; b*=_scale; a*=_scale; }
};
@ -484,10 +484,10 @@ struct RecordRowOperator
mutable std::vector<osg::Vec4> _colours;
mutable unsigned int _pos;
inline void luminance(float l) const { rgba(l,l,l,1.0f); }
inline void alpha(float a) const { rgba(1.0f,1.0f,1.0f,a); }
inline void luminance_alpha(float l,float a) const { rgba(l,l,l,a); }
inline void luminance(float l) const { rgba(l,l,l,1.0f); }
inline void alpha(float a) const { rgba(1.0f,1.0f,1.0f,a); }
inline void luminance_alpha(float l,float a) const { rgba(l,l,l,a); }
inline void rgb(float r,float g,float b) const { rgba(r,g,b,1.0f); }
inline void rgba(float r,float g,float b,float a) const { _colours[_pos++].set(r,g,b,a); }
};
@ -499,10 +499,10 @@ struct WriteRowOperator
std::vector<osg::Vec4> _colours;
mutable unsigned int _pos;
inline void luminance(float& l) const { l = _colours[_pos++].r(); }
inline void alpha(float& a) const { a = _colours[_pos++].a(); }
inline void luminance_alpha(float& l,float& a) const { l = _colours[_pos].r(); a = _colours[_pos++].a(); }
inline void luminance(float& l) const { l = _colours[_pos++].r(); }
inline void alpha(float& a) const { a = _colours[_pos++].a(); }
inline void luminance_alpha(float& l,float& a) const { l = _colours[_pos].r(); a = _colours[_pos++].a(); }
inline void rgb(float& r,float& g,float& b) const { r = _colours[_pos].r(); g = _colours[_pos].g(); b = _colours[_pos].b(); }
inline void rgba(float& r,float& g,float& b,float& a) const { r = _colours[_pos].r(); g = _colours[_pos].g(); b = _colours[_pos].b(); a = _colours[_pos++].a(); }
};
@ -524,20 +524,20 @@ osg::Image* readRaw(int sizeX, int sizeY, int sizeZ, int numberBytesPerComponent
return 0;
}
GLenum dataType;
switch(numberBytesPerComponent)
{
case 1 : dataType = GL_UNSIGNED_BYTE; break;
case 2 : dataType = GL_UNSIGNED_SHORT; break;
case 4 : dataType = GL_UNSIGNED_INT; break;
default :
default :
osg::notify(osg::NOTICE)<<"Error: numberBytesPerComponent="<<numberBytesPerComponent<<" not supported, only 1,2 or 4 are supported."<<std::endl;
return 0;
}
int s_maximumTextureSize=256, t_maximumTextureSize=256, r_maximumTextureSize=256;
int sizeS = sizeX;
int sizeT = sizeY;
int sizeR = sizeZ;
@ -545,12 +545,12 @@ osg::Image* readRaw(int sizeX, int sizeY, int sizeZ, int numberBytesPerComponent
osg::ref_ptr<osg::Image> image = new osg::Image;
image->allocateImage(sizeS, sizeT, sizeR, pixelFormat, dataType);
bool endianSwap = (osg::getCpuByteOrder()==osg::BigEndian) ? (endian!="big") : (endian=="big");
unsigned int r_offset = (sizeZ<sizeR) ? sizeR/2 - sizeZ/2 : 0;
int offset = endianSwap ? numberBytesPerComponent : 0;
int delta = endianSwap ? -1 : 1;
for(int r=0;r<sizeZ;++r)
@ -561,7 +561,7 @@ osg::Image* readRaw(int sizeX, int sizeY, int sizeZ, int numberBytesPerComponent
for(int s=0;s<sizeX;++s)
{
if (!fin) return 0;
for(int c=0;c<numberOfComponents;++c)
{
char* ptr = data+offset;
@ -582,19 +582,19 @@ osg::Image* readRaw(int sizeX, int sizeY, int sizeZ, int numberBytesPerComponent
// compute range of values
osg::Vec4 minValue, maxValue;
osg::computeMinMax(image.get(), minValue, maxValue);
osg::modifyImage(image.get(),ScaleOperator(1.0f/maxValue.r()));
osg::modifyImage(image.get(),ScaleOperator(1.0f/maxValue.r()));
}
fin.close();
if (dataType!=GL_UNSIGNED_BYTE)
{
// need to convert to ubyte
osg::ref_ptr<osg::Image> new_image = new osg::Image;
new_image->allocateImage(sizeS, sizeT, sizeR, pixelFormat, GL_UNSIGNED_BYTE);
RecordRowOperator readOp(sizeS);
WriteRowOperator writeOp;
@ -605,26 +605,26 @@ osg::Image* readRaw(int sizeX, int sizeY, int sizeZ, int numberBytesPerComponent
// reset the indices to beginning
readOp._pos = 0;
writeOp._pos = 0;
// read the pixels into readOp's _colour array
osg::readRow(sizeS, pixelFormat, dataType, image->data(0,t,r), readOp);
// pass readOp's _colour array contents over to writeOp (note this is just a pointer swap).
writeOp._colours.swap(readOp._colours);
osg::modifyRow(sizeS, pixelFormat, GL_UNSIGNED_BYTE, new_image->data(0,t,r), writeOp);
// return readOp's _colour array contents back to its rightful owner.
writeOp._colours.swap(readOp._colours);
}
}
image = new_image;
}
return image.release();
}
enum ColourSpaceOperation
@ -640,9 +640,9 @@ struct ModulateAlphaByLuminanceOperator
{
ModulateAlphaByLuminanceOperator() {}
inline void luminance(float&) const {}
inline void alpha(float&) const {}
inline void luminance_alpha(float& l,float& a) const { a*= l; }
inline void luminance(float&) const {}
inline void alpha(float&) const {}
inline void luminance_alpha(float& l,float& a) const { a*= l; }
inline void rgb(float&,float&,float&) const {}
inline void rgba(float& r,float& g,float& b,float& a) const { float l = (r+g+b)*0.3333333; a *= l;}
};
@ -650,13 +650,13 @@ struct ModulateAlphaByLuminanceOperator
struct ModulateAlphaByColourOperator
{
ModulateAlphaByColourOperator(const osg::Vec4& colour):_colour(colour) { _lum = _colour.length(); }
osg::Vec4 _colour;
float _lum;
inline void luminance(float&) const {}
inline void alpha(float&) const {}
inline void luminance_alpha(float& l,float& a) const { a*= l*_lum; }
inline void luminance(float&) const {}
inline void alpha(float&) const {}
inline void luminance_alpha(float& l,float& a) const { a*= l*_lum; }
inline void rgb(float&,float&,float&) const {}
inline void rgba(float& r,float& g,float& b,float& a) const { a = (r*_colour.r()+g*_colour.g()+b*_colour.b()+a*_colour.a()); }
};
@ -665,9 +665,9 @@ struct ReplaceAlphaWithLuminanceOperator
{
ReplaceAlphaWithLuminanceOperator() {}
inline void luminance(float&) const {}
inline void alpha(float&) const {}
inline void luminance_alpha(float& l,float& a) const { a= l; }
inline void luminance(float&) const {}
inline void alpha(float&) const {}
inline void luminance_alpha(float& l,float& a) const { a= l; }
inline void rgb(float&,float&,float&) const { }
inline void rgba(float& r,float& g,float& b,float& a) const { float l = (r+g+b)*0.3333333; a = l; }
};
@ -679,19 +679,19 @@ osg::Image* doColourSpaceConversion(ColourSpaceOperation op, osg::Image* image,
case (MODULATE_ALPHA_BY_LUMINANCE):
{
std::cout<<"doing conversion MODULATE_ALPHA_BY_LUMINANCE"<<std::endl;
osg::modifyImage(image,ModulateAlphaByLuminanceOperator());
osg::modifyImage(image,ModulateAlphaByLuminanceOperator());
return image;
}
case (MODULATE_ALPHA_BY_COLOUR):
{
std::cout<<"doing conversion MODULATE_ALPHA_BY_COLOUR"<<std::endl;
osg::modifyImage(image,ModulateAlphaByColourOperator(colour));
osg::modifyImage(image,ModulateAlphaByColourOperator(colour));
return image;
}
case (REPLACE_ALPHA_WITH_LUMINANCE):
{
std::cout<<"doing conversion REPLACE_ALPHA_WITH_LUMINANCE"<<std::endl;
osg::modifyImage(image,ReplaceAlphaWithLuminanceOperator());
osg::modifyImage(image,ReplaceAlphaWithLuminanceOperator());
return image;
}
case (REPLACE_RGB_WITH_LUMINANCE):
@ -700,7 +700,7 @@ osg::Image* doColourSpaceConversion(ColourSpaceOperation op, osg::Image* image,
osg::Image* newImage = new osg::Image;
newImage->allocateImage(image->s(), image->t(), image->r(), GL_LUMINANCE, image->getDataType());
osg::copyImage(image, 0, 0, 0, image->s(), image->t(), image->r(),
newImage, 0, 0, 0, false);
newImage, 0, 0, 0, false);
return newImage;
}
default:
@ -712,12 +712,12 @@ osg::Image* doColourSpaceConversion(ColourSpaceOperation op, osg::Image* image,
osg::TransferFunction1D* readTransferFunctionFile(const std::string& filename)
{
std::string foundFile = osgDB::findDataFile(filename);
if (foundFile.empty())
if (foundFile.empty())
{
std::cout<<"Error: could not find transfer function file : "<<filename<<std::endl;
return 0;
}
std::cout<<"Reading transfer function "<<filename<<std::endl;
osg::TransferFunction1D::ColorMap colorMap;
@ -726,22 +726,22 @@ osg::TransferFunction1D* readTransferFunctionFile(const std::string& filename)
{
float value, red, green, blue, alpha;
fin >> value >> red >> green >> blue >> alpha;
if (fin)
if (fin)
{
std::cout<<"value = "<<value<<" ("<<red<<", "<<green<<", "<<blue<<", "<<alpha<<")"<<std::endl;
colorMap[value] = osg::Vec4(red,green,blue,alpha);
}
}
if (colorMap.empty())
{
std::cout<<"Error: No values read from transfer function file: "<<filename<<std::endl;
return 0;
}
osg::TransferFunction1D* tf = new osg::TransferFunction1D;
tf->assign(colorMap);
return tf;
}
@ -761,10 +761,10 @@ public:
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(mutex);
glGetIntegerv( GL_MAX_3D_TEXTURE_SIZE, &maximumTextureSize );
osg::notify(osg::NOTICE)<<"Max texture size="<<maximumTextureSize<<std::endl;
}
OpenThreads::Mutex mutex;
bool supported;
std::string errorMessage;
@ -840,7 +840,7 @@ int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of 3D textures.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
@ -884,12 +884,12 @@ int main( int argc, char **argv )
// add the window size toggle handler
viewer.addEventHandler(new osgViewer::WindowSizeHandler);
{
osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
osgGA::FlightManipulator* flightManipulator = new osgGA::FlightManipulator();
flightManipulator->setYawControlMode(osgGA::FlightManipulator::NO_AUTOMATIC_YAW);
keyswitchManipulator->addMatrixManipulator( '2', "Flight", flightManipulator );
@ -920,7 +920,7 @@ int main( int argc, char **argv )
{
transferFunction = readTransferFunctionFile(tranferFunctionFile);
}
while(arguments.read("--test"))
{
transferFunction = new osg::TransferFunction1D;
@ -940,8 +940,8 @@ int main( int argc, char **argv )
unsigned int numSlices=500;
while (arguments.read("-s",numSlices)) {}
float sliceEnd=1.0f;
while (arguments.read("--clip",sliceEnd)) {}
@ -949,7 +949,7 @@ int main( int argc, char **argv )
while (arguments.read("--alphaFunc",alphaFunc)) {}
ShadingModel shadingModel = Standard;
while(arguments.read("--mip")) shadingModel = MaximumIntensityProjection;
@ -964,7 +964,7 @@ int main( int argc, char **argv )
osg::ref_ptr<TestSupportOperation> testSupportOperation = new TestSupportOperation;
viewer.setRealizeOperation(testSupportOperation.get());
viewer.realize();
int maximumTextureSize = testSupportOperation->maximumTextureSize;
@ -987,8 +987,8 @@ int main( int argc, char **argv )
while(arguments.read("--compressed-dxt1")) { internalFormatMode = osg::Texture::USE_S3TC_DXT1_COMPRESSION; }
while(arguments.read("--compressed-dxt3")) { internalFormatMode = osg::Texture::USE_S3TC_DXT3_COMPRESSION; }
while(arguments.read("--compressed-dxt5")) { internalFormatMode = osg::Texture::USE_S3TC_DXT5_COMPRESSION; }
// set up colour space operation.
ColourSpaceOperation colourSpaceOperation = NO_COLOUR_SPACE_OPERATION;
osg::Vec4 colourModulate(0.25f,0.25f,0.25f,0.25f);
@ -1004,61 +1004,61 @@ int main( int argc, char **argv )
RESCALE_TO_ZERO_TO_ONE_RANGE,
SHIFT_MIN_TO_ZERO
};
RescaleOperation rescaleOperation = RESCALE_TO_ZERO_TO_ONE_RANGE;
while(arguments.read("--no-rescale")) rescaleOperation = NO_RESCALE;
while(arguments.read("--rescale")) rescaleOperation = RESCALE_TO_ZERO_TO_ONE_RANGE;
while(arguments.read("--shift-min-to-zero")) rescaleOperation = SHIFT_MIN_TO_ZERO;
bool resizeToPowerOfTwo = false;
unsigned int numComponentsDesired = 0;
unsigned int numComponentsDesired = 0;
while(arguments.read("--num-components", numComponentsDesired)) {}
bool useManipulator = false;
while(arguments.read("--manipulator") || arguments.read("-m")) { useManipulator = true; }
bool useShader = true;
bool useShader = true;
while(arguments.read("--shader")) { useShader = true; }
while(arguments.read("--no-shader")) { useShader = false; }
bool gpuTransferFunction = true;
bool gpuTransferFunction = true;
while(arguments.read("--gpu-tf")) { gpuTransferFunction = true; }
while(arguments.read("--cpu-tf")) { gpuTransferFunction = false; }
double sequenceLength = 10.0;
while(arguments.read("--sequence-duration", sequenceLength) ||
arguments.read("--sd", sequenceLength)) {}
while(arguments.read("--sequence-duration", sequenceLength) ||
arguments.read("--sd", sequenceLength)) {}
typedef std::list< osg::ref_ptr<osg::Image> > Images;
Images images;
std::string vh_filename;
while (arguments.read("--vh", vh_filename))
while (arguments.read("--vh", vh_filename))
{
std::string raw_filename, transfer_filename;
int xdim(0), ydim(0), zdim(0);
int xdim(0), ydim(0), zdim(0);
osgDB::ifstream header(vh_filename.c_str());
if (header)
{
header >> raw_filename >> transfer_filename >> xdim >> ydim >> zdim >> xSize >> ySize >> zSize;
}
if (xdim*ydim*zdim==0)
{
std::cout<<"Error in reading volume header "<<vh_filename<<std::endl;
return 1;
}
if (!raw_filename.empty())
{
images.push_back(readRaw(xdim, ydim, zdim, 1, 1, "little", raw_filename));
}
if (!transfer_filename.empty())
{
osgDB::ifstream fin(transfer_filename.c_str());
@ -1070,7 +1070,7 @@ int main( int argc, char **argv )
{
float red, green, blue, alpha;
fin >> red >> green >> blue >> alpha;
if (fin)
if (fin)
{
colorMap[value] = osg::Vec4(red/255.0f,green/255.0f,blue/255.0f,alpha/255.0f);
std::cout<<"value = "<<value<<" ("<<red<<", "<<green<<", "<<blue<<", "<<alpha<<")";
@ -1091,11 +1091,11 @@ int main( int argc, char **argv )
}
}
int sizeX, sizeY, sizeZ, numberBytesPerComponent, numberOfComponents;
std::string endian, raw_filename;
while (arguments.read("--raw", sizeX, sizeY, sizeZ, numberBytesPerComponent, numberOfComponents, endian, raw_filename))
while (arguments.read("--raw", sizeX, sizeY, sizeZ, numberBytesPerComponent, numberOfComponents, endian, raw_filename))
{
images.push_back(readRaw(sizeX, sizeY, sizeZ, numberBytesPerComponent, numberOfComponents, endian, raw_filename));
}
@ -1115,9 +1115,9 @@ int main( int argc, char **argv )
imageList.push_back(image);
}
}
arguments.remove(images_pos, pos-images_pos);
// pack the textures into a single texture.
ProcessRow processRow;
images.push_back(createTexture3D(imageList, processRow, numComponentsDesired, s_maximumTextureSize, t_maximumTextureSize, r_maximumTextureSize, resizeToPowerOfTwo));
@ -1133,7 +1133,7 @@ int main( int argc, char **argv )
arguments.writeErrorMessages(std::cout);
return 1;
}
// assume remaining arguments are file names of textures.
for(int pos=1;pos<arguments.argc();++pos)
@ -1161,11 +1161,11 @@ int main( int argc, char **argv )
if (fileType == osgDB::DIRECTORY)
{
osg::Image *image = osgDB::readImageFile(filename+".dicom");
osg::Image *image = osgDB::readImageFile(filename+".dicom");
if(image)
{
images.push_back(image);
}
}
}
else if (fileType == osgDB::REGULAR_FILE)
{
@ -1177,11 +1177,11 @@ int main( int argc, char **argv )
osg::notify(osg::NOTICE)<<"Error: could not find file: "<<filename<<std::endl;
return 1;
}
}
}
}
}
if (images.empty())
if (images.empty())
{
std::cout<<"No model loaded, please specify and volumetric image file on the command line."<<std::endl;
return 1;
@ -1196,7 +1196,7 @@ int main( int argc, char **argv )
for(;sizeItr != images.end(); ++sizeItr)
{
if ((*sizeItr)->s() != image_s ||
if ((*sizeItr)->s() != image_s ||
(*sizeItr)->t() != image_t ||
(*sizeItr)->r() != image_r)
{
@ -1206,14 +1206,15 @@ int main( int argc, char **argv )
}
osg::ref_ptr<osg::RefMatrix> matrix = dynamic_cast<osg::RefMatrix*>(images.front()->getUserData());
osg::ref_ptr<osgVolume::ImageDetails> details = dynamic_cast<osgVolume::ImageDetails*>(images.front()->getUserData());
osg::ref_ptr<osg::RefMatrix> matrix = details ? details->getMatrix() : dynamic_cast<osg::RefMatrix*>(images.front()->getUserData());
if (!matrix)
{
if (xSize==0.0) xSize = static_cast<float>(image_s);
if (ySize==0.0) ySize = static_cast<float>(image_t);
if (zSize==0.0) zSize = static_cast<float>(image_r);
matrix = new osg::RefMatrix(xSize, 0.0, 0.0, 0.0,
0.0, ySize, 0.0, 0.0,
0.0, 0.0, zSize, 0.0,
@ -1245,7 +1246,7 @@ int main( int argc, char **argv )
computeMinMax = true;
}
}
if (computeMinMax)
{
osg::notify(osg::NOTICE)<<"Min value "<<minValue<<std::endl;
@ -1261,7 +1262,7 @@ int main( int argc, char **argv )
maxComponent = osg::maximum(maxComponent,maxValue[2]);
maxComponent = osg::maximum(maxComponent,maxValue[3]);
#if 0
switch(rescaleOperation)
{
case(NO_RESCALE):
@ -1275,8 +1276,8 @@ int main( int argc, char **argv )
for(Images::iterator itr = images.begin();
itr != images.end();
++itr)
{
osg::offsetAndScaleImage(itr->get(),
{
osg::offsetAndScaleImage(itr->get(),
osg::Vec4(offset, offset, offset, offset),
osg::Vec4(scale, scale, scale, scale));
}
@ -1289,38 +1290,38 @@ int main( int argc, char **argv )
for(Images::iterator itr = images.begin();
itr != images.end();
++itr)
{
osg::offsetAndScaleImage(itr->get(),
{
osg::offsetAndScaleImage(itr->get(),
osg::Vec4(offset, offset, offset, offset),
osg::Vec4(1.0f, 1.0f, 1.0f, 1.0f));
}
break;
}
};
#endif
}
if (colourSpaceOperation!=NO_COLOUR_SPACE_OPERATION)
{
for(Images::iterator itr = images.begin();
itr != images.end();
++itr)
{
{
(*itr) = doColourSpaceConversion(colourSpaceOperation, itr->get(), colourModulate);
}
}
if (!gpuTransferFunction && transferFunction.valid())
{
for(Images::iterator itr = images.begin();
itr != images.end();
++itr)
{
{
*itr = osgVolume::applyTransferFunction(itr->get(), transferFunction.get());
}
}
osg::ref_ptr<osg::Image> image_3d = 0;
if (images.size()==1)
@ -1331,24 +1332,47 @@ int main( int argc, char **argv )
else
{
osg::notify(osg::NOTICE)<<"Creating sequence of "<<images.size()<<" volumes."<<std::endl;
osg::ref_ptr<osg::ImageSequence> imageSequence = new osg::ImageSequence;
imageSequence->setLength(sequenceLength);
image_3d = imageSequence.get();
for(Images::iterator itr = images.begin();
itr != images.end();
++itr)
{
{
imageSequence->addImage(itr->get());
}
imageSequence->play();
}
osg::ref_ptr<osgVolume::Volume> volume = new osgVolume::Volume;
osg::ref_ptr<osgVolume::VolumeTile> tile = new osgVolume::VolumeTile;
volume->addChild(tile.get());
osg::ref_ptr<osgVolume::Layer> layer = new osgVolume::ImageLayer(image_3d.get());
osg::ref_ptr<osgVolume::ImageLayer> layer = new osgVolume::ImageLayer(image_3d.get());
if (details)
{
layer->setRescaleIntercept(details->getRescaleIntercept());
layer->setRescaleSlope(details->getRescaleSlope());
}
switch(rescaleOperation)
{
case(NO_RESCALE):
break;
case(RESCALE_TO_ZERO_TO_ONE_RANGE):
{
layer->rescaleToZeroToOneRange();
break;
}
case(SHIFT_MIN_TO_ZERO):
{
layer->translateMinToZero();
break;
}
};
layer->setLocator(new osgVolume::Locator(*matrix));
tile->setLocator(new osgVolume::Locator(*matrix));
@ -1431,23 +1455,23 @@ int main( int argc, char **argv )
layer->addProperty(new osgVolume::AlphaFuncProperty(alphaFunc));
tile->setVolumeTechnique(new osgVolume::FixedFunctionTechnique);
}
if (!outputFile.empty())
{
{
std::string ext = osgDB::getFileExtension(outputFile);
std::string name_no_ext = osgDB::getNameLessExtension(outputFile);
if (ext=="osg")
{
if (image_3d.valid())
{
image_3d->setFileName(name_no_ext + ".dds");
image_3d->setFileName(name_no_ext + ".dds");
osgDB::writeImageFile(*image_3d, image_3d->getFileName());
}
osgDB::writeNodeFile(*volume, outputFile);
}
else if (ext=="ive")
{
osgDB::writeNodeFile(*volume, outputFile);
osgDB::writeNodeFile(*volume, outputFile);
}
else if (ext=="dds")
{
@ -1457,11 +1481,11 @@ int main( int argc, char **argv )
{
std::cout<<"Extension not support for file output, not file written."<<std::endl;
}
return 0;
}
if (volume.valid())
if (volume.valid())
{
osg::ref_ptr<osg::Node> loadedModel = volume.get();
@ -1494,11 +1518,11 @@ int main( int argc, char **argv )
// set the scene to render
viewer.setSceneData(loadedModel.get());
// the the viewers main frame loop
viewer.run();
}
}
return 0;
}

View File

@ -22,6 +22,37 @@
namespace osgVolume {
/** Data strucutre for passing details about the loading imagery on to osgVolume for use when setting up dimensions etc.*/
class OSGVOLUME_EXPORT ImageDetails : public osg::Object
{
public:
ImageDetails();
/** Copy constructor using CopyOp to manage deep vs shallow copy.*/
ImageDetails(const ImageDetails&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
META_Object(osgVolume, ImageDetails);
void setRescaleIntercept(double intercept) { _rescaleIntercept = intercept; }
double getRescaleIntercept() const { return _rescaleIntercept; }
void setRescaleSlope(double slope) { _rescaleSlope = slope; }
double getRescaleSlope() const { return _rescaleSlope; }
void setMatrix(osg::RefMatrix* matrix) { _matrix = matrix; }
osg::RefMatrix* getMatrix() { return _matrix.get(); }
const osg::RefMatrix* getMatrix() const { return _matrix.get(); }
protected:
double _rescaleIntercept;
double _rescaleSlope;
osg::ref_ptr<osg::RefMatrix> _matrix;
};
/** Base class for representing a single layer of volume data.*/
class OSGVOLUME_EXPORT Layer : public osg::Object
{
public:
@ -30,9 +61,9 @@ class OSGVOLUME_EXPORT Layer : public osg::Object
/** Copy constructor using CopyOp to manage deep vs shallow copy.*/
Layer(const Layer&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
META_Object(osgVolume, Layer);
/** Set the file name of the data associated with this layer. */
virtual void setFileName(const std::string& filename) { _filename = filename; }
@ -42,7 +73,7 @@ class OSGVOLUME_EXPORT Layer : public osg::Object
void setLocator(Locator* locator) { _locator = locator; }
Locator* getLocator() { return _locator.get(); }
const Locator* getLocator() const { return _locator.get(); }
void setDefaultValue(const osg::Vec4& value) { _defaultValue = value; }
const osg::Vec4& getDefaultValue() const { return _defaultValue; }
@ -58,10 +89,10 @@ class OSGVOLUME_EXPORT Layer : public osg::Object
/** Get the magnification texture filter to use when do texture associated with this layer.*/
osg::Texture::FilterMode getMagFilter() const { return _magFilter; }
/** Return image associated with layer if supported. */
/** Return image associated with layer if supported. */
virtual osg::Image* getImage() { return 0; }
/** Return const image associated with layer if supported. */
/** Return const image associated with layer if supported. */
virtual const osg::Image* getImage() const { return 0; }
@ -82,7 +113,7 @@ class OSGVOLUME_EXPORT Layer : public osg::Object
virtual bool requiresUpdateTraversal() const { return false; }
/** Call update on the Layer.*/
virtual void update(osg::NodeVisitor& /*nv*/) {}
virtual void update(osg::NodeVisitor& /*nv*/) {}
/** increment the modified count."*/
virtual void dirty() {};
@ -104,7 +135,7 @@ class OSGVOLUME_EXPORT Layer : public osg::Object
osg::Vec4 _defaultValue;
osg::Texture::FilterMode _minFilter;
osg::Texture::FilterMode _magFilter;
osg::ref_ptr<Property> _property;
};
@ -117,7 +148,7 @@ class OSGVOLUME_EXPORT ImageLayer : public Layer
/** Copy constructor using CopyOp to manage deep vs shallow copy.*/
ImageLayer(const ImageLayer& imageLayer,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
META_Object(osgVolume, ImageLayer);
void setFileName(const std::string& filename) { _filename = filename; if (_image.valid()) _image->setFileName(filename); }
@ -125,21 +156,29 @@ class OSGVOLUME_EXPORT ImageLayer : public Layer
void setImage(osg::Image* image);
/** Return image associated with layer. */
/** Return image associated with layer. */
virtual osg::Image* getImage() { return _image.get(); }
/** Return const image associated with layer. */
virtual const osg::Image* getImage() const { return _image.get(); }
void setRescaleIntercept(double intercept) { _rescaleIntercept = intercept; }
double getRescaleIntercept() const { return _rescaleIntercept; }
void setRescaleSlope(double slope) { _rescaleSlope = slope; }
double setRescaleSlope() const { return _rescaleSlope; }
/** Compute the min and max pixel colors.*/
bool computeMinMax(osg::Vec4& min, osg::Vec4& max);
/** Apply color transformation to pixels using c' = offset + c * scale .*/
void offsetAndScaleImage(const osg::Vec4& offset, const osg::Vec4& scale);
/** Compute the min max range of the image, and then remap this to a 0 to 1 range.*/
void rescaleToZeroToOneRange();
/** Compute the min color component of the image and then translate and pixels by this offset to make the new min component 0.*/
void translateMinToZero();
@ -155,6 +194,8 @@ class OSGVOLUME_EXPORT ImageLayer : public Layer
virtual ~ImageLayer() {}
double _rescaleIntercept;
double _rescaleSlope;
osg::ref_ptr<osg::Image> _image;
};
@ -167,7 +208,7 @@ class OSGVOLUME_EXPORT CompositeLayer : public Layer
/** Copy constructor using CopyOp to manage deep vs shallow copy.*/
CompositeLayer(const CompositeLayer& compositeLayer,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
META_Object(osgVolume, CompositeLayer);
void clear();
@ -182,11 +223,11 @@ class OSGVOLUME_EXPORT CompositeLayer : public Layer
void addLayer(Layer* layer) { _layers.push_back(NameLayer(layer->getFileName(),layer)); }
void removeLayer(unsigned int i) { _layers.erase(_layers.begin()+i); }
unsigned int getNumLayers() const { return _layers.size(); }
bool requiresUpdateTraversal() const;
virtual void update(osg::NodeVisitor& /*nv*/);
protected:
@ -196,7 +237,7 @@ class OSGVOLUME_EXPORT CompositeLayer : public Layer
struct NameLayer
{
NameLayer() {}
NameLayer(const NameLayer& cnl):
filename(cnl.filename),
layer(cnl.layer) {}
@ -208,7 +249,7 @@ class OSGVOLUME_EXPORT CompositeLayer : public Layer
NameLayer& operator = (const NameLayer& cnl)
{
if (&cnl==this) return *this;
filename = cnl.filename;
layer = cnl.layer;
return *this;
@ -217,9 +258,9 @@ class OSGVOLUME_EXPORT CompositeLayer : public Layer
std::string filename;
osg::ref_ptr<Layer> layer;
};
typedef std::vector< NameLayer > Layers;
Layers _layers;
};

View File

@ -23,9 +23,10 @@
#define HAVE_CONFIG_H
#endif
#include <dcmtk/config/osconfig.h>
#include <dcmtk/config/osconfig.h>
#include <dcmtk/dcmdata/dcfilefo.h>
#include <dcmtk/dcmdata/dcdeftag.h>
#include <dcmtk/dcmdata/dcuid.h>
#include <dcmtk/dcmimgle/dcmimage.h>
#endif
@ -48,7 +49,7 @@
class ReaderWriterDICOM : public osgDB::ReaderWriter
{
public:
ReaderWriterDICOM()
{
supportsExtension("mag","dicom image format");
@ -63,18 +64,18 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
std::ostream& warning() const { return osg::notify(osg::WARN); }
std::ostream& notice() const { return osg::notify(osg::NOTICE); }
std::ostream& info() const { return osg::notify(osg::INFO); }
template<typename T>
T* readData(std::istream& fin, unsigned int length, unsigned int& numComponents) const
{
numComponents = length/sizeof(T);
T* data = new T[numComponents];
fin.read((char*)data, numComponents*sizeof(T));
// read over any padding
length -= numComponents*sizeof(T);
while(fin && length>0) { fin.get(); --length; }
return data;
}
@ -89,8 +90,8 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
else out<<".";
}
}
else
{
else
{
for(unsigned int i=0; i<numComponents; ++i)
{
if (i==0) out<<data[i];
@ -98,9 +99,9 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
}
}
}
virtual const char* className() const { return "DICOM Image Reader/Writer"; }
typedef std::vector<std::string> Files;
bool getDicomFilesInDirectory(const std::string& path, Files& files) const
{
@ -143,16 +144,16 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
{
ReadResult result = readImage(file, options);
if (!result.validImage()) return result;
osg::ref_ptr<osgVolume::VolumeTile> tile = new osgVolume::VolumeTile;
tile->setVolumeTechnique(new osgVolume::RayTracedTechnique());
osg::ref_ptr<osgVolume::ImageLayer> layer= new osgVolume::ImageLayer(result.getImage());
layer->rescaleToZeroToOneRange();
osgVolume::SwitchProperty* sp = new osgVolume::SwitchProperty;
sp->setActiveProperty(0);
float alphaFunc = 0.1f;
osgVolume::AlphaFuncProperty* ap = new osgVolume::AlphaFuncProperty(alphaFunc);
@ -206,24 +207,31 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
tile->setLayer(layer.get());
// get matrix providing size of texels (in mm)
osg::RefMatrix* matrix = dynamic_cast<osg::RefMatrix*>(result.getImage()->getUserData());
osgVolume::ImageDetails* details = dynamic_cast<osgVolume::ImageDetails*>(result.getImage()->getUserData());
osg::RefMatrix* matrix = details ? details->getMatrix() : 0;
if (details)
{
layer->setRescaleIntercept(details->getRescaleIntercept());
layer->setRescaleSlope(details->getRescaleSlope());
}
if (matrix)
{
osgVolume::Locator* locator = new osgVolume::Locator(*matrix);
tile->setLocator(locator);
layer->setLocator(locator);
// result.getImage()->setUserData(0);
info()<<"Locator "<<*matrix<<std::endl;
}
else
{
info()<<"No Locator found on osg::Image"<<std::endl;
}
return tile.release();
}
@ -298,7 +306,8 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
++itr)
{
osg::Image* image = itr->get();
osg::RefMatrix* matrix = dynamic_cast<osg::RefMatrix*>(image->getUserData());
osgVolume::ImageDetails* details = dynamic_cast<osgVolume::ImageDetails*>(result.getImage()->getUserData());
osg::RefMatrix* matrix = details ? details->getMatrix() : 0;
if (matrix)
{
osg::Vec3 p0 = osg::Vec3(0.0, 0.0, 0.0) * (*matrix);
@ -340,18 +349,19 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
{
osg::Image* image = itr->second.get();
osg::copyImage(image, 0,0,0, image->s(), image->t(), image->r(),
image3D.get(), 0, 0, r,
false);
image3D.get(), 0, 0, r,
false);
r += image->r();
}
osg::Image* firstImage = dim.begin()->second.get();
osg::RefMatrix* matrix = dynamic_cast<osg::RefMatrix*>(firstImage->getUserData());
osgVolume::ImageDetails* details = dynamic_cast<osgVolume::ImageDetails*>(result.getImage()->getUserData());
osg::RefMatrix* matrix = details ? details->getMatrix() : 0;
if (matrix)
{
image3D->setUserData(
new osg::RefMatrix(osg::Matrix::scale(1.0,1.0,totalThickness) * (*matrix))
);
osgVolume::ImageDetails* details3D = new osgVolume::ImageDetails(*details);
details3D->getMatrix()->preMult(osg::Matrix::scale(1.0,1.0,totalThickness));
image3D->setUserData(details3D);
}
return image3D.get();
@ -384,36 +394,36 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
std::cerr << e.GetLocation() << std::endl;
return ReadResult::ERROR_IN_READING_FILE;
}
ImageType::Pointer inputImage = reader->GetOutput();
ImageType::RegionType region = inputImage->GetBufferedRegion();
ImageType::SizeType size = region.GetSize();
ImageType::IndexType start = region.GetIndex();
//inputImage->GetSpacing();
//inputImage->GetOrigin();
unsigned int width = size[0];
unsigned int height = size[1];
unsigned int depth = size[2];
osg::RefMatrix* matrix = new osg::RefMatrix;
info()<<"width = "<<width<<" height = "<<height<<" depth = "<<depth<<std::endl;
for(unsigned int i=0; i<Dimension; ++i)
{
(*matrix)(i,i) = inputImage->GetSpacing()[i];
(*matrix)(3,i) = inputImage->GetOrigin()[i];
}
osg::Image* image = new osg::Image;
image->allocateImage(width, height, depth, GL_LUMINANCE, GL_UNSIGNED_BYTE, 1);
unsigned char* data = image->data();
unsigned char* data = image->data();
typedef itk::ImageRegionConstIterator< ImageType > IteratorType;
IteratorType it(inputImage, region);
it.GoToBegin();
while (!it.IsAtEnd())
{
@ -421,9 +431,12 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
++data;
++it;
}
image->setUserData(matrix);
osgVolume::ImageDetails* details = new osgVolume::ImageDetails;
details->setMatrix(matrix);
image->setUserData(details);
matrix->preMult(osg::Matrix::scale(double(image->s()), double(image->t()), double(image->r())));
return image;
@ -432,9 +445,9 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
#ifdef USE_DCMTK
void convertPixelTypes(const DiPixel* pixelData,
EP_Representation& pixelRep, int& numPlanes,
GLenum& dataType, GLenum& pixelFormat, unsigned int& pixelSize) const
void convertPixelTypes(const DiPixel* pixelData,
EP_Representation& pixelRep, int& numPlanes,
GLenum& dataType, GLenum& pixelFormat, unsigned int& pixelSize) const
{
dataType = GL_UNSIGNED_BYTE;
pixelRep = pixelData->getRepresentation();
@ -490,7 +503,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
break;
}
}
@ -500,7 +513,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
std::string ext = osgDB::getLowerCaseFileExtension(file);
if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;
std::string fileName = file;
if (ext=="dicom")
{
@ -511,7 +524,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;
Files files;
osgDB::FileType fileType = osgDB::fileType(fileName);
if (fileType==osgDB::DIRECTORY)
{
@ -521,12 +534,12 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
{
#if 1
files.push_back(fileName);
#else
#else
if (!getDicomFilesInDirectory(osgDB::getFilePath(fileName), files))
{
files.push_back(fileName);
}
#endif
#endif
}
if (files.empty())
@ -534,22 +547,25 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
return ReadResult::FILE_NOT_FOUND;
}
osg::ref_ptr<osg::RefMatrix> matrix = new osg::RefMatrix;
osg::ref_ptr<osgVolume::ImageDetails> details = new osgVolume::ImageDetails;
details->setMatrix(new osg::RefMatrix);
osg::ref_ptr<osg::Image> image;
unsigned int imageNum = 0;
EP_Representation pixelRep = EPR_Uint8;
int numPlanes = 0;
GLenum pixelFormat = 0;
GLenum dataType = 0;
unsigned int pixelSize = 0;
typedef std::list<FileInfo> FileInfoList;
FileInfoList fileInfoList;
typedef std::map<double, FileInfo> DistanceFileInfoMap;
typedef std::map<osg::Vec3d, DistanceFileInfoMap> OrientationFileInfoMap;
OrientationFileInfoMap orientationFileInfoMap;
unsigned int totalNumSlices = 0;
for(Files::iterator itr = files.begin();
@ -559,7 +575,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
DcmFileFormat fileformat;
OFCondition status = fileformat.loadFile((*itr).c_str());
if(!status.good()) return ReadResult::ERROR_IN_READING_FILE;
FileInfo fileInfo;
fileInfo.filename = *itr;
@ -569,7 +585,33 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
double imagePositionPatient[3] = {0, 0, 0};
double imageOrientationPatient[6] = {1.0, 0.0, 0.0, 0.0, 1.0, 0.0 };
Uint16 numOfSlices = 1;
// code for reading the intercept and scale that is required to convert to Hounsfield units.
bool rescaling = false;
double rescaleIntercept = 0.0;
double rescaleSlope = 1.0;
const char *classUID = NULL;
if (fileformat.getDataset()->findAndGetString(DCM_SOPClassUID, classUID).good())
{
osg::notify(osg::NOTICE)<<" classUID = "<<classUID<<std::endl;
if (0 == strcmp(classUID, UID_CTImageStorage))
{
osg::notify(osg::NOTICE)<<" is a UID_CTImageStorage "<<std::endl;
}
}
rescaling = fileformat.getDataset()->findAndGetFloat64(DCM_RescaleIntercept, rescaleIntercept).good();
rescaling &= fileformat.getDataset()->findAndGetFloat64(DCM_RescaleSlope, rescaleSlope).good();
if (rescaling)
{
fileInfo.rescaleIntercept = rescaleIntercept;
fileInfo.rescaleSlope = rescaleSlope;
osg::notify(osg::NOTICE)<<" rescaleIntercept = "<<rescaleIntercept<<std::endl;
osg::notify(osg::NOTICE)<<" rescaleSlope = "<<rescaleSlope<<std::endl;
}
double value = 0.0;
if (fileformat.getDataset()->findAndGetFloat64(DCM_PixelSpacing, value,0).good())
{
@ -590,7 +632,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
info()<<"sliceThickness = "<<sliceThickness<<std::endl;
fileInfo.sliceThickness = sliceThickness;
}
info()<<"tagExistsWithValue(DCM_NumberOfFrames)="<<fileformat.getDataset()->tagExistsWithValue(DCM_NumberOfFrames)<<std::endl;
info()<<"tagExistsWithValue(DCM_NumberOfSlices)="<<fileformat.getDataset()->tagExistsWithValue(DCM_NumberOfSlices)<<std::endl;
@ -601,7 +643,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
info()<<"Read number of frames = "<<numFrames<<std::endl;
}
OFString numFramesStr;
if (fileformat.getDataset()->findAndGetOFString(DCM_NumberOfFrames, numFramesStr).good())
{
@ -614,7 +656,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
fileInfo.numSlices = numOfSlices;
info()<<"Read number of frames = "<<numOfSlices<<std::endl;
}
if (fileformat.getDataset()->findAndGetUint16(DCM_NumberOfSlices, numOfSlices).good())
{
fileInfo.numSlices = numOfSlices;
@ -636,7 +678,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
}
}
//info()<<"imagePositionPatient[2]="<<imagePositionPatient[2]<<std::endl;
fileInfo.matrix.setTrans(imagePositionPatient[0],imagePositionPatient[1],imagePositionPatient[2]);
for(int i=0; i<6; ++i)
@ -657,22 +699,22 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
osg::Vec3d dirY(imageOrientationPatient[3],imageOrientationPatient[4],imageOrientationPatient[5]);
osg::Vec3d dirZ = dirX ^ dirY;
dirZ.normalize();
dirX *= pixelSize_x;
dirY *= pixelSize_y;
fileInfo.matrix(0,0) = dirX[0];
fileInfo.matrix(1,0) = dirX[1];
fileInfo.matrix(2,0) = dirX[2];
fileInfo.matrix(0,1) = dirY[0];
fileInfo.matrix(1,1) = dirY[1];
fileInfo.matrix(2,1) = dirY[2];
fileInfo.matrix(0,2) = dirZ[0];
fileInfo.matrix(1,2) = dirZ[1];
fileInfo.matrix(2,2) = dirZ[2];
fileInfo.distance = dirZ * (osg::Vec3d(0.0,0.0,0.0)*fileInfo.matrix);
info()<<"dirX = "<<dirX<<std::endl;
@ -690,7 +732,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
}
if (orientationFileInfoMap.empty()) return 0;
typedef std::map<double, FileInfo> DistanceFileInfoMap;
typedef std::map<osg::Vec3d, DistanceFileInfoMap> OrientationFileInfoMap;
for(OrientationFileInfoMap::iterator itr = orientationFileInfoMap.begin();
@ -707,7 +749,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
info()<<" d = "<<fileInfo.distance<<" "<<fileInfo.filename<<std::endl;
}
}
DistanceFileInfoMap& dfim = orientationFileInfoMap.begin()->second;
if (dfim.empty()) return 0;
@ -721,11 +763,11 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
{
totalDistance = dfim.begin()->second.sliceThickness * double(dfim.begin()->second.numSlices);
}
info()<<"Total Distance including ends "<<totalDistance<<std::endl;
double averageThickness = totalNumSlices<=1 ? 1.0 : totalDistance / double(totalNumSlices-1);
info()<<"Average thickness "<<averageThickness<<std::endl;
for(DistanceFileInfoMap::iterator ditr = dfim.begin();
@ -733,7 +775,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
++ditr)
{
FileInfo& fileInfo = ditr->second;
std::auto_ptr<DicomImage> dcmImage(new DicomImage(fileInfo.filename.c_str()));
if (dcmImage.get())
{
@ -742,14 +784,14 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
// get the pixel data
const DiPixel* pixelData = dcmImage->getInterData();
if(!pixelData)
if(!pixelData)
{
warning()<<"Error: no data in DicomImage object."<<std::endl;
return ReadResult::ERROR_IN_READING_FILE;
}
osg::ref_ptr<osg::Image> imageAdapter = new osg::Image;
EP_Representation curr_pixelRep;
int curr_numPlanes;
GLenum curr_pixelFormat;
@ -758,15 +800,15 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
// create the new image
convertPixelTypes(pixelData,
curr_pixelRep, curr_numPlanes,
curr_dataType, curr_pixelFormat, curr_pixelSize);
curr_pixelRep, curr_numPlanes,
curr_dataType, curr_pixelFormat, curr_pixelSize);
imageAdapter->setImage(dcmImage->getWidth(), dcmImage->getHeight(), dcmImage->getFrameCount(),
curr_pixelFormat,
curr_pixelFormat,
curr_dataType,
(unsigned char*)(pixelData->getData()),
osg::Image::NO_DELETE);
curr_pixelFormat,
curr_pixelFormat,
curr_dataType,
(unsigned char*)(pixelData->getData()),
osg::Image::NO_DELETE);
if (!image)
{
pixelRep = curr_pixelRep;
@ -775,6 +817,8 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
pixelFormat = curr_pixelFormat;
pixelSize = curr_pixelSize;
osg::RefMatrix* matrix = details->getMatrix();
(*matrix)(0,0) = fileInfo.matrix(0,0);
(*matrix)(1,0) = fileInfo.matrix(1,0);
(*matrix)(2,0) = fileInfo.matrix(2,0);
@ -784,49 +828,50 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
(*matrix)(0,2) = fileInfo.matrix(0,2) * averageThickness;
(*matrix)(1,2) = fileInfo.matrix(1,2) * averageThickness;
(*matrix)(2,2) = fileInfo.matrix(2,2) * averageThickness;
details->setRescaleIntercept(fileInfo.rescaleIntercept);
details->setRescaleSlope(fileInfo.rescaleSlope);
image = new osg::Image;
image->setUserData(matrix.get());
image->setUserData(details.get());
image->setFileName(fileName.c_str());
image->allocateImage(dcmImage->getWidth(), dcmImage->getHeight(), totalNumSlices,
pixelFormat, dataType);
image->allocateImage(dcmImage->getWidth(), dcmImage->getHeight(), totalNumSlices,
pixelFormat, dataType);
matrix->preMult(osg::Matrix::scale(double(image->s()), double(image->t()), double(image->r())));
info()<<"Image dimensions = "<<image->s()<<", "<<image->t()<<", "<<image->r()<<" pixelFormat=0x"<<std::hex<<pixelFormat<<" dataType=0x"<<std::hex<<dataType<<std::dec<<std::endl;
}
else if (pixelData->getPlanes()>numPlanes ||
pixelData->getRepresentation()>pixelRep)
pixelData->getRepresentation()>pixelRep)
{
info()<<"Need to reallocated "<<image->s()<<", "<<image->t()<<", "<<image->r()<<std::endl;
// record the previous image settings to use when we copy back the content.
osg::ref_ptr<osg::Image> previous_image = image;
// create the new image
convertPixelTypes(pixelData,
pixelRep, numPlanes,
dataType, pixelFormat, pixelSize);
pixelRep, numPlanes,
dataType, pixelFormat, pixelSize);
image = new osg::Image;
image->setUserData(previous_image->getUserData());
image->setFileName(fileName.c_str());
image->allocateImage(dcmImage->getWidth(), dcmImage->getHeight(), totalNumSlices,
pixelFormat, dataType);
image->allocateImage(dcmImage->getWidth(), dcmImage->getHeight(), totalNumSlices,
pixelFormat, dataType);
osg::copyImage(previous_image.get(), 0,0,0, previous_image->s(), previous_image->t(), imageNum,
image.get(), 0, 0, 0,
false);
image.get(), 0, 0, 0,
false);
}
osg::copyImage(imageAdapter.get(), 0,0,0, imageAdapter->s(), imageAdapter->t(), imageAdapter->r(),
image.get(), 0, 0, imageNum,
false);
osg::copyImage(imageAdapter.get(), 0,0,0, imageAdapter->s(), imageAdapter->t(), imageAdapter->r(),
image.get(), 0, 0, imageNum,
false);
imageNum += dcmImage->getFrameCount();
}
else
@ -835,14 +880,14 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
}
}
}
if (!image)
{
return ReadResult::ERROR_IN_READING_FILE;
}
info()<<"Spacing = "<<*matrix<<std::endl;
info()<<"Spacing = "<<*(details->getMatrix())<<std::endl;
return image.get();
}
#endif
@ -850,6 +895,8 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
struct FileInfo
{
FileInfo():
rescaleIntercept(0.0),
rescaleSlope(1.0),
numX(0),
numY(0),
numSlices(1),
@ -859,6 +906,8 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
FileInfo(const FileInfo& rhs):
filename(rhs.filename),
matrix(rhs.matrix),
rescaleIntercept(rhs.rescaleIntercept),
rescaleSlope(rhs.rescaleSlope),
numX(rhs.numX),
numY(rhs.numY),
numSlices(rhs.numSlices),
@ -868,20 +917,24 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter
FileInfo& operator = (const FileInfo& rhs)
{
if (&rhs == this) return *this;
filename = rhs.filename;
matrix = rhs.matrix;
rescaleIntercept = rhs.rescaleIntercept;
rescaleSlope = rhs.rescaleSlope;
numX = rhs.numX;
numY = rhs.numY;
sliceThickness = rhs.sliceThickness;
numSlices = rhs.numSlices;
distance = rhs.distance;
return *this;
}
std::string filename;
osg::Matrixd matrix;
double rescaleIntercept;
double rescaleSlope;
unsigned int numX;
unsigned int numY;
unsigned int numSlices;

View File

@ -1,14 +1,14 @@
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include <osgVolume/Layer>
@ -21,6 +21,19 @@
using namespace osgVolume;
ImageDetails::ImageDetails():
_rescaleIntercept(0.0),
_rescaleSlope(1.0)
{
}
ImageDetails::ImageDetails(const ImageDetails& rhs,const osg::CopyOp& copyop):
_rescaleIntercept(rhs._rescaleIntercept),
_rescaleSlope(rhs._rescaleSlope),
_matrix(rhs._matrix)
{
}
Layer::Layer():
_minFilter(osg::Texture::LINEAR),
_magFilter(osg::Texture::LINEAR)
@ -42,10 +55,10 @@ Layer::~Layer()
osg::BoundingSphere Layer::computeBound() const
{
if (!getLocator()) return osg::BoundingSphere();
osg::Vec3d left, right;
getLocator()->computeLocalBounds(left, right);
//osg::notify(osg::NOTICE)<<"left = "<<left<<std::endl;
//osg::notify(osg::NOTICE)<<"right = "<<right<<std::endl;
@ -57,12 +70,12 @@ void Layer::addProperty(Property* property)
{
if (!property) return;
if (!_property)
if (!_property)
{
_property = property;
return;
}
CompositeProperty* cp = dynamic_cast<CompositeProperty*>(_property.get());
if (cp)
{
@ -82,12 +95,16 @@ void Layer::addProperty(Property* property)
// ImageLayer
//
ImageLayer::ImageLayer(osg::Image* image):
_rescaleIntercept(0.0),
_rescaleSlope(1.0),
_image(image)
{
}
ImageLayer::ImageLayer(const ImageLayer& imageLayer,const osg::CopyOp& copyop):
Layer(imageLayer, copyop),
_rescaleIntercept(imageLayer._rescaleIntercept),
_rescaleSlope(imageLayer._rescaleSlope),
_image(imageLayer._image)
{
}
@ -123,12 +140,16 @@ bool ImageLayer::computeMinMax(osg::Vec4& minValue, osg::Vec4& maxValue)
void ImageLayer::offsetAndScaleImage(const osg::Vec4& offset, const osg::Vec4& scale)
{
if (!_image) return;
osg::offsetAndScaleImage(_image.get(), offset, scale);
}
void ImageLayer::rescaleToZeroToOneRange()
{
osg::notify(osg::NOTICE)<<"ImageLayer::rescaleToZeroToOneRange()"<<std::endl;
osg::notify(osg::NOTICE)<<" _rescaleIntercept "<<_rescaleIntercept<<std::endl;
osg::notify(osg::NOTICE)<<" _rescaleSlope "<<_rescaleSlope<<std::endl;
osg::Vec4 minValue, maxValue;
if (computeMinMax(minValue, maxValue))
{
@ -141,10 +162,13 @@ void ImageLayer::rescaleToZeroToOneRange()
maxComponent = osg::maximum(maxComponent,maxValue[1]);
maxComponent = osg::maximum(maxComponent,maxValue[2]);
maxComponent = osg::maximum(maxComponent,maxValue[3]);
float scale = 0.99f/(maxComponent-minComponent);
float offset = -minComponent * scale;
osg::notify(osg::NOTICE)<<" scale "<<scale<<std::endl;
osg::notify(osg::NOTICE)<<" offset "<<offset<<std::endl;
offsetAndScaleImage(osg::Vec4(offset, offset, offset, offset),
osg::Vec4(scale, scale, scale, scale));
}
@ -204,7 +228,7 @@ bool CompositeLayer::requiresUpdateTraversal() const
{
if (itr->layer->requiresUpdateTraversal()) return true;
}
return false;
}
@ -216,7 +240,7 @@ void CompositeLayer::update(osg::NodeVisitor& nv)
{
itr->layer->update(nv);
}
}
@ -231,7 +255,7 @@ osg::Image* osgVolume::createNormalMapTexture(osg::Image* image_3d)
GLenum dataType = image_3d->getDataType();
unsigned int sourcePixelIncrement = 1;
unsigned int alphaOffset = 0;
unsigned int alphaOffset = 0;
switch(image_3d->getPixelFormat())
{
case(GL_ALPHA):
@ -269,7 +293,7 @@ osg::Image* osgVolume::createNormalMapTexture(osg::Image* image_3d)
{
if (dataType==GL_UNSIGNED_BYTE)
{
{
unsigned char* ptr = image_3d->data(1,t,r)+alphaOffset;
unsigned char* left = image_3d->data(0,t,r)+alphaOffset;
unsigned char* right = image_3d->data(2,t,r)+alphaOffset;
@ -284,8 +308,8 @@ osg::Image* osgVolume::createNormalMapTexture(osg::Image* image_3d)
{
osg::Vec3 grad((float)(*left)-(float)(*right),
(float)(*below)-(float)(*above),
(float)(*out) -(float)(*in));
(float)(*below)-(float)(*above),
(float)(*out) -(float)(*in));
grad.normalize();
@ -331,8 +355,8 @@ osg::Image* osgVolume::createNormalMapTexture(osg::Image* image_3d)
{
osg::Vec3 grad((float)(*left)-(float)(*right),
(float)(*below)-(float)(*above),
(float)(*out) -(float)(*in));
(float)(*below)-(float)(*above),
(float)(*out) -(float)(*in));
grad.normalize();
@ -348,7 +372,7 @@ osg::Image* osgVolume::createNormalMapTexture(osg::Image* image_3d)
grad.y() = osg::clampBetween((grad.y()+1.0f)*128.0f,0.0f,255.0f);
grad.z() = osg::clampBetween((grad.z()+1.0f)*128.0f,0.0f,255.0f);
}
*(destination++) = (unsigned char)(grad.x()); // scale and bias X.
*(destination++) = (unsigned char)(grad.y()); // scale and bias Y.
@ -381,8 +405,8 @@ osg::Image* osgVolume::createNormalMapTexture(osg::Image* image_3d)
{
osg::Vec3 grad((float)(*left)-(float)(*right),
(float)(*below)-(float)(*above),
(float)(*out) -(float)(*in));
(float)(*below)-(float)(*above),
(float)(*out) -(float)(*in));
grad.normalize();
@ -414,10 +438,10 @@ osg::Image* osgVolume::createNormalMapTexture(osg::Image* image_3d)
}
}
}
osg::notify(osg::INFO)<<"Created NormalMapTexture"<<std::endl;
return normalmap_3d.release();
}
@ -430,7 +454,7 @@ struct ApplyTransferFunctionOperator
ApplyTransferFunctionOperator(osg::TransferFunction1D* tf, unsigned char* data):
_tf(tf),
_data(data) {}
inline void luminance(float l) const
{
osg::Vec4 c = _tf->getColor(l);
@ -440,27 +464,27 @@ struct ApplyTransferFunctionOperator
*(_data++) = (unsigned char)(c[2]*255.0f + 0.5f);
*(_data++) = (unsigned char)(c[3]*255.0f + 0.5f);
}
inline void alpha(float a) const
{
luminance(a);
}
}
inline void luminance_alpha(float l,float a) const
{
{
luminance(l);
}
inline void rgb(float r,float g,float b) const
{
luminance((r+g+b)*0.3333333);
}
inline void rgba(float r,float g,float b,float a) const
{
luminance(a);
}
mutable osg::ref_ptr<osg::TransferFunction1D> _tf;
mutable unsigned char* _data;
};
@ -468,12 +492,12 @@ struct ApplyTransferFunctionOperator
osg::Image* osgVolume::applyTransferFunction(osg::Image* image, osg::TransferFunction1D* transferFunction)
{
osg::notify(osg::INFO)<<"Applying transfer function"<<std::endl;
osg::Image* output_image = new osg::Image;
output_image->allocateImage(image->s(),image->t(), image->r(), GL_RGBA, GL_UNSIGNED_BYTE);
ApplyTransferFunctionOperator op(transferFunction, output_image->data());
osg::readImage(image,op);
osg::readImage(image,op);
return output_image;
}