示例#1
0
# read
r = gdcm.Reader()
r.SetFileName(filename)
if not r.Read():
    print "not valid"
    sys.exit(1)

file = r.GetFile()
dataset = file.GetDataSet()

ano = gdcm.Anonymizer()
ano.SetFile(file)

tags = [
    gdcm.Tag(0x0018, 0x1164),
    gdcm.Tag(0x0018, 0x0088),
    gdcm.Tag(0x0018, 0x0050),
    gdcm.Tag(0x0028, 0x0030),
]

for tag in tags:
    print tag
    if dataset.FindDataElement(tag):
        pixelspacing = dataset.GetDataElement(tag)
        #print pixelspacing
        bv = pixelspacing.GetByteValue()
        str = bv.GetBuffer()
        #print bv.GetLength()
        #print len(str)
        new_str = str.replace(",", ".")
示例#2
0
import gdcm
import sys

#filename = "/home/mmalaterre/Creatis/gdcmDataExtra/gdcmNonImageData/audio_from_rafael_sanguinetti.dcm"
filename = sys.argv[1]
print filename

r = gdcm.Reader()
r.SetFileName(filename)
if not r.Read():
    sys.exit(1)

ds = r.GetFile().GetDataSet()

waveformtag = gdcm.Tag(0x5400, 0x0100)
waveformsq = ds.GetDataElement(waveformtag)
#print waveformsq

#print dir(waveformsq)

items = waveformsq.GetSequenceOfItems()

if not items.GetNumberOfItems():
    sys.exit(1)

item = items.GetItem(1)
#print item

waveformds = item.GetNestedDataSet()
#print waveformds
示例#3
0
    def run(self):
        grouper = self.grouper
        reader = gdcm.ImageReader()
        if _has_win32api:
            try:
                reader.SetFileName(utils.encode(win32api.GetShortPathName(self.filepath),
                                                const.FS_ENCODE))
            except TypeError:
                reader.SetFileName(win32api.GetShortPathName(self.filepath))
        else:
            try:
                reader.SetFileName(utils.encode(self.filepath, const.FS_ENCODE))
            except TypeError:
                reader.SetFileName(self.filepath)
        if (reader.Read()):
            file = reader.GetFile()
            # Retrieve data set
            dataSet = file.GetDataSet()
            # Retrieve header
            header = file.GetHeader()
            stf = gdcm.StringFilter()
            stf.SetFile(file)

            field_dict = {}
            data_dict = {}

            tag = gdcm.Tag(0x0008, 0x0005)
            ds = reader.GetFile().GetDataSet()
            image_helper = gdcm.ImageHelper()
            data_dict['spacing'] = image_helper.GetSpacingValue(reader.GetFile())
            if ds.FindDataElement(tag):
                encoding_value = str(ds.GetDataElement(tag).GetValue()).split('\\')[0]
                
                if encoding_value.startswith("Loaded"):
                    encoding = "ISO_IR 100"
                else:
                    try:
                        encoding = const.DICOM_ENCODING_TO_PYTHON[encoding_value]
                    except KeyError:
                        encoding = 'ISO_IR 100'
            else:
                encoding = "ISO_IR 100"

            # Iterate through the Header
            iterator = header.GetDES().begin()
            while (not iterator.equal(header.GetDES().end())):
                dataElement = iterator.next()
                if not dataElement.IsUndefinedLength():
                    tag = dataElement.GetTag()
                    data = stf.ToStringPair(tag)
                    stag = tag.PrintAsPipeSeparatedString()

                    group = str(tag.GetGroup())
                    field = str(tag.GetElement())

                    tag_labels[stag] = data[0]

                    if not group in data_dict.keys():
                        data_dict[group] = {}

                    if not(utils.VerifyInvalidPListCharacter(data[1])):
                        data_dict[group][field] = utils.decode(data[1], encoding)
                    else:
                        data_dict[group][field] = "Invalid Character"

            # Iterate through the Data set
            iterator = dataSet.GetDES().begin()
            while (not iterator.equal(dataSet.GetDES().end())):
                dataElement = iterator.next()
                if not dataElement.IsUndefinedLength():
                    tag = dataElement.GetTag()
                    #  if (tag.GetGroup() == 0x0009 and tag.GetElement() == 0x10e3) \
                            #  or (tag.GetGroup() == 0x0043 and tag.GetElement() == 0x1027):
                        #  continue
                    data = stf.ToStringPair(tag)
                    stag = tag.PrintAsPipeSeparatedString()

                    group = str(tag.GetGroup())
                    field = str(tag.GetElement())

                    tag_labels[stag] = data[0]

                    if not group in data_dict.keys():
                        data_dict[group] = {}

                    if not(utils.VerifyInvalidPListCharacter(data[1])):
                        data_dict[group][field] = utils.decode(data[1], encoding, 'replace')
                    else:
                        data_dict[group][field] = "Invalid Character"


            # -------------- To Create DICOM Thumbnail -----------


            try:
                data = data_dict[str(0x028)][str(0x1050)]
                level = [float(value) for value in data.split('\\')][0]
                data = data_dict[str(0x028)][str(0x1051)]
                window =  [float(value) for value in data.split('\\')][0]
            except(KeyError, ValueError):
                level = None
                window = None

            img = reader.GetImage()
            thumbnail_path = imagedata_utils.create_dicom_thumbnails(img, window, level)

            #------ Verify the orientation --------------------------------

            direc_cosines = img.GetDirectionCosines()
            orientation = gdcm.Orientation()
            try:
                _type = orientation.GetType(tuple(direc_cosines))
            except TypeError:
                _type = orientation.GetType(direc_cosines)
            label = orientation.GetLabel(_type)

 
            # ----------   Refactory --------------------------------------
            data_dict['invesalius'] = {'orientation_label' : label}

            # -------------------------------------------------------------
            dict_file[self.filepath] = data_dict
            
            #----------  Verify is DICOMDir -------------------------------
            is_dicom_dir = 1
            try: 
                if (data_dict[str(0x002)][str(0x002)] != "1.2.840.10008.1.3.10"): #DICOMDIR
                    is_dicom_dir = 0
            except(KeyError):
                    is_dicom_dir = 0
                                        
            if not(is_dicom_dir):
                parser = dicom.Parser()
                parser.SetDataImage(dict_file[self.filepath], self.filepath, thumbnail_path)
                
                dcm = dicom.Dicom()
                #self.l.acquire()
                dcm.SetParser(parser)
                grouper.AddFile(dcm)
