Beispiel #1
0
    def downloadSeries(self, studyUID, seriesUID, outputdir, patientID=None):
        hashdir = hashlib.sha224(studyUID + "/" + seriesUID).hexdigest()
        targetdir = outputdir + "/" + hashdir + "/"

        if not os.path.exists(outputdir): os.makedirs(outputdir)
        if not os.path.exists(targetdir): os.makedirs(targetdir)

        self.de_infmodel = gdcm.DataElement(self.tag_infmodel)
        self.de_infmodel.SetByteValue('SERIES', gdcm.VL(len('SERIES')))
        self.de_StudyUID = gdcm.DataElement(self.tag_StudyUID)
        self.de_StudyUID.SetByteValue(studyUID, gdcm.VL(len(studyUID)))
        self.de_SeriesUID = gdcm.DataElement(self.tag_SeriesUID)
        self.de_SeriesUID.SetByteValue(seriesUID, gdcm.VL(len(seriesUID)))
        self.dataset_seriesQuery = gdcm.DataSet()
        self.dataset_seriesQuery.Insert(self.de_StudyUID)
        self.dataset_seriesQuery.Insert(self.de_infmodel)
        self.dataset_seriesQuery.Insert(self.de_SeriesUID)

        self.cnf_series = gdcm.CompositeNetworkFunctions()
        self.theSeriesQuery = self.cnf_series.ConstructQuery(
            gdcm.eStudyRootType, gdcm.eSeries, self.dataset_seriesQuery)
        # Execute the C-FIND query
        self.cnf_series.CMove(self.server, self.remoteport,
                              self.theSeriesQuery, self.localport,
                              self.aetitle, self.caller, targetdir)
        return targetdir
Beispiel #2
0
def TestModifyFields(filename):
    outfilename = filename + ".rewrite"
    r = gdcm.Reader()
    r.SetFileName(filename)
    sucess = r.Read()
    #print r.GetFile().GetDataSet()

    ds = r.GetFile().GetDataSet()
    #print dir(ds)
    # eg, let's remove a tag
    removetag = gdcm.Tag(0x0043, 0x106f)
    if ds.FindDataElement(removetag):
        ds.Remove(removetag)

    # let's replace a value:
    replacetag = gdcm.Tag(0x0010, 0x0010)
    if ds.FindDataElement(replacetag):
        de = ds.GetDataElement(replacetag)
        #print dir(de)
        patname = "This^is^an^example"
        vl = gdcm.VL(len(patname))
        de.SetByteValue(patname, vl)

    # let's insert a new dataelement
    # <entry group="0012" element="0062" vr="CS" vm="1" name="Patient Identity Removed"/>
    pir = gdcm.DataElement(gdcm.Tag(0x0012, 0x0062))
    pir.SetVR(gdcm.VR(gdcm.VR.CS))  # specify the VR explicitely
    yes = "YES"
    pir.SetByteValue(yes, gdcm.VL(len(yes)))
    ds.Insert(pir)

    # try again but pretend we don't know the VR
    # <entry group="0012" element="0063" vr="LO" vm="1-n" name="De-identification Method"/>
    deidmethod = gdcm.Tag(0x0012, 0x0063)
    # retrieve the supreme global instance, sum of all knowledge in da whole universe:
    dicomdicts = gdcm.GlobalInstance.GetDicts()
    dictel = dicomdicts.GetDictEntry(deidmethod)
    #print dictel.GetVR()
    deid = gdcm.DataElement(deidmethod)
    deid.SetVR(dictel.GetVR())
    methodstr = "Well known Company"
    #deid.SetByteValue( methodstr, gdcm.VL(len(methodstr)) )
    deid.SetByteValue(methodstr, gdcm.VL(len(methodstr)))
    ds.Insert(deid)

    #w = gdcm.Writer()
    #w.SetFileName( outfilename )
    #w.SetFile( r.GetFile() )
    #sucess = w.Write()
    return sucess
