1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "gdcmStreamImageReader.h"
#include "gdcmImage.h"
#include "gdcmMediaStorage.h"
#include "gdcmImageHelper.h"
#include "gdcmRAWCodec.h"
#include "gdcmJPEGLSCodec.h"
#include <algorithm>
namespace gdcm
{
//see http://stackoverflow.com/questions/1448467/initializing-a-c-stdistringstream-from-an-in-memory-buffer/1449527#1449527
struct OneShotReadBuf : public std::streambuf
{
OneShotReadBuf(void* s, std::size_t n){
char* cast = (char*)s;
setg(cast, cast, cast+n);
}
};
StreamImageReader::StreamImageReader()
{
//set these values to be the opposite ends of possible,
//so that if the extent is not defined, read can fail properly.
mXMin = mYMin = mZMin = std::numeric_limits<uint16_t>::max();
mXMax = mYMax = mZMax = std::numeric_limits<uint16_t>::min();
}
StreamImageReader::~StreamImageReader()
{
}
/// One of either SetFileName or SetStream must be called prior
/// to any other functions.
void StreamImageReader::SetFileName(const char* inFileName)
{
mReader.SetFileName(inFileName);
}
void StreamImageReader::SetStream(std::istream& inStream)
{
mReader.SetStream(inStream);
}
std::vector<unsigned int> StreamImageReader::GetDimensionsValueForResolution( unsigned int res )
{
std::vector<unsigned int> extent(3);
File &file_t = mReader.GetFile();
DataSet &ds_t = file_t.GetDataSet();
const DataElement &seq = ds_t.GetDataElement( Tag(0x0048,0x0200) );
SmartPointer<SequenceOfItems> sqi = seq.GetValueAsSQ();
Item &itemL = sqi->GetItem(res);
DataSet &subds_L = itemL.GetNestedDataSet();
const DataElement &brrL = subds_L.GetDataElement( Tag(0x0048,0x0202) );
Element<VR::US,VM::VM2> elL1;
elL1.SetFromDataElement( brrL );
extent[0] = elL1.GetValue(0);
extent[1] = elL1.GetValue(1);
extent[2] = res;
return extent;
}
/// Defines an image extent for the Read function.
/// DICOM states that an image can have no more than 2^16 pixels per edge (as of 2009)
/// In this case, the pixel extents ignore the direction cosines entirely, and
/// assumes that the origin of the image is at location 0,0 (regardless of the definition
/// in space per the tags). So, if the first 100 pixels of the first row are to be read in,
/// this function should be called with DefinePixelExtent(0, 100, 0, 1), regardless
/// of pixel size or orientation.
void StreamImageReader::DefinePixelExtent(uint16_t inXMin, uint16_t inXMax,
uint16_t inYMin, uint16_t inYMax,
uint16_t inZMin, uint16_t inZMax){
mXMin = inXMin;
mYMin = inYMin;
mXMax = inXMax;
mYMax = inYMax;
mZMin = inZMin;
mZMax = inZMax;
}
/// Paying attention to the pixel format and so forth, define the proper buffer length for the user.
/// The return amount is in bytes.
/// If the return is 0, then that means that the pixel extent was not defined prior
uint32_t StreamImageReader::DefineProperBufferLength() const
{
if (mXMax < mXMin || mYMax < mYMin || mZMax < mZMin) return 0;
PixelFormat pixelInfo = ImageHelper::GetPixelFormatValue(mReader.GetFile());
//unsigned short samplesPerPixel = pixelInfo.GetSamplesPerPixel();
int bytesPerPixel = pixelInfo.GetPixelSize();
return (mYMax - mYMin)*(mXMax - mXMin)*(mZMax - mZMin)*bytesPerPixel;
}
/// Read the DICOM image. There are two reason for failure:
/// 1. The extent is not set
/// 2. The output buffer is not set
/// This method has been implemented to look similar to the metaimageio in itk
bool StreamImageReader::Read(char* inReadBuffer, const std::size_t& inBufferLength)
{
//need to have some kind of extent defined.
if (mXMin > mXMax || mYMin > mYMax || mZMin > mZMax)
{
return false; //for now
}
// OneShotReadBuf osrb(inReadBuffer, inBufferLength);
// std::ostream ostr(&osrb);
//put the codec interpretation here
// return ReadImageSubregionRAW(ostr);
//just do memcpys instead of doing this stream shenanigans
return ReadImageSubregionRAW(inReadBuffer, inBufferLength);
}
/** Read a particular subregion, using the stored mFileOffset as the beginning of the stream.
This class reads uncompressed data; other subclasses will reimplement this function for compression.
Assumes that the given buffer is the size in bytes returned from DefineProperBufferLength.
*/
bool StreamImageReader::ReadImageSubregionRAW(char* inReadBuffer, const std::size_t& inBufferLength)
{
//assumes that the file is organized in row-major format, with each row rastering across
assert( mFileOffset != -1 );
(void)inBufferLength;
int y, z;
std::streamoff theOffset;
//need to get the pixel size information
//should that come from the header?
//most likely that's a tag in the header
std::vector<unsigned int> extent = ImageHelper::GetDimensionsValue(mReader.GetFile());
PixelFormat pixelInfo = ImageHelper::GetPixelFormatValue(mReader.GetFile());
//unsigned short samplesPerPixel = pixelInfo.GetSamplesPerPixel();
int bytesPerPixel = pixelInfo.GetPixelSize();
int SubRowSize = mXMax - mXMin;
int SubColSize = mYMax - mYMin;
//set up the codec prior to resetting the file, just in case that affects the way that
//files are handled by the ImageHelper
const FileMetaInformation &header = mReader.GetFile().GetHeader();
const TransferSyntax &ts = header.GetDataSetTransferSyntax();
bool needbyteswap = (ts == TransferSyntax::ImplicitVRBigEndianPrivateGE);
RAWCodec theCodec;
if( !theCodec.CanDecode(ts) )
{
JPEGLSCodec theJpegLSCodec;
if (!theJpegLSCodec.CanDecode(ts))
{
gdcmDebugMacro( "Raw Codec cannot decode this file by streaming." );
return false;
}
else
{
//read in the entire file for jpegls
//right now, it needs to be read entirely off of disk first
//kind of a shame, but it's the way it is now
mReader.Read();
}
}
theCodec.SetNeedByteSwap( needbyteswap );
theCodec.SetDimensions(ImageHelper::GetDimensionsValue(mReader.GetFile()));
theCodec.SetPlanarConfiguration(
ImageHelper::GetPlanarConfigurationValue(mReader.GetFile()));
theCodec.SetPhotometricInterpretation(
ImageHelper::GetPhotometricInterpretationValue(mReader.GetFile()));
//how do I handle byte swapping here? where is it set?
//have to reset the stream to the proper position
//first, reopen the stream,then the loop should set the right position
//mReader.SetFileName(mReader.GetFileName().c_str());
std::istream* theStream = mReader.GetStreamPtr();//probably going to need a copy of this
//to ensure thread safety; if the stream ptr handler gets used simultaneously by different threads,
//that would be BAD
//tmpBuffer is for a single raster
char* tmpBuffer = new char[SubRowSize*bytesPerPixel];
char* tmpBuffer2 = new char[SubRowSize*bytesPerPixel];
try
{
for (z = mZMin; z < mZMax; ++z)
{
#if 0
theStream->seekg(std::ios::beg);
if(mFileOffset1 == 0)
{
mFileOffset1 = mFileOffset;
for(int j = 1; j<=z; j++)
{
std::vector<unsigned int> extent = GetDimensionsValueForResolution(j);
mFileOffset1 = mFileOffset1 + (int)((extent[1])*(extent[0])*bytesPerPixel);
mFileOffset1 = mFileOffset1 + 4*sizeof(uint16_t);
}
}
else
{
mFileOffset1 = mFileOffset;
}
std::vector<unsigned int> extent = GetDimensionsValueForResolution(z+1);
#endif
for (y = mYMin; y < mYMax; ++y)
{
#if 0
theOffset = mFileOffset1 + (y*(int)(extent[0]) + mXMin)*bytesPerPixel;
#else
theStream->seekg(std::ios::beg);
theOffset = mFileOffset + (z * (int)(extent[1]*extent[0]) + y*(int)extent[0] + mXMin)*bytesPerPixel;
#endif
theStream->seekg(theOffset);
theStream->read(tmpBuffer, SubRowSize*bytesPerPixel);
//now, convert that buffer.
if (!theCodec.DecodeBytes(tmpBuffer, SubRowSize*bytesPerPixel,
tmpBuffer2, SubRowSize*bytesPerPixel))
{
delete [] tmpBuffer;
delete [] tmpBuffer2;
return false;
}
//this next line may require a bit of finagling...
//std::copy(tmpBuffer2, &(tmpBuffer2[SubRowSize*bytesPerPixel]), std::ostream_iterator<char>(os));
//make sure to have a test that will test different x, y, and z mins and maxes
memcpy(&(inReadBuffer[((z-mZMin)*SubRowSize*SubColSize +
(y-mYMin)*SubRowSize)// + mXMin)//shouldn't need mXMin
*bytesPerPixel]), tmpBuffer2, SubRowSize*bytesPerPixel);
}
#if 0
if((mYMax == extent[1]) && (mXMax == extent[0]))
{
mFileOffset1 = mFileOffset1 + (int)((extent[1])*(extent[0])*bytesPerPixel) + 4*sizeof(uint16_t);
}
#endif
}
#if 0
mFileOffset = mFileOffset1;
#endif
}
catch (std::exception & ex)
{
(void)ex;
gdcmWarningMacro( "Failed to read with ex:" << ex.what() );
delete [] tmpBuffer;
delete [] tmpBuffer2;
return false;
}
catch (...)
{
gdcmWarningMacro( "Failed to read with unknown error." );
delete [] tmpBuffer;
delete [] tmpBuffer2;
return false;
}
delete [] tmpBuffer;
delete [] tmpBuffer2;
return true;
}
/** This class reads via the jpegls codec.
Due to limitations in that codec, the entire file must be read into memory before a subregion
can be decoded.
*/
bool StreamImageReader::ReadImageSubregionJpegLS(char* inReadBuffer, const std::size_t& inBufferLength) {
//assumes that the file is organized in row-major format, with each row rastering across
//don't need to get all the other stuff (ie, the file offset) since we have to read it all in anyway
//set up the codec prior to resetting the file, just in case that affects the way that
//files are handled by the ImageHelper
const FileMetaInformation &header = mReader.GetFile().GetHeader();
const TransferSyntax &ts = header.GetDataSetTransferSyntax();
bool needbyteswap = (ts == TransferSyntax::ImplicitVRBigEndianPrivateGE);
JPEGLSCodec theCodec;
if (!theCodec.CanDecode(ts))
{
gdcmDebugMacro( "JpegLS cannot read this." );
return false;
}
//read in the entire file for jpegls
//right now, it needs to be read entirely off of disk first
//kind of a shame, but it's the way it is now
mReader.Read();
theCodec.SetNeedByteSwap( needbyteswap );
theCodec.SetDimensions(ImageHelper::GetDimensionsValue(mReader.GetFile()));
theCodec.SetPlanarConfiguration(ImageHelper::GetPlanarConfigurationValue(mReader.GetFile()));
theCodec.SetPhotometricInterpretation(ImageHelper::GetPhotometricInterpretationValue(mReader.GetFile()));
try {
DataSet ds = mReader.GetFile().GetDataSet();
Tag thePixelDataTag(0x7fe0, 0x0010);
DataElement de = ds.GetDataElement(thePixelDataTag);
theCodec.Decode(de, inReadBuffer, inBufferLength, mXMin, mXMax, mYMin, mYMax, mZMin, mZMax);
}
catch (std::exception & ex){
(void)ex;
gdcmWarningMacro( "Failed to read with ex:" << ex.what() );
return false;
}
catch (...){
gdcmWarningMacro( "Failed to read with unknown error." );
return false;
}
return true;
}
/// Set the spacing and dimension information for the set filename.
/// returns false if the file is not initialized or not an image,
/// with the pixel 0x7fe0, 0x0010 tag.
bool StreamImageReader::ReadImageInformation()
{
//read up to the point in the stream where the pixel information tag is
//store that location and keep the rest of the data as the header information dataset
std::set<Tag> theSkipTags;
Tag thePixelDataTag(0x7fe0, 0x0010);//must be LESS than the pixel information tag, 0x7fe0,0x0010
//otherwise, it'll read that tag as well.
//make a reader object in readimageinformation
//call read up to tag
//then create data structures from that dataset that's been read-up-to
theSkipTags.insert(thePixelDataTag);
try
{
//ok, need to read up until I know what kind of endianness i'm dealing with?
if (!mReader.ReadUpToTag(thePixelDataTag, theSkipTags))
{
gdcmWarningMacro("Failed to read tags in the gdcm stream image reader.");
return false;
}
#if 0
std::streampos shift = 4*sizeof(uint16_t)+2*sizeof(uint32_t);
mFileOffset = mReader.GetStreamPtr()->tellg()+ shift;
mFileOffset1 = 0;
#else
mFileOffset = mReader.GetStreamPtr()->tellg();
#endif
}
catch(std::exception & ex)
{
(void)ex;
gdcmWarningMacro( "Failed to read with ex:" << ex.what() );
return false;
}
catch(...)
{
gdcmWarningMacro( "Failed to read with unknown error" );
return false;
}
// eg. ELSCINT1_PMSCT_RLE1.dcm
if( mFileOffset == -1 ) return false;
// postcondition
assert( mFileOffset != -1 );
const File &file_t = mReader.GetFile();
const DataSet &ds_t = file_t.GetDataSet();
MediaStorage ms;
ms.SetFromFile(file_t);
if( ms == MediaStorage::VLWholeSlideMicroscopyImageStorage )
{
if( !ds_t.FindDataElement( Tag(0x0048,0x0200) ) )
{
gdcmWarningMacro( "error occured in WSI File read" );
return false;
}
DataElement seq = ds_t.GetDataElement( Tag(0x0048,0x0200) );
SmartPointer<SequenceOfItems> sqi = seq.GetValueAsSQ();
SequenceOfItems::SizeType s = sqi->GetNumberOfItems();
Item itemL = sqi->GetItem(1);
DataSet &subds_L = itemL.GetNestedDataSet();
if( !subds_L.FindDataElement( Tag(0x0008,0x1160) ) )
{
gdcmWarningMacro( "Error occured during WSI File Read" );
return false;
}
DataElement rfnL = subds_L.GetDataElement( Tag(0x0008,0x1160) );
Element<VR::IS,VM::VM1> elL;
elL.SetFromDataElement( rfnL );
if( !subds_L.FindDataElement( Tag(0x0048,0x0202) ) )
{
gdcmWarningMacro( "Error During WSI File Read" );
return false;
}
DataElement brrL = subds_L.GetDataElement( Tag(0x0048,0x0202) );
Element<VR::US,VM::VM2> elL1;
elL1.SetFromDataElement( brrL );
Item itemH = sqi->GetItem(s);
DataSet &subds_H = itemH.GetNestedDataSet();
if( !subds_H.FindDataElement( Tag(0x0008,0x1160) ) )
{
gdcmWarningMacro( "Error occured during WSI File Read" );
return false;
}
DataElement rfnH = subds_H.GetDataElement( Tag(0x0008,0x1160) );
Element<VR::IS,VM::VM1> elH;
elH.SetFromDataElement( rfnH );
if( !subds_H.FindDataElement( Tag(0x0048,0x0202) ) )
{
gdcmWarningMacro( "Error During WSI File Read" );
return false;
}
DataElement brrH = subds_H.GetDataElement( Tag(0x0048,0x0202) );
Element<VR::US,VM::VM2> elH1;
elH1.SetFromDataElement( brrH );
}
return true;
}
bool StreamImageReader::CanReadImage() const
{
//this is the check to ensure that ReadImageInformation was read in properly
if (mFileOffset == -1)
{
return false;
}
const FileMetaInformation &header = mReader.GetFile().GetHeader();
const TransferSyntax &ts = header.GetDataSetTransferSyntax();
//bool needbyteswap = (ts == TransferSyntax::ImplicitVRBigEndianPrivateGE);
RAWCodec theCodec;
bool canDecodeRaw = theCodec.CanDecode(ts);
if (!canDecodeRaw) return false;
std::vector<unsigned int> extent = ImageHelper::GetDimensionsValue(mReader.GetFile());
if (extent.empty()) return false; //should not happen with current GetDimensionsValue implementation
//but just in case...
if (extent[0] == 0 || extent[1] == 0)
return false;
return true;
}
/// Returns the dataset read by ReadImageInformation
/// Couple this with the ImageHelper to get statistics about the image,
/// like pixel extent, to be able to initialize buffers for reading
File const &StreamImageReader::GetFile() const
{
if (mFileOffset > 0)
{
/// mFileOffset1 = 0;
return mReader.GetFile();
}
else
{
assert(0);
return mReader.GetFile();
}
}
} // end namespace gdcm
|