示例#4
0
    def __init__(self,
                 server="",
                 port=1040,
                 aetitle="DICOMFS_AE",
                 caller="DICOMFS_CALLER",
                 localport=11112):
        self.server = str(server)
        self.remoteport = int(port)
        self.localport = int(localport)
        self.aetitle = str(aetitle)
        self.caller = str(caller)

        self.tag_StudyUID = gdcm.Tag(0x20, 0x0d)
        self.tag_StudyDate = gdcm.Tag(0x08, 0x20)
        self.tag_StudyTime = gdcm.Tag(0x08, 0x30)
        self.tag_StudyID = gdcm.Tag(0x20, 0x10)
        self.tag_StudyDescription = gdcm.Tag(0x08, 0x1030)

        self.tag_Study = [
            self.tag_StudyDate, self.tag_StudyTime, self.tag_StudyID,
            self.tag_StudyDescription
        ]

        self.tag_SeriesUID = gdcm.Tag(0x20, 0x0e)
        self.tag_SeriesDate = gdcm.Tag(0x08, 0x21)
        self.tag_SeriesTime = gdcm.Tag(0x08, 0x31)
        self.tag_SeriesDescription = gdcm.Tag(0x0008, 0x103e)
        self.tag_SeriesModality = gdcm.Tag(0x0008, 0x0060)  # modality
        self.tag_Series = [
            self.tag_SeriesDate, self.tag_SeriesDescription,
            self.tag_SeriesModality
        ]

        self.tag_infmodel = gdcm.Tag(0x0008, 0x0052)
        self.tag_SOP_UID = gdcm.Tag(0x08, 0x0018)

        self.tag_PatientName = gdcm.Tag(0x10, 0x10)
        self.tag_PatientID = gdcm.Tag(0x10, 0x20)
        self.tag_Patient = [self.tag_PatientName]