Beispiel #3
0
    def RunCMove(self, values):

        ds = gdcm.DataSet()

        #for v in values:


        tg_patient = gdcm.Tag(0x0010, 0x0020)
        tg_serie = gdcm.Tag(0x0020, 0x000e)

        de_patient = gdcm.DataElement(tg_patient)
        de_serie = gdcm.DataElement(tg_serie)

        patient_id = str(values[0])        
        serie_id = str(values[1])

        print "(0x0010, 0x0020)",patient_id
        
        print "(0x0020, 0x000e)",serie_id
        print "\n\n"

        de_patient.SetByteValue(patient_id,  gdcm.VL(len(patient_id)))
        de_serie.SetByteValue(serie_id, gdcm.VL(len(serie_id)))

        ds.Insert(de_patient)
        ds.Insert(de_serie)


        cnf = gdcm.CompositeNetworkFunctions()
        theQuery = cnf.ConstructQuery(gdcm.ePatientRootType, gdcm.eImageOrFrame, ds)
        #ret = gdcm.DataSetArrayType()

        """
        CMove (const char *remote, 
        uint16_t portno, 
        const BaseRootQuery *query, 

        uint16_t portscp, 
        const char *aetitle=NULL, 
        const char *call=NULL, 
        const char *outputdir=NULL)"""

        print ">>>>>", self.address, int(self.port), theQuery, 11112, self.aetitle,\
                  self.aetitle_call, "/home/phamorim/Desktop/output/"


        cnf.CMove(self.address, int(self.port), theQuery, 11112, self.aetitle,\
                  self.aetitle_call, "/home/phamorim/Desktop/")

        print "BAIXOUUUUUUUU"
Beispiel #4
0
def study(request, study_iuid):
    # Patient Name
    response = {}
    study_iuid_tag = gdcm.Tag(0x20, 0xD)
    study_iuid_element = gdcm.DataElement(study_iuid_tag)
    study_descr_tag = gdcm.Tag(0x8, 0x1030)
    study_descr_element = gdcm.DataElement(study_descr_tag)
    study_iuid_element.SetByteValue(str(study_iuid), gdcm.VL(len(study_iuid)))
    ds = gdcm.DataSet()
    ds.Insert(study_iuid_element)
    ds.Insert(study_descr_element)
    cnf = gdcm.CompositeNetworkFunctions()
    theQuery = cnf.ConstructQuery(gdcm.eStudyRootType, gdcm.eStudy, ds)

    # prepare the variable for output
    ret = gdcm.DataSetArrayType()
    # Execute the C-FIND query
    cnf.CFind(settings.SC_DICOM_SERVER, settings.SC_DICOM_PORT, theQuery, ret,
              'GDCM_PYTHON', settings.AET)

    response["description"] = str(
        ret[0].GetDataElement(study_descr_tag).GetValue())

    ds = gdcm.DataSet()

    series_descr_tag = gdcm.Tag(0x8, 0x103E)
    series_descr_element = gdcm.DataElement(series_descr_tag)
    series_iuid_tag = gdcm.Tag(0x20, 0xE)
    series_iuid_element = gdcm.DataElement(series_iuid_tag)
    series_number_tag = gdcm.Tag(0x20, 0x11)
    series_number_element = gdcm.DataElement(series_number_tag)

    ds.Insert(study_iuid_element)
    ds.Insert(series_descr_element)
    ds.Insert(series_iuid_element)
    ds.Insert(series_number_element)

    series_query = cnf.ConstructQuery(gdcm.eStudyRootType, gdcm.eSeries, ds)
    ret = gdcm.DataSetArrayType()
    cnf.CFind(settings.SC_DICOM_SERVER, settings.SC_DICOM_PORT, series_query,
              ret, 'GDCM_PYTHON', settings.AET)

    sorted_ret = sorted(
        ret,
        key=lambda x: int(str(x.GetDataElement(series_number_tag).GetValue())))

    response["series"] = [{
        "description":
        str(x.GetDataElement(series_descr_tag).GetValue()),
        "uid":
        str(x.GetDataElement(series_iuid_tag).GetValue())
    } for x in sorted_ret]

    json_response = json.dumps(response)

    if request.GET.has_key('callback'):
        json_response = "(function(){%s(%s);})();" % (request.GET['callback'],
                                                      json_response)

    return HttpResponse(json_response, content_type="application/json")
