GDCM: ExtractImageRegion.py

GDCM 3.2.8

ExtractImageRegion.py
1
14
15"""
16
17 This small code shows how to use the gdcm.ImageRegionReader API
18 In this example we are taking each frame by frame and dump them to
19 /tmp/frame.raw.
20
21 Usage:
22 $ ExtractImageRegion.py input.dcm
23
24 Example:
25 $ ExtractImageRegion.py gdcmData/012345.002.050.dcm
26 $ md5sum /tmp/frame.raw
27 d594a5e2fde12f32b6633ca859b4d4a6 /tmp/frame.raw
28 $ gdcminfo --md5sum gdcmData/012345.002.050.dcm
29 [...]
30 md5sum: d594a5e2fde12f32b6633ca859b4d4a6
31"""
32
33import gdcm
34
35if __name__ == "__main__":
36 import sys
37 filename = sys.argv[1]
38
39 file_size = gdcm.System.FileSize(filename);
40
41 # instantiate the reader:
42 reader = gdcm.ImageRegionReader();
43 reader.SetFileName( filename );
44
45 # pull DICOM info:
46 if not reader.ReadInformation():
47 sys.exit(1)
48
49 # store current offset:
50 cur_pos = reader.GetStreamCurrentPosition();
51
52 remaining = file_size - cur_pos;
53
54 print("Remaining bytes to read (Pixel Data): %d" % remaining );
55
56 # Get file infos
57 f = reader.GetFile();
58
59 # get some info about image
60 dims = gdcm.ImageHelper.GetDimensionsValue(f);
61 print(dims)
62 pf = gdcm.ImageHelper.GetPixelFormatValue (f);
63 pixelsize = pf.GetPixelSize();
64 pi = gdcm.ImageHelper.GetPhotometricInterpretationValue(f);
65 print( pi );
66
67 # buffer to get the pixels
68 buffer = bytearray( dims[0] * dims[1] * pixelsize )
69
70 # define a simple box region.
71 box = gdcm.BoxRegion();
72 for z in range(0, dims[2]):
73 # Define that I want the image 0, full size (dimx x dimy pixels)
74 # and do that for each z:
75 box.SetDomain(0, dims[0] - 1, 0, dims[1] - 1, z, z);
76 #print( box.toString() );
77 reader.SetRegion( box );
78
79 # reader will try to load the uncompressed image region into buffer.
80 # the call returns an error when buffer.Length is too small. For instance
81 # one can call:
82 # uint buf_len = reader.ComputeBufferLength(); // take into account pixel size
83 # to get the exact size of minimum buffer
84 if reader.ReadIntoBuffer(buffer):
85 open('/tmp/frame.raw', 'wb').write(buffer)
86 else:
87 #throw new Exception("can't read pixels error");
88 sys.exit(1)
gdcm::BoxRegion
Class for manipulation box region.
Definition gdcmBoxRegion.h:31
gdcm::ImageHelper::GetPhotometricInterpretationValue
static PhotometricInterpretation GetPhotometricInterpretationValue(File const &f)
gdcm::ImageHelper::GetDimensionsValue
static std::vector< unsigned int > GetDimensionsValue(const File &f)
gdcm::ImageRegionReader
ImageRegionReader.
Definition gdcmImageRegionReader.h:35
gdcm::System::FileSize
static size_t FileSize(const char *filename)