示例#5
0
#  See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details.
#
#     This software is distributed WITHOUT ANY WARRANTY; without even
#     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
#     PURPOSE.  See the above copyright notice for more information.
#
############################################################################

import gdcm
import sys, os

if __name__ == "__main__":
    directory = sys.argv[1]

    # Define the set of tags we are interested in
    t1 = gdcm.Tag(0x8, 0x8)
    t2 = gdcm.Tag(0x10, 0x10)

    # Iterate over directory
    d = gdcm.Directory()
    nfiles = d.Load(directory)
    if (nfiles == 0): sys.exit(1)
    # System.Console.WriteLine( "Files:\n" + d.toString() );

    filenames = d.GetFilenames()

    #  Get rid of any Warning while parsing the DICOM files
    gdcm.Trace.WarningOff()

    # instanciate Scanner:
    s = gdcm.Scanner()
示例#6
0
    filename = sys.argv[1]

    # Instanciate a gdcm.Reader
    # This is the main class to handle any type of DICOM object
    # You should check for gdcm.ImageReader for reading specifically DICOM Image file
    r = gdcm.Reader()
    r.SetFileName(filename)
    # If the reader fails to read the file, we should stop !
    if not r.Read():
        print "Not a valid DICOM file"
        sys.exit(1)

    # Get the DICOM File structure
    file = r.GetFile()

    # Get the DataSet part of the file
    dataset = file.GetDataSet()

    # Ok let's print it !
    print dataset

    # Use StringFilter to print a particular Tag:
    sf = gdcm.StringFilter()
    sf.SetFile(r.GetFile())

    # Check if Attribute exist
    print dataset.FindDataElement(gdcm.Tag(0x0028, 0x0010))

    # Let's print it as string pair:
    print sf.ToStringPair(gdcm.Tag(0x0028, 0x0010))
示例#7
0
def _create_gdcm_image(src: bytes, **kwargs: Any) -> "gdcm.Image":
    """Return a gdcm.Image from the `src`.

    Parameters
    ----------
    src : bytes
        The raw image frame data to be encoded.
    **kwargs
        Required parameters:

        * `rows`: int
        * `columns`: int
        * `samples_per_pixel`: int
        * `number_of_frames`: int
        * `bits_allocated`: int
        * `bits_stored`: int
        * `pixel_representation`: int
        * `photometric_interpretation`: str

    Returns
    -------
    gdcm.Image
        An Image containing the `src` as a single uncompressed frame.
    """
    rows = kwargs['rows']
    columns = kwargs['columns']
    samples_per_pixel = kwargs['samples_per_pixel']
    number_of_frames = kwargs['number_of_frames']
    pixel_representation = kwargs['pixel_representation']
    bits_allocated = kwargs['bits_allocated']
    bits_stored = kwargs['bits_stored']
    photometric_interpretation = kwargs['photometric_interpretation']

    pi = gdcm.PhotometricInterpretation.GetPIType(photometric_interpretation)

    # GDCM's null photometric interpretation gets used for invalid values
    if pi == gdcm.PhotometricInterpretation.PI_END:
        raise ValueError(
            "An error occurred with the 'gdcm' plugin: invalid photometric "
            f"interpretation '{photometric_interpretation}'")

    # `src` uses little-endian byte ordering
    ts = gdcm.TransferSyntax.ImplicitVRLittleEndian

    image = gdcm.Image()
    image.SetNumberOfDimensions(2)
    image.SetDimensions((columns, rows, 1))
    image.SetPhotometricInterpretation(gdcm.PhotometricInterpretation(pi))
    image.SetTransferSyntax(gdcm.TransferSyntax(ts))

    pixel_format = gdcm.PixelFormat(samples_per_pixel, bits_allocated,
                                    bits_stored, bits_stored - 1,
                                    pixel_representation)
    image.SetPixelFormat(pixel_format)
    if samples_per_pixel > 1:
        # Default `src` is planar configuration 0 (i.e. R1 G1 B1 R2 G2 B2)
        image.SetPlanarConfiguration(0)

    # Add the Pixel Data element and set the value to `src`
    elem = gdcm.DataElement(gdcm.Tag(0x7FE0, 0x0010))
    elem.SetByteStringValue(src)
    image.SetDataElement(elem)

    return cast("gdcm.Image", image)
