#include "gdcmReader.h"
#include "gdcmPrivateTag.h"
#include "gdcmAttribute.h"
#include "gdcmImageWriter.h"
void delta_decode(const char *inbuffer, size_t length, std::vector<unsigned short> &output)
{
std::vector<char> temp;
for(size_t i = 0; i < length; ++i)
{
if( inbuffer[i] == (char)0xa5 )
{
int repeat = (unsigned char)inbuffer[i+1] + 1;
char value = inbuffer[i+2];
while(repeat)
{
temp.push_back( value );
--repeat;
}
i+=2;
}
else
{
temp.push_back( inbuffer[i] );
}
}
unsigned short delta = 0;
for(size_t i = 0; i < temp.size(); ++i)
{
if( temp[i] == 0x5a )
{
unsigned char v1 = (unsigned char)temp[i+1];
unsigned char v2 = (unsigned char)temp[i+2];
int value = v2 * 256 + v1;
output.push_back( value );
delta = value;
i+=2;
}
else
{
int value = temp[i] + delta;
output.push_back( value );
delta = value;
}
}
if ( output.size() % 2 )
{
output.resize( output.size() - 1 );
}
std::cout << length << " -> " << output.size() * 2 << std::endl;
}
int main(int argc, char *argv [])
{
if( argc < 2 ) return 1;
const char *filename = argv[1];
gdcm::Reader reader;
reader.SetFileName( filename );
if( !reader.Read() )
{
std::cerr << "Failed to read: " << filename << std::endl;
return 1;
}
const gdcm::DataSet& ds = reader.GetFile().GetDataSet();
const gdcm::PrivateTag tcompressiontype(0x07a1,0x0011,"ELSCINT1");
if( !ds.FindDataElement( tcompressiontype ) ) return 1;
const gdcm::DataElement& compressiontype = ds.GetDataElement( tcompressiontype );
if ( compressiontype.IsEmpty() ) return 1;
const gdcm::ByteValue * bv = compressiontype.GetByteValue();
std::string comp = "PMSCT_RLE1";
if( strncmp( bv->GetPointer(), comp.c_str(), comp.size() ) != 0 ) return 1;
const gdcm::PrivateTag tcompressedpixeldata(0x07a1,0x000a,"ELSCINT1");
if( !ds.FindDataElement( tcompressedpixeldata) ) return 1;
const gdcm::DataElement& compressionpixeldata = ds.GetDataElement( tcompressedpixeldata);
if ( compressionpixeldata.IsEmpty() ) return 1;
const gdcm::ByteValue * bv2 = compressionpixeldata.GetByteValue();
std::vector<unsigned short> buffer;
delta_decode(bv2->GetPointer(), bv2->GetLength(), buffer);
gdcm::DataElement pixeldata( gdcm::Tag(0x7fe0,0x0010) );
pixeldata.SetVR( gdcm::VR::OW );
pixeldata.SetByteValue( (char*)&buffer[0], buffer.size() * sizeof( unsigned short ) );
reader.GetFile().GetDataSet().Replace( pixeldata );
gdcm::Writer writer;
writer.SetFile( reader.GetFile() );
writer.GetFile().GetDataSet().Remove( compressionpixeldata.GetTag() );
std::string outfilename;
if (argc > 2)
outfilename = argv[2];
else
outfilename = "outrle.dcm";
writer.SetFileName( outfilename.c_str() );
if( !writer.Write() )
{
std::cerr << "Failed to write" << std::endl;
return 1;
}
std::cout << "success !" << std::endl;
return 0;
}