Beispiel #5
0
    def construct_dataset(self, dic_keys, dataset_rsp=None):
        #fill dataset
        dataset = gdcm.DataSet()
        for tags in dic_keys:
            group = tags[0]
            element = tags[1]
            de = gdcm.DataElement(gdcm.Tag(group, element))
            if dataset_rsp and group == 0x0020 and element == 0x000D:
                de = dataset_rsp.GetDataElement(gdcm.Tag(group, element))
                value = str(de.GetByteValue())
            else:
                value = dic_keys[tags]
            if value:
                value_length = len(value)
                de.SetByteValue(value, gdcm.VL(value_length))
                #de.SetVR(gdcm.VR(gdcm.VR.PN))
            dataset.Insert(de)

        return dataset
Beispiel #6
0
def series(request, series_iuid):

    series_iuid_tag = gdcm.Tag(0x20, 0xE)
    series_iuid_element = gdcm.DataElement(series_iuid_tag)
    series_iuid_element.SetByteValue(str(series_iuid),
                                     gdcm.VL(len(series_iuid)))
    instance_uid_tag = gdcm.Tag(0x8, 0x18)
    instance_uid_element = gdcm.DataElement(instance_uid_tag)
    instance_number_tag = gdcm.Tag(0x20, 0x13)
    instance_number_element = gdcm.DataElement(instance_number_tag)

    ds = gdcm.DataSet()
    ds.Insert(series_iuid_element)
    ds.Insert(instance_uid_element)
    ds.Insert(instance_number_element)

    cnf = gdcm.CompositeNetworkFunctions()

    instance_query = cnf.ConstructQuery(gdcm.eStudyRootType, gdcm.eImage, ds)
    ret = gdcm.DataSetArrayType()
    cnf.CFind(settings.SC_DICOM_SERVER, settings.SC_DICOM_PORT, instance_query,
              ret, 'GDCM_PYTHON', settings.AET)

    sorted_ret = sorted(
        ret,
        key=lambda x: int(str(
            x.GetDataElement(instance_number_tag).GetValue())))
    response = [
        str(x.GetDataElement(instance_uid_tag).GetValue()) for x in sorted_ret
    ]

    json_response = json.dumps(response)

    if request.GET.has_key('callback'):
        json_response = "(function(){%s(%s);})();" % (request.GET['callback'],
                                                      json_response)

    return HttpResponse(json_response, content_type="application/json")
Beispiel #7
0
    def RunCFind(self):

        tags = [(0x0010, 0x0010), (0x0010, 0x1010), (0x0010,0x0040), (0x0008,0x1030),\
                (0x0008,0x0060), (0x0008,0x0022), (0x0008,0x0080), (0x0010,0x0030),\
                (0x0008,0x0050), (0x0008,0x0090), (0x0008,0x103E), (0x0008,0x0033),\
                (0x0008,0x0032), (0x0020,0x000d)]

        ds = gdcm.DataSet()

        for tag in tags:

            tg = gdcm.Tag(tag[0], tag[1])

            de = gdcm.DataElement(tg)

            if self.search_type == 'patient' and tag == (0x0010, 0x0010):

                bit_size = len(self.search_word) + 1
                de.SetByteValue(str(self.search_word + '*'), gdcm.VL(bit_size))
            else:
                de.SetByteValue('*', gdcm.VL(1))

            ds.Insert(de)

        cnf = gdcm.CompositeNetworkFunctions()
        theQuery = cnf.ConstructQuery(gdcm.ePatientRootType,
                                      gdcm.eImageOrFrame, ds)
        ret = gdcm.DataSetArrayType()

        cnf.CFind(self.address, int(self.port), theQuery, ret, self.aetitle,\
                  self.aetitle_call)

        patients = {}

        exist_images = False
        c = 0
        for i in range(0, ret.size()):
            patient_id = str(ret[i].GetDataElement(gdcm.Tag(
                0x0010, 0x0020)).GetValue())
            serie_id = str(ret[i].GetDataElement(gdcm.Tag(0x0020,
                                                          0x000e)).GetValue())

            if not (patient_id in patients.keys()):
                patients[patient_id] = {}

            if not (serie_id in patients[patient_id]):

                rt = ret[i]

                name = self.GetValueFromDICOM(rt, (0x0010, 0x0010))
                age = self.GetValueFromDICOM(rt, (0x0010, 0x1010))
                gender = self.GetValueFromDICOM(rt, (0x0010, 0x0040))
                study_description = self.GetValueFromDICOM(
                    rt, (0x0008, 0x1030))
                modality = self.GetValueFromDICOM(rt, (0x0008, 0x0060))
                institution = self.GetValueFromDICOM(rt, (0x0008, 0x0080))
                date_of_birth = utils.format_date(
                    self.GetValueFromDICOM(rt, (0x0010, 0x0030)))
                acession_number = self.GetValueFromDICOM(rt, (0x0008, 0x0050))
                ref_physician = self.GetValueFromDICOM(rt, (0x0008, 0x0090))
                serie_description = self.GetValueFromDICOM(
                    rt, (0x0008, 0x103E))
                acquisition_time = utils.format_time(
                    self.GetValueFromDICOM(rt, (0x0008, 0x0032)))
                acquisition_date = utils.format_date(
                    self.GetValueFromDICOM(rt, (0x0008, 0x0022)))

                teste = self.GetValueFromDICOM(rt, (0x0020, 0x000d))

                patients[patient_id][serie_id] = {'name':name, 'age':age, 'gender':gender,\
                                                  'study_description':study_description,\
                                                  'modality':modality, \
                                                  'acquisition_time':acquisition_time,\
                                                  'acquisition_date':acquisition_date,\
                                                  'institution':institution,\
                                                  'date_of_birth':date_of_birth,\
                                                  'acession_number':acession_number,\
                                                  'ref_physician':ref_physician,\
                                                  'serie_description':serie_description}

                patients[patient_id][serie_id]['n_images'] = 1
            else:
                patients[patient_id][serie_id]['n_images'] += 1

        return patients