示例#8
0
    def run(self):

        grouper = self.grouper
        reader = gdcm.ImageReader()
        reader.SetFileName(self.filepath)
        if (reader.Read()):
            file = reader.GetFile()

            # Retrieve data set
            dataSet = file.GetDataSet()

            # Retrieve header
            header = file.GetHeader()
            stf = gdcm.StringFilter()

            field_dict = {}
            data_dict = {}

            tag = gdcm.Tag(0x0008, 0x0005)
            ds = reader.GetFile().GetDataSet()
            if ds.FindDataElement(tag):
                encoding_value = str(
                    ds.GetDataElement(tag).GetValue()).split('\\')[0]

                if encoding_value.startswith("Loaded"):
                    encoding = "ISO_IR 100"
                else:
                    try:
                        encoding = const.DICOM_ENCODING_TO_PYTHON[
                            encoding_value]
                    except KeyError:
                        encoding = 'ISO_IR 100'
            else:
                encoding = "ISO_IR 100"

            # Iterate through the Header
            iterator = header.GetDES().begin()
            while (not iterator.equal(header.GetDES().end())):
                dataElement = iterator.next()
                stf.SetFile(file)
                tag = dataElement.GetTag()
                data = stf.ToStringPair(tag)
                stag = tag.PrintAsPipeSeparatedString()

                group = str(tag.GetGroup())
                field = str(tag.GetElement())

                tag_labels[stag] = data[0]

                if not group in data_dict.keys():
                    data_dict[group] = {}

                if not (utils.VerifyInvalidPListCharacter(data[1])):
                    data_dict[group][field] = data[1].decode(encoding)
                else:
                    data_dict[group][field] = "Invalid Character"

            # Iterate through the Data set
            iterator = dataSet.GetDES().begin()
            while (not iterator.equal(dataSet.GetDES().end())):
                dataElement = iterator.next()

                stf.SetFile(file)
                tag = dataElement.GetTag()
                data = stf.ToStringPair(tag)
                stag = tag.PrintAsPipeSeparatedString()

                group = str(tag.GetGroup())
                field = str(tag.GetElement())

                tag_labels[stag] = data[0]

                if not group in data_dict.keys():
                    data_dict[group] = {}

                if not (utils.VerifyInvalidPListCharacter(data[1])):
                    data_dict[group][field] = data[1].decode(
                        encoding, 'replace')
                else:
                    data_dict[group][field] = "Invalid Character"

            # -------------- To Create DICOM Thumbnail -----------
            rvtk = vtkgdcm.vtkGDCMImageReader()
            rvtk.SetFileName(self.filepath)
            rvtk.Update()

            try:
                data = data_dict[str(0x028)][str(0x1050)]
                level = [float(value) for value in data.split('\\')][0]
                data = data_dict[str(0x028)][str(0x1051)]
                window = [float(value) for value in data.split('\\')][0]
            except (KeyError):
                level = 300.0
                window = 2000.0

            colorer = vtk.vtkImageMapToWindowLevelColors()
            colorer.SetInputConnection(rvtk.GetOutputPort())
            colorer.SetWindow(float(window))
            colorer.SetLevel(float(level))
            colorer.SetOutputFormatToRGB()
            colorer.Update()

            resample = vtk.vtkImageResample()
            resample.SetInputConnection(colorer.GetOutputPort())
            resample.SetAxisMagnificationFactor(0, 0.25)
            resample.SetAxisMagnificationFactor(1, 0.25)
            resample.SetAxisMagnificationFactor(2, 1)
            resample.Update()

            thumbnail_path = tempfile.mktemp()

            write_png = vtk.vtkPNGWriter()
            write_png.SetInputConnection(resample.GetOutputPort())
            write_png.SetFileName(thumbnail_path)
            write_png.Write()

            #------ Verify the orientation --------------------------------

            img = reader.GetImage()
            direc_cosines = img.GetDirectionCosines()
            orientation = gdcm.Orientation()
            try:
                type = orientation.GetType(tuple(direc_cosines))
            except TypeError:
                type = orientation.GetType(direc_cosines)
            label = orientation.GetLabel(type)

            # ----------   Refactory --------------------------------------
            data_dict['invesalius'] = {'orientation_label': label}

            # -------------------------------------------------------------
            dict_file[self.filepath] = data_dict

            #----------  Verify is DICOMDir -------------------------------
            is_dicom_dir = 1
            try:
                if (data_dict[str(0x002)][str(0x002)] !=
                        "1.2.840.10008.1.3.10"):  #DICOMDIR
                    is_dicom_dir = 0
            except (KeyError):
                is_dicom_dir = 0

            if not (is_dicom_dir):
                parser = dicom.Parser()
                parser.SetDataImage(dict_file[self.filepath], self.filepath,
                                    thumbnail_path)

                dcm = dicom.Dicom()
                #self.l.acquire()
                dcm.SetParser(parser)
                grouper.AddFile(dcm)
示例#9
0
    print ir.GetDimension(1)
    print "Dims:", dims

    #  Just for fun:
    dircos = ir.GetDirectionCosines()
    t = gdcm.Orientation.GetType(dircos)
    l = gdcm.Orientation.GetLabel(t)
    print "Orientation label:", l

    image.SetDimension(0, ir.GetDimension(0))
    image.SetDimension(1, ir.GetDimension(1))

    pixeltype = ir.GetPixelFormat()
    image.SetPixelFormat(pixeltype)

    pi = ir.GetPhotometricInterpretation()
    image.SetPhotometricInterpretation(pi)

    pixeldata = gdcm.DataElement(gdcm.Tag(0x7fe0, 0x0010))
    str1 = ir.GetBuffer()
    #print ir.GetBufferLength()
    pixeldata.SetByteValue(str1, gdcm.VL(len(str1)))
    image.SetDataElement(pixeldata)

    w = gdcm.ImageWriter()
    w.SetFileName(file2)
    w.SetFile(r.GetFile())
    w.SetImage(image)
    if not w.Write():
        sys.exit(1)
示例#10
0
    def _scan(self, paths):
        """Given a list combining filenames and directories, search
        recursively to find all valid DICOM files.  Build
        dictionaries.
        """

        # UIDs are unique for their domains.  Patient ID for example
        # is not unique.
        # Instance UID (0008,0018)
        # Patient ID (0010,0020)
        # Study UID (0020,000D) - data with common procedural context
        # Study description (0008,1030)
        # Series UID (0020,000E)

        # see http://public.kitware.com/pipermail/igstk-developers/
        # 2006-March/000901.html for explanation w.r.t. number of
        # frames; for now we are going to assume that this refers to
        # the number of included slices (as is the case for the
        # Toshiba 320 slice for example)

        tag_to_symbol = {
            (0x0008, 0x0018): 'instance_uid',
            (0x0010, 0x0010): 'patient_name',
            (0x0010, 0x0020): 'patient_id',
            (0x0020, 0x000d): 'study_uid',
            (0x0008, 0x1030): 'study_description',
            (0x0008, 0x0020): 'study_date',
            (0x0020, 0x000e): 'series_uid',
            (0x0008, 0x103e): 'series_description',
            (0x0008, 0x0060): 'modality',  # fixed per series
            (0x0028, 0x0008): 'number_of_frames',
            (0x0028, 0x0010): 'rows',
            (0x0028, 0x0011): 'columns'
        }

        # find list of unique and sorted filenames
        filenames = self._helper_recursive_glob(paths)

        s = gdcm.Scanner()
        # add the tags we want to the scanner
        for tag_tuple in tag_to_symbol:
            tag = gdcm.Tag(*tag_tuple)
            s.AddTag(tag)

        # maps from study_uid to instance of Study
        study_dict = {}

        # we're going to break the filenames up into 10 blocks and
        # scan each block separately in order to be able to give
        # proper feedback to the user, and also to give the user the
        # opportunity to interrupt the scan
        num_files = len(filenames)

        # no filenames, we return an empty dict.
        if num_files == 0:
            return study_dict

        num_files_per_block = 100
        num_blocks = num_files / num_files_per_block
        if num_blocks == 0:
            num_blocks = 1

        blocklen = num_files / num_blocks
        blockmod = num_files % num_blocks

        block_lens = [blocklen] * num_blocks
        if blockmod > 0:
            block_lens += [blockmod]

        file_idx = 0
        progress = 0.0

        # setup progress dialog
        dlg = wx.ProgressDialog(
            "DICOMBrowser",
            "Scanning DICOM data",
            maximum=100,
            parent=self._view_frame,
            style=wx.PD_CAN_ABORT
            | wx.PD_APP_MODAL
            | wx.PD_ELAPSED_TIME
            | wx.PD_AUTO_HIDE
            #| wx.PD_ESTIMATED_TIME
            | wx.PD_REMAINING_TIME)
        keep_going = True
        error_occurred = False

        # and now the processing loop can start
        for block_len in block_lens:
            # scan the current block of files
            try:
                self._helper_scan_block(
                    s, filenames[file_idx:file_idx + block_len], tag_to_symbol,
                    study_dict)
            except Exception:
                # error during scan, we have to kill the dialog and
                # then re-raise the error
                dlg.Destroy()
                raise

            # update file_idx for the next block
            file_idx += block_len
            # update progress counter
            progress = int(100 * file_idx / float(num_files))
            # and tell the progress dialog about our progress
            # by definition, progress will be 100 at the end: if you
            # add all blocklens together, you have to get 1
            (keep_going, skip) = dlg.Update(progress)

            if not keep_going:
                # user has clicked cancel so we zero the dictionary
                study_dict = {}
                # and stop the for loop
                break

        # dialog needs to be taken care of
        dlg.Destroy()

        # return all the scanned data
        return study_dict