Beispiel #8
0
It will print the list of patient name found

Usage:

 python FindAllPatientName.py

"""

import gdcm

# Patient Name
tag = gdcm.Tag(0x10, 0x10)
de = gdcm.DataElement(tag)

# Search all patient name where string match 'F*'
de.SetByteValue('F*', gdcm.VL(2))

ds = gdcm.DataSet()
ds.Insert(de)

cnf = gdcm.CompositeNetworkFunctions()
theQuery = cnf.ConstructQuery(gdcm.ePatientRootType, gdcm.ePatient, ds)

#print theQuery.ValidateQuery()

# prepare the variable for output
ret = gdcm.DataSetArrayType()

# Execute the C-FIND query
cnf.CFind('dicom.example.com', 11112, theQuery, ret, 'GDCM_PYTHON', 'ANY-SCP')
Beispiel #9
0
  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)

  # Insert sequence into data set
Beispiel #10
0
    f = r.GetFile()
    ds = f.GetDataSet()
    tsis = gdcm.Tag(0x0008, 0x2112)  # SourceImageSequence
    if ds.FindDataElement(tsis):
        sis = ds.GetDataElement(tsis)
        #sqsis = sis.GetSequenceOfItems()
        # GetValueAsSQ handle more cases
        sqsis = sis.GetValueAsSQ()
        if sqsis.GetNumberOfItems():
            item1 = sqsis.GetItem(1)
            nestedds = item1.GetNestedDataSet()
            tprcs = gdcm.Tag(0x0040, 0xa170)  # PurposeOfReferenceCodeSequence
            if nestedds.FindDataElement(tprcs):
                prcs = nestedds.GetDataElement(tprcs)
                sqprcs = prcs.GetSequenceOfItems()
                if sqprcs.GetNumberOfItems():
                    item2 = sqprcs.GetItem(1)
                    nestedds2 = item2.GetNestedDataSet()
                    # (0008,0104) LO [Uncompressed predecessor]               #  24, 1 CodeMeaning
                    tcm = gdcm.Tag(0x0008, 0x0104)
                    if nestedds2.FindDataElement(tcm):
                        cm = nestedds2.GetDataElement(tcm)
                        mystr = "GDCM was here"
                        cm.SetByteValue(mystr, gdcm.VL(len(mystr)))

    w = gdcm.Writer()
    w.SetFile(f)
    w.SetFileName(file2)
    if not w.Write():
        sys.exit(1)
Beispiel #11
0
    def get_query_and_level(self, dic_keys):
        """Esta funcion retorna un dataset con los maching key y return key y 
        el nivel de consulta QR"""
        # Estos diccionarios pueden estar en ficheros
        level_patient = {
            "PatientName": (0x0010, 0x0010),
            "PatientID": (0x0010, 0x0020),
            "PatientSex": (0x0010, 0x0040),
            "PatientAge": (0x0010, 0x1010),
            "PatientBirthDate": (0010, 0030)
        }

        level_study = {
            "StudyDescription": (0x0008, 0x1030),
            "StudyDate": (0x0008, 0x0020),
            "StudyTime": (0x0008, 0x0030),
            "StudyInstanceUID": (0x0020, 0x000D),
            "NumberStudyRelatedInstances": (0x0020, 0x1208)
        }

        level_series = {
            "SeriesInstanceUID": (0x0020, 0x000E),
            "Modality": (0x0008, 0x0060),
            "SeriesDate": (0x0008, 0x0021),
            "SeriesTime": (0x0008, 0x0031),
            "NumberSeriesRelatedInstances": (0x0020, 0x1209)
        }

        level_image = {
            "SopInstanceUID": (0x0008, 0x0018),
            "InstanceNumber": (0x0020, 0x0013),
            "SopClassUID": (0x0008, 0x0016)
        }

        alias_tags = {}
        alias_tags.update(level_patient)
        alias_tags.update(level_study)
        alias_tags.update(level_series)
        alias_tags.update(level_image)

        query_level = -1

        for attr_key in dic_keys:
            value = dic_keys[attr_key]
            if attr_key in level_image:
                if value:
                    query_level = gdcm.eImageOrFrame
                break
            elif attr_key in level_patient:
                if value and query_level < gdcm.ePatient:
                    query_level = gdcm.ePatient
            elif attr_key in level_study:
                if value and query_level < gdcm.eStudy:
                    query_level = gdcm.eStudy
            elif attr_key in level_series:
                if value and query_level < gdcm.eSeries:
                    query_level = gdcm.eSeries
            else:
                raise Exception("Invaliud Tag")

        keys_dataset = gdcm.DataSet()
        #fill dataset
        for attr_key in dic_keys:
            group = alias_tags[attr_key][0]
            element = alias_tags[attr_key][1]
            de = gdcm.DataElement(gdcm.Tag(group, element))
            value = dic_keys[attr_key]
            if value:
                value_length = len(value)
                de.SetByteValue(value, gdcm.VL(value_length))
                #de.SetVR(gdcm.VR(gdcm.VR.PN))
            keys_dataset.Insert(de)

        return (query_level, keys_dataset)
if __name__ == "__main__":
    r = gdcm.Reader()
    # Will require Testing...
    dataroot = gdcm.Testing.GetDataRoot()
    filename = os.path.join(dataroot, '012345.002.050.dcm')
    r.SetFileName(filename)
    r.Read()
    f = r.GetFile()
    ds = f.GetDataSet()

    uid = "1.2.840.10008.5.1.4.1.1.66"
    #  f = gdcm.File()
    #  ds = f.GetDataSet()
    de = gdcm.DataElement(gdcm.Tag(0x0008, 0x0016))
    de.SetByteValue(uid, gdcm.VL(len(uid)))
    vr = gdcm.VR(gdcm.VR.UI)
    de.SetVR(vr)
    ds.Replace(de)

    ano = gdcm.Anonymizer()
    ano.SetFile(r.GetFile())
    ano.RemovePrivateTags()
    ano.RemoveGroupLength()
    taglist = [
        gdcm.Tag(0x0008, 0x0008),
        gdcm.Tag(0x0008, 0x0022),
        gdcm.Tag(0x0008, 0x0032),
        gdcm.Tag(0x0008, 0x2111),
        gdcm.Tag(0x0008, 0x1150),
        gdcm.Tag(0x0008, 0x1155),
Beispiel #13
0
    print ir.GetDimension(0)
    print ir.GetDimension(1)
    print "Dims:", dims

    #  Just for fun:
    dircos = ir.GetDirectionCosines()
    t = gdcm.Orientation.GetType(tuple(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.SetFileName(file2)
    w.SetFile(r.GetFile())
    w.SetImage(image)
    if not w.Write():
        sys.exit(1)
Beispiel #14
0
 def add(self, tag, value=""):
     self.dataelement = gdcm.DataElement(tag)
     self.dataelement.SetByteValue(value, gdcm.VL(len(value)))
     self.dataset.Insert(self.dataelement)
     return self