示例#11
0
#
#  Copyright (c) 2006-2010 Mathieu Malaterre
#  All rights reserved.
#  See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details.
#
#     This software is distributed WITHOUT ANY WARRANTY; without even
#     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
#     PURPOSE.  See the above copyright notice for more information.
#
############################################################################

import gdcm
import os, sys

if __name__ == "__main__":
    o1 = gdcm.Tag(0x0000, 0x0000)
    o2 = gdcm.Tag(0x0010, 0x0000)
    o3 = gdcm.Tag(0x0000, 0x0010)
    o4 = gdcm.Tag(0x0010, 0x0010)

    if o1 == o2:
        sys.exit(1)
    if o1 == o3:
        sys.exit(1)
    if o1 == o4:
        sys.exit(1)

    if o1 != o1:
        sys.exit(1)

    if o1 > o2:
示例#12
0
文件: gdcm.py 项目: pydicom/pydicom
def _rle_encode(src: bytes, **kwargs: Any) -> bytes:
    """Return RLE encoded image data from `src`.

    Parameters
    ----------
    src : bytes
        The raw image frame data to be encoded.
    **kwargs
        Required parameters:

        * `rows`: int
        * `columns`: int
        * `samples_per_pixel`: int
        * `number_of_frames`: int
        * `bits_allocated`: int
        * `bits_stored`: int
        * `pixel_representation`: int
        * `photometric_interpretation`: str

    Returns
    -------
    bytes
        The encoded image data.
    """
    # Check the parameters are valid for RLE encoding with GDCM
    rows = kwargs['rows']
    columns = kwargs['columns']
    samples_per_pixel = kwargs['samples_per_pixel']
    number_of_frames = kwargs['number_of_frames']
    pixel_representation = kwargs['pixel_representation']
    bits_allocated = kwargs['bits_allocated']
    bits_stored = kwargs['bits_stored']
    photometric_interpretation = kwargs['photometric_interpretation']

    # Bug up to v3.0.9 (Apr 2021) in handling 32-bit, 3 sample/px data
    gdcm_version = [int(c) for c in gdcm.Version.GetVersion().split('.')]
    if gdcm_version < [3, 0, 10]:
        if bits_allocated == 32 and samples_per_pixel == 3:
            raise RuntimeError(
                "The 'gdcm' plugin is unable to RLE encode 32-bit, 3 "
                "samples/px data with GDCM v3.0.9 or older"
            )

    if bits_allocated > 32:
        raise ValueError(
            f"The 'gdcm' plugin is unable to encode {bits_allocated}-bit data"
        )

    # Create a gdcm.Image with the uncompressed `src` data
    pi = gdcm.PhotometricInterpretation.GetPIType(
        photometric_interpretation
    )

    # GDCM's null photometric interpretation gets used for invalid values
    if pi == gdcm.PhotometricInterpretation.PI_END:
        raise ValueError(
            "An error occurred with the 'gdcm' plugin: invalid photometric "
            f"interpretation '{photometric_interpretation}'"
        )

    # `src` uses little-endian byte ordering
    ts = gdcm.TransferSyntax.ImplicitVRLittleEndian

    # Must use ImageWriter().GetImage() to create a gdcmImage
    #   also have to make sure `writer` doesn't go out of scope
    writer = gdcm.ImageWriter()
    image = writer.GetImage()
    image.SetNumberOfDimensions(2)
    image.SetDimensions((columns, rows, 1))
    image.SetPhotometricInterpretation(
        gdcm.PhotometricInterpretation(pi)
    )
    image.SetTransferSyntax(gdcm.TransferSyntax(ts))

    pixel_format = gdcm.PixelFormat(
        samples_per_pixel,
        bits_allocated,
        bits_stored,
        bits_stored - 1,
        pixel_representation
    )
    image.SetPixelFormat(pixel_format)
    if samples_per_pixel > 1:
        # Default `src` is planar configuration 0 (i.e. R1 G1 B1 R2 G2 B2)
        image.SetPlanarConfiguration(0)

    # Add the Pixel Data element and set the value to `src`
    elem = gdcm.DataElement(gdcm.Tag(0x7FE0, 0x0010))
    elem.SetByteStringValue(src)
    image.SetDataElement(elem)

    # Converts an image to match the set transfer syntax
    converter = gdcm.ImageChangeTransferSyntax()

    # Set up the converter with the intended transfer syntax...
    rle = gdcm.TransferSyntax.GetTSType(kwargs['transfer_syntax_uid'])
    converter.SetTransferSyntax(gdcm.TransferSyntax(rle))
    # ...and image to be converted
    converter.SetInput(image)

    # Perform the conversion, returns bool
    # 'PALETTE COLOR' and a lossy transfer syntax will return False
    result = converter.Change()
    if not result:
        raise RuntimeError(
            "An error occurred with the 'gdcm' plugin: "
            "ImageChangeTransferSyntax.Change() returned a failure result"
        )

    # A new gdcmImage with the converted pixel data element
    image = converter.GetOutput()

    # The element's value is the encapsulated encoded pixel data
    seq = image.GetDataElement().GetSequenceOfFragments()

    # RLECodec::Code() uses only 1 fragment per frame
    if seq is None or seq.GetNumberOfFragments() != 1:
        # Covers both no sequence and unexpected number of fragments
        raise RuntimeError(
            "An error occurred with the 'gdcm' plugin: unexpected number of "
            "fragments found in the 'Pixel Data'"
        )

    fragment = seq.GetFragment(0).GetByteValue().GetBuffer()
    return cast(bytes, fragment.encode("utf-8", "surrogateescape"))
示例#13
0
# (2005,0014)     LO      26      Philips MR Imaging DD 005
tag1 = gdcm.PrivateTag(0x2005, 0x09, "Philips MR Imaging DD 005")
tag2 = gdcm.PrivateTag(0x2005, 0x0a, "Philips MR Imaging DD 005")
print tag1
print tag2

# make sure to do a copy, we want the private tag to remain
# otherwise gdcm gives us a reference
el1 = gdcm.DataElement(ds.GetDataElement(tag1))
print el1
el2 = gdcm.DataElement(ds.GetDataElement(tag2))
print el2

# (0028,1052) DS [-1000]                                  #   6, 1 RescaleIntercept
# (0028,1053) DS [1]                                      #   2, 1 RescaleSlope

el1.SetTag(gdcm.Tag(0x0028, 0x1052))
el2.SetTag(gdcm.Tag(0x0028, 0x1053))

ds.Insert(el1)
ds.Insert(el2)

w = gdcm.Writer()
w.SetCheckFileMetaInformation(False)
w.SetFileName(tmpfile)
w.SetFile(reader.GetFile())
if not w.Write():
    sys.exit(1)

print "success"
示例#14
0
if __name__ == "__main__":

  file1 = sys.argv[1]
  file2 = sys.argv[2]

  r = gdcm.Reader()
  r.SetFileName( file1 )
  if not r.Read():
    sys.exit(1)

  f = r.GetFile()
  ds = f.GetDataSet()
  #tsis = gdcm.Tag(0x0008,0x2112) # SourceImageSequence

  # Create a dataelement
  de = gdcm.DataElement(gdcm.Tag(0x0010, 0x2180))
  de.SetByteValue("Occupation", gdcm.VL(len("Occupation")))
  de.SetVR(gdcm.VR(gdcm.VR.SH))

  # Create an item
  it=gdcm.Item()
  it.SetVLToUndefined()      # Needed to not popup error message
  #it.InsertDataElement(de)
  nds=it.GetNestedDataSet()
  nds.Insert(de)

  # Create a Sequence
  sq=gdcm.SequenceOfItems().New()
  sq.SetLengthToUndefined()
  sq.AddItem(it)
示例#15
0
import gdcm

if __name__ == "__main__":

    file1 = sys.argv[1]
    file2 = sys.argv[2]

    r = gdcm.Reader()
    r.SetFileName(file1)
    if not r.Read():
        sys.exit(1)

    ano = gdcm.Anonymizer()
    ano.SetFile(r.GetFile())
    ano.RemovePrivateTags()
    ano.Remove(gdcm.Tag(0x0032, 0x1030))
    ano.Remove(gdcm.Tag(0x008, 0x14))
    ano.Remove(gdcm.Tag(0x008, 0x1111))
    ano.Remove(gdcm.Tag(0x008, 0x1120))
    ano.Remove(gdcm.Tag(0x008, 0x1140))
    ano.Remove(gdcm.Tag(0x10, 0x21b0))
    ano.Empty(gdcm.Tag(0x10, 0x10))
    ano.Empty(gdcm.Tag(0x10, 0x20))
    ano.Empty(gdcm.Tag(0x10, 0x30))
    ano.Empty(gdcm.Tag(0x20, 0x10))
    ano.Empty(gdcm.Tag(0x32, 0x1032))
    ano.Empty(gdcm.Tag(0x32, 0x1033))
    ano.Empty(gdcm.Tag(0x40, 0x241))
    ano.Empty(gdcm.Tag(0x40, 0x254))
    ano.Empty(gdcm.Tag(0x40, 0x253))
    ano.Empty(gdcm.Tag(0x40, 0x1001))
示例#16
0
#  Copyright (c) 2006-2011 Mathieu Malaterre
#  All rights reserved.
#  See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details.
#
#     This software is distributed WITHOUT ANY WARRANTY; without even
#     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
#     PURPOSE.  See the above copyright notice for more information.
#
############################################################################

import gdcm
import os, sys

g = gdcm.Global.GetInstance()
g.LoadResourcesFiles()
defs = g.GetDefs()
modules = defs.GetModules()
macros = defs.GetMacros()
#module = modules.GetModule( "MR Image Module Attributes" )
module = modules.GetModule("C.8.3.1")
#print dir(module)

mentry = module.GetModuleEntryInMacros(macros, gdcm.Tag(0x0018, 0x0087))
#print dir(mentry)
print mentry
mentry = module.GetModuleEntryInMacros(macros, gdcm.Tag(0x0018, 0x1080))
print mentry

# Test succeed ?
sys.exit(0)