def WriteWoolzObject(filename, obj):
    errNum = Wlz.enum__WlzErrorNum(Wlz.WLZ_ERR_FILE_OPEN)
    fp = libc.fopen(filename, 'wb')
    if (bool(fp)):
        errNum = Wlz.WlzWriteObj(fp, obj)
        libc.fclose(fp)
    return (errNum)
def ReadWoolzFile(filename):
    obj = None
    errNum = Wlz.enum__WlzErrorNum(Wlz.WLZ_ERR_FILE_OPEN)
    fp = libc.fopen(filename, 'rb')
    if (bool(fp)):
        obj = Wlz.WlzReadObj(fp, ctypes.byref(errNum))
        libc.fclose(fp)
    return (obj)
def ReadLmkTr(): #{
  sv = []
  tv = []
  try: #{
    if args.input == '-': #{
      f = sys.stdin
    else: #}{
      f = open(args.input, 'r')
    #}
    doc = et.parse(f)
    idx = 0
    for lm in doc.findall('Landmark'): #{
      s = lm.find('Source')
      t = lm.find('Target')
      sv.append(GetLmkVertex(s))
      tv.append(GetLmkVertex(t))
      VerbMsg('{:d} {:g} {:g} {:g} {:g} {:g} {:g}'. \
              format( \
                idx, \
                sv[idx].vtX, sv[idx].vtY, sv[idx].vtZ, \
                tv[idx].vtX, tv[idx].vtY, tv[idx].vtZ))
      idx = idx + 1
    #}
    if not args.input == '-': #{
      f.close()
    #}
    if ((not len(sv) == len(tv)) or (len(sv) < 3)): #{
      raise IOError()
    #}
  except IOError: #}{
    ErrorMsg('Failed to read ITK affine transform from file ' + args.input)
  #}
  try: #{
    n = len(sv)
    svtx = (w.WlzDVertex3 * n)()
    tvtx = (w.WlzDVertex3 * n)()
    errNum = w.enum__WlzErrorNum(w.WLZ_ERR_NONE)
    for i in range(0, n): #{
      svtx[i] = sv[i]
      tvtx[i] = tv[i]
    #}
    tr = w.WlzAffineTransformLSq3D(n, tvtx, n, svtx, 0, None, \
                         w.enum__WlzTransformType(w.WLZ_TRANSFORM_3D_AFFINE), \
                         c.byref(errNum))
    if bool(errNum) or \
       (not int(tr.contents.type) == int(w.WLZ_TRANSFORM_3D_AFFINE)): #{
      raise WlzError()
    #}
  except WlzError: #}{
    ErrorMsg('Failed to compute LSq affine transform from landmarks (' +
             w.WlzStringFromErrorNum(errNum, None) + ')')
  #}
  mat = WlzTrToMat(tr)
  return(mat)
Exemple #4
0
 def readWlzObj(self, fname):  #{
     logging.debug('readWlzObj()')
     obj = None
     logging.debug('attempting to read object from ' + fname)
     self.errnum = c.c_int(w.WLZ_ERR_FILE_OPEN)
     fp = c.cast(libc.fopen(fname, 'rb'), c.POINTER(w.FILE))
     if bool(fp):  #{
         obj = w.WlzAssignObject( \
               w.WlzReadObj(fp, c.byref(self.errnum)), None)
         libc.fclose(fp)
         if bool(self.errnum):  #{
             self.warnWlzError('Failed to read object from ' + fname)
         #}
     #}
     return (obj)
def WriteWoolzObject(filename, obj):
  errNum = Wlz.enum__WlzErrorNum(Wlz.WLZ_ERR_FILE_OPEN)
  fp = libc.fopen(filename, 'wb')
  if(bool(fp)):
    errNum = Wlz.WlzWriteObj(fp, obj)
    libc.fclose(fp)
  return(errNum)
Exemple #6
0
 def warnWlzError(self, msg):  #{
     logging.debug('warnWlzError')
     logging.debug('error message is: ' + msg)
     err = str(w.WlzStringFromErrorNum(self.errnum, None))
     logging.debug('error code is: ' + err)
     QtGui.QMessageBox.critical(self, 'Warning', msg + ' (' + err + ')',
                                QtGui.QMessageBox.Close)
     self.errnum = c.c_int(w.WLZ_ERR_NONE)
def ReadWoolzFile(filename):
  obj = None
  errNum = Wlz.enum__WlzErrorNum(Wlz.WLZ_ERR_FILE_OPEN)
  fp = libc.fopen(filename, 'rb')
  if(bool(fp)):
    obj = Wlz.WlzReadObj(fp, ctypes.byref(errNum))
    libc.fclose(fp)
  return(obj)
def ChkWoolzError(errNum, status): #{
  if(bool(errNum)): #{
    msg = 'Woolz error ' + w.WlzStringFromErrorNum(errNum, None)
    if(status < 1): #{
      MsgWarn(msg)
    else: #}{
      MsgError(msg, status)
    #}
    raise WlzError()
Exemple #9
0
 def trackCurVal(self, evt):  #{
     logging.debug('trackCurVal(' + str(evt) + ')')
     pos = evt[0]
     if self.img_itm.sceneBoundingRect().contains(pos):  #{
         q = self.img_view_box.mapSceneToView(pos)
         p = [int(q.x()), int(q.y())]
         v = self.img[p[0], p[1]]
         g = w.WlzStringFromGreyType(self.obj_gtype, None)
         msg = str(g) + ' ' + str(p) + ' ' + str(v)
         self.statusBar().showMessage(msg)
Exemple #10
0
 def setObj2D(self):  #{
     logging.debug('setObj2D')
     errnum = c.c_int(w.WLZ_ERR_NONE)
     t = self.obj.contents.type
     if t == w.WLZ_2D_DOMAINOBJ:  #{
         self.obj2d = w.WlzAssignObject(self.obj, None)
     elif t == w.WLZ_3D_DOMAINOBJ:  #}{
         logging.debug('cutting section from 3D object')
         w.WlzInit3DViewStruct(self.view, self.obj)
         o2d = w.WlzGetSubSectionFromObject(
             self.obj, None, self.view,
             c.c_int(w.WLZ_INTERPOLATION_NEAREST), None, c.byref(errnum))
         print(o2d)
         print(errnum)
         if not bool(errnum):  #{
             w.WlzFreeObj(self.obj2d)
             self.obj2d = w.WlzAssignObject(o2d, None)
         #}
     #}
     return (errnum)
def ReadWlzTr(): #{
  try: #{
    errNum = w.enum__WlzErrorNum(w.WLZ_ERR_FILE_OPEN)
    if args.input== '-': #{
      f = libc.stdin
    else: #}{
      f = libc.fopen(args.input, 'rb')
    #}
    if not bool(f): #{
      raise IOError()
    #}
    obj = w.WlzAssignObject( \
          w.WlzReadObj(f, c.byref(errNum)), None)
    if not args.input == '-': #{
      libc.fclose(f)
    #}
    if not bool(obj): #{
      errNum = w.enum__WlzErrorNum(w.WLZ_ERR_OBJECT_NULL)
      raise WlzError()
    #}
    if ((not int(obj.contents.type) == int(w.WLZ_AFFINE_TRANS)) or \
        (not int(obj.contents.domain.core.contents.type) ==  \
             int(w.WLZ_TRANSFORM_3D_AFFINE))): #{
      errNum = w.enum__WlzErrorNum(w.WLZ_ERR_OBJECT_TYPE)
      raise WlzError()
    #}
  except IOError: #}{
    ErrorMsg('Failed to open ' + args.input)
  except WlzError: #}{
    ErrorMsg('Failed to read affine transform from ' + args.input +
             '(' + w.WlzStringFromErrorNum(errNum, None) + ')')
  #}
  mat = WlzTrToMat(obj.contents.domain.t)
  return(mat)
Exemple #12
0
def outputFiles(out_dir, img_series, rescale, nowrite):
    for i in img_series:
        vrbMsg('Encoding ' + img_series[i][0].ProtocolName + '_' + str(i))
        obj = makeWlzImageObj(img_series[i], rescale)
        file_base = out_dir + '/' + img_series[i][0].ProtocolName + '_' + str(
            i)
        wlz_file_nm = file_base + '.wlz'
        txt_file_nm = file_base + '.txt'
        if not nowrite:
            fp = c.cast(fopen(wlz_file_nm.encode('utf-8'), b'wb'),
                        c.POINTER(w.FILE))
            err_num = w.WlzWriteObj(fp, obj)
            if bool(err_num):
                raise WlzError()
            fclose(fp)
            vrbMsg('Woolz object written to ' + wlz_file_nm)
        w.WlzFreeObj(obj)
        obj = None
        if not nowrite:
            f = open(txt_file_nm, 'wt')
            f.write(str(img_series[i][0]))
            f.close()
            vrbMsg('Text written to ' + txt_file_nm)
Exemple #13
0
 def wlz2DToNP(self):  #{
     ary = None
     logging.debug('wlz2DToNP()')
     try:  #{
         box = w.WlzBoundingBox3I(self.obj2d, c.byref(self.errnum))
         if (bool(self.errnum)):  #{
             raise WlzError()
         #}
         sz = w.WlzIVertex2()
         sz.vtX = box.xMax - box.xMin + 1
         sz.vtY = box.yMax - box.yMin + 1
         org = w.WlzIVertex2()
         org.vtX = box.xMin
         org.vtY = box.yMin
         gtype = w.WlzGreyTypeFromObj(self.obj2d, c.byref(self.errnum))
         if (bool(self.errnum)):  #{
             raise WlzError()
         #}
         if gtype == w.WLZ_GREY_INT:  #{
             vtype = c.c_int
         elif gtype == w.WLZ_GREY_SHORT:  #}{
             vtype = c.c_short
         elif gtype == w.WLZ_GREY_UBYTE:  #}{
             vtype = c.c_ubyte
         elif gtype == w.WLZ_GREY_FLOAT:  #}{
             vtype = c.c_float
         elif gtype == w.WLZ_GREY_DOUBLE:  #}{
             vtype = c.c_double
         else:  #}{
             self.errnum = c.c_int(w.WLZ_ERR_GREY_TYPE)
             raise WlzError()
         #}
         UPP = c.POINTER(c.POINTER(vtype))
         UPV = c.POINTER(c.c_void_p)
         aryc = c.cast(0, UPV)
         self.errnum = w.WlzToArray2D(c.byref(aryc), self.obj2d, sz, org, 0, \
                                      c.c_int(gtype))
         if (bool(self.errnum)):  #{
             raise WlzError()
         #}
         aryc = c.cast(aryc, UPP)
         ary = np.ctypeslib.as_array(aryc.contents, (sz.vtY, sz.vtX))
         self.obj_gtype = gtype
         self.obj2d_sz = [sz.vtX, sz.vtY]
         self.obj2d_org = [org.vtX, org.vtY]
         w.AlcFree(aryc)
     except WlzError:  #}{
         self.warnWlzError('Failed to extract numeric data from object.')
     #}
     return (ary)
Exemple #14
0
 def addObj(self, o):  #{
     logging.debug('addObj()')
     t = int(o.contents.type)
     self.errnum = c.c_int(w.WLZ_ERR_OBJECT_TYPE)
     if (t == int(w.WLZ_2D_DOMAINOBJ)) or (t == int(
             w.WLZ_3D_DOMAINOBJ)):  #{
         if t == int(w.WLZ_2D_DOMAINOBJ):  #{
             self.errnum = c.c_int(w.WLZ_ERR_NONE)
         else:  #}{
             logging.debug('making view struct')
             v = w.WlzMake3DViewStruct(c.c_int(w.WLZ_3D_VIEW_STRUCT), \
                                       c.byref(self.errnum))
             if not bool(self.errnum):  #{
                 f = w.WlzDVertex3()
                 v.vtX = c.c_double(0.0)
                 v.vtY = c.c_double(0.0)
                 v.vtZ = c.c_double(0.0)
                 v.contents.theta = self.yaw * m.pi / 180.0
                 v.contents.phi = self.pitch * m.pi / 180.0
                 v.contents.zeta = self.roll * m.pi / 180.0
                 v.contents.dist = self.dist
                 v.contents.fixed = f
                 v.contents.view_mode = c.c_int(w.WLZ_UP_IS_UP_MODE)
                 v.contents.scale = c.c_double(1.0)
                 v.contents.voxelRescaleFlg = c.c_int(0)
                 w.WlzFree3DViewStruct(self.view)
                 self.view = w.WlzAssign3DViewStruct(v, None)
             #}
         #}
     #}
     if not bool(self.errnum):  #{
         w.WlzFreeObj(self.obj)
         self.obj = w.WlzAssignObject(o, None)
         self.errnum = self.setObj2D()
     #}
     if not bool(self.errnum):  #{
         ary = self.wlz2DToNP()
         logging.debug('setting image')
         self.img = ary.astype(np.float64).T
         self.img_itm.setImage(self.img)
         self.setROIType('N')
     #}
     if bool(self.errnum):  #{
         self.warnWlzError('Failed to add object.')
Exemple #15
0
#!/usr/bin/python
# Reads a Woolz 2D or 3D domain object and generates a histogram.

from __future__ import print_function
import sys
import ctypes
import Wlz
import matplotlib.pyplot as pt
import numpy as np

libc = ctypes.CDLL("libc.so.6")
fopen = libc.fopen
fclose = libc.fclose

errNum = Wlz.enum__WlzErrorNum(Wlz.WLZ_ERR_NONE)

fopen.restype = ctypes.POINTER(Wlz.FILE)

f = 'test.wlz'

print('Read test object from the file ' +  f);
fp = fopen(f, 'rb')
obj = Wlz.WlzAssignObject(Wlz.WlzReadObj(fp, ctypes.byref(errNum)), None)
fclose(fp)
if(bool(errNum)):
  print('Failed to read object from ' + f + \
        ' (' + Wlz.WlzStringFromErrorNum(errNum, None) + ').')
  exit(1)


if((not bool(obj.contents)) or
def ExportDomainsToIndexObj():  #{
    # Get domain indices and names from the label description file
    # adding the domain at each step.
    cpd_obj = None
    idx_obj = None
    max_idx = 0
    obj_type = w.WLZ_NULL
    dom_objs = []
    dom_idxs = []
    with open(args.ldf) as ldf:  #{
        for rec in ldf:  #{
            VerbMsg('rec = ' + rec)
            if not re.match(r'^[ \t]*#', rec):  #{
                rec = rec.lstrip()
                dom_idx = int(re.split('\s+', rec)[0])
                dom_name = re.split('"', rec)[1]
                VerbMsg('idx = ' + str(dom_idx) + ' dom = ' + dom_name)
                if (dom_idx > 0):  #{
                    try:  #{
                        if dom_idx > max_idx:  #{
                            max_idx = dom_idx
                        #}
                        dom_idxs.append(dom_idx)
                        errNum = w.enum__WlzErrorNum(w.WLZ_ERR_FILE_OPEN)
                        dom_file = args.domaindir + '/' + dom_name + '.wlz'
                        fp = libc.fopen(dom_file, 'rb')
                        if not bool(fp):  #{
                            raise IOError()
                        #}
                        obj = w.WlzAssignObject( \
                              w.WlzReadObj(fp, c.byref(errNum)), None)
                        if (bool(errNum)):  #{
                            raise WlzError()
                        #}
                        p_lst = w.WlzMakePropertyList(None)
                        p_nam = w.WlzMakeNameProperty(dom_name,
                                                      c.byref(errNum))
                        if (bool(errNum)):  #{
                            raise WlzError()
                        #}
                        ft = c.CFUNCTYPE(c.c_void_p, c.c_void_p)\
                                        (w.WlzFreePropertyListEntry)
                        alcerr = w.AlcDLPListEntryAppend(p_lst.contents.list, None, \
                                       p_nam, ft)
                        if (bool(alcerr)):  #{
                            raise WlzError()
                        #}
                        obj.contents.plist = w.WlzAssignPropertyList(
                            p_lst, None)
                        dom_objs.append(obj)
                        libc.fclose(fp)
                        if (bool(errNum)):  #{
                            raise WlzError()
                        #}
                        VerbMsg('domain object type (idx == ' + str(dom_idx) + ') ' + \
                                str(w.WlzStringFromObjTypeValue( \
                                obj.contents.type, None)))
                        if (obj_type == w.WLZ_NULL):  #{
                            if((obj.contents.type == w.WLZ_2D_DOMAINOBJ) or \
                               (obj.contents.type == w.WLZ_3D_DOMAINOBJ)): #{
                                obj_type = obj.contents.type
                            #}
                        #}
                    except IOError:  #}{
                        ErrorMsg('Failed to read domain from file ' + dom_file + \
                                 ' (' + w.WlzStringFromErrorNum(errNum, None) + ')')
                    except WlzError:  #}{
                        ErrorMsg('Failed to process domain from file ' + dom_file + \
                                 ' (' + w.WlzStringFromErrorNum(errNum, None) + ')')
                    #}
                #}
            #}
        #}
    #}
    VerbMsg('Object type ' + str(w.WlzStringFromObjTypeValue(obj_type, None)))
    if ((max_idx < 1) or ((not obj_type == w.WLZ_2D_DOMAINOBJ) and
                          (not obj_type == w.WLZ_3D_DOMAINOBJ))):  #{
        ErrorMsg('Require at least one 2 or 3D domain with a positive index.')
    #}
    try:  #{
        VerbMsg('Creating compound array object of domains.')
        cpd_obj = w.WlzMakeCompoundArray( \
                    w.enum__WlzObjectType(w.WLZ_COMPOUND_ARR_2), \
                    1, max_idx + 1, None, obj_type, c.byref(errNum))
        if (bool(errNum)):  #{
            raise WlzError()
        #}
        for i in range(0, len(dom_objs)):  #{
            obj = dom_objs[i]
            idx = dom_idxs[i]
            cpd_obj.contents.o[idx] = obj
        #}
    except:  #}{
        ErrorMsg('Failed to create compound object from domains (' + \
                 w.WlzStringFromErrorNum(errNum, None) + ')')
    #}
    if not args.compound:  #{
        try:  #{
            VerbMsg('Creating index object from compound of domains.')
            idx_obj = w.WlzAssignObject( \
                      w.WlzIndexObjFromCompound(cpd_obj, c.byref(errNum)), None)
            if (bool(errNum)):  #{
                raise WlzError()
            #}
        except:  #}{
            ErrorMsg('Failed to create index object from compound of domains (' + \
                     w.WlzStringFromErrorNum(errNum, None) + ')')
        #}
    #}
    if bool(args.reference) and (not args.compound):  #{
        try:  #{
            VerbMsg('Cutting index object to the same bounding box as the\n' + \
                    'reference object (read from ' + args.reference + ').')
            fp = None
            errNum = w.enum__WlzErrorNum(w.WLZ_ERR_FILE_OPEN)
            if args.reference == '-':  #{
                fp = libc.stdin
            else:  #}{
                fp = libc.fopen(args.reference, 'rb')
            #}
            if not bool(fp):  #{
                raise IOError()
            #}
            obj = w.WlzAssignObject( \
                  w.WlzReadObj(fp, c.byref(errNum)), None)
            if not args.reference == '-':  #{
                libc.fclose(fp)
            #}
            if (bool(errNum)):  #{
                raise WlzError()
            #}
            box = w.WlzBoundingBox3I(obj, c.byref(errNum))
            if (not bool(errNum)):  #{
                gtype = w.WlzGreyTypeFromObj(idx_obj, c.byref(errNum))
            #}
            w.WlzFreeObj(obj)
            if (bool(errNum)):  #{
                raise WlzError()
            #}
            VerbMsg('Using bounding box ' + \
                    '(' + str(box.xMin) + ',' + str(box.xMax) + '),' + \
                    '(' + str(box.yMin) + ',' + str(box.yMax) + '),' + \
                    '(' + str(box.zMin) + ',' + str(box.zMax) + ')')
            VerbMsg('Preserving grey type ' + \
                    w.WlzStringFromGreyType(gtype, None) + \
                    '.')
            obj = w.WlzCutObjToBox3D(idx_obj, box, gtype, 0, 0.0, 0.0, \
                                       c.byref(errNum))
            if (bool(errNum)):  #{
                raise WlzError()
            #}
            w.WlzFreeObj(idx_obj)
            idx_obj = obj
        except IOError:  #}{
            ErrorMsg('Failed to read the reference object read from ' + \
                     args.reference + '.')
        except WlzError:  #}{
            ErrorMsg('Failed to cut index object to the bounding box of the\n' + \
                     'reference object read from (' + args.reference + ') (' + \
                     w.WlzStringFromErrorNum(errNum, None) + ')')
        #}
    #}
    try:  #{
        ft = 'index'
        if args.compound:  #{
            ft = 'compound'
        #}
        VerbMsg('Writing ' + ft + ' object to output file (' + args.output +
                ').')
        errNum = w.enum__WlzErrorNum(w.WLZ_ERR_FILE_OPEN)
        if args.output == '-':  #{
            fp = libc.stdout
        else:  #}{
            fp = libc.fopen(args.output, 'wb')
        #}
        if not bool(fp):  #{
            raise IOError()
        #}
        if args.compound:  #{
            errNum = w.WlzWriteObj(fp, cpd_obj)
        else:  #}{
            errNum = w.WlzWriteObj(fp, idx_obj)
        #}
        if not args.output == '-':  #{
            libc.fclose(fp)
        #}
        if (bool(errNum)):  #{
            raise WlzError()
        #}
    except:  #}{
        ErrorMsg('Failed to write ' + ft + ' object to file (' + \
                 w.WlzStringFromErrorNum(errNum, None) + ')')
        #}
        if args.compound:  #{
            errNum = w.WlzWriteObj(fp, cpd_obj)
        else:  #}{
            errNum = w.WlzWriteObj(fp, idx_obj)
        #}
        if not args.output == '-':  #{
            libc.fclose(fp)
        #}
        if (bool(errNum)):  #{
            raise WlzError()
        #}
    except:  #}{
        ErrorMsg('Failed to write ' + ft + ' object to file (' + \
                 w.WlzStringFromErrorNum(errNum, None) + ')')
    #}


#}

if __name__ == '__main__':  #{
    # Process the command line
    args = ParseArgs()
    prog = sys.argv[0]
    errNum = w.enum__WlzErrorNum(w.WLZ_ERR_NONE)
    if (args.verbose):  #{
        print(prog + ': args = ' + str(args))
    #}
    ExportDomainsToIndexObj()
#}
        a_node = False
      #}
    #}
    if(not bool(a_node)): #{
      MsgWarn('failed to merge color for EMAPA:' + str(t_EMAPA) + ' ' +
              row.name)
    #}
  #}
#}

if __name__ == '__main__': #{
  #
  # Process the command line
  args = ParseArgs()
  prog = sys.argv[0];
  errNum = w.enum__WlzErrorNum(w.WLZ_ERR_NONE)
  if(args.stage): #{
    match = re.match(r'^TS\d\d?$', args.stage.upper())
    if(match): #{
      single_stage = match.group(0)
    else: #}{
      MsgError('Bad stage, specify using TS[0-9][0-9]? (eg TS07\n' +
               'or TS17).', 1)
    #}
  #}
  MsgVerbose('args = ' + str(args))
  #
  # Fetch the EMAP service description file
  MsgVerbose('Fetching service description file (using url =\n' +
             emap_srv_desc_url + ').')
  try: #{
def GetLmkVertex(g): #{
  vtx = w.WlzDVertex3()
  vtx.vtX = float(g.find('X').text)
  vtx.vtY = float(g.find('Y').text)
  vtx.vtZ = float(g.find('Z').text)
  return(vtx)
    with open(filename, "w") as ff:
        for fr in flt:
            print(fr, file=ff)
    ff.close()


def CleanExit(stat):
    for f in glob.glob(workfile + '[0-1].*'):
        os.remove(f)
    exit(stat)


if __name__ == '__main__':
    args = ParseArgs()
    prog = sys.argv[0]
    errNum = Wlz.enum__WlzErrorNum(Wlz.WLZ_ERR_NONE)

    if (args.verbose):
        print('Args = ' + str(args))

    workfile = tempfile.mktemp(dir=args.tmpdir, prefix='wd2vs')

    # Use MAVTKDomainToSurf to create an stl file corresponding to the
    # given Woolz domain.
    cmdline = [MAVTKDomainToSurf, '-o' + workfile + '0.stl']
    if (args.voxelscaling):
        cmdline.append('-z')
    cmdline.append(args.infile)
    if (args.verbose):
        print(cmdline)
    rtn = subprocess.call(cmdline)
def WriteMeshLabFilter(filename, flt):
  with open(filename, "w") as ff:
    for fr in flt:
      print(fr, file=ff)
  ff.close()

def CleanExit(stat):
  for f in glob.glob(workfile + '[0-1].*'):
    os.remove(f)
  exit(stat)

if __name__ == '__main__':
  args = ParseArgs()
  prog = sys.argv[0];
  errNum = Wlz.enum__WlzErrorNum(Wlz.WLZ_ERR_NONE)

  if(args.verbose):
    print('Args = ' + str(args))

  workfile = tempfile.mktemp(dir=args.tmpdir, prefix='wd2vs')

  # Use MAVTKDomainToSurf to create an stl file corresponding to the
  # given Woolz domain.
  cmdline = [MAVTKDomainToSurf, '-o' + workfile + '0.stl']
  if(args.voxelscaling):
    cmdline.append('-z')
  cmdline.append(args.infile)
  if(args.verbose):
    print(cmdline)
  rtn = subprocess.call(cmdline)
Exemple #22
0
def makeWlzImageObj(slices, rescale):
    vrbMsg('creating Woolz object')
    obj = None
    gvw = None
    errNum = w.enum__WlzErrorNum(w.WLZ_ERR_NONE)
    s0 = slices[0]
    nx = s0.Columns
    ny = s0.Rows
    nz = len(slices)
    sx = float(s0.PixelSpacing[0])
    sy = float(s0.PixelSpacing[1])
    r_intercept = 0.0
    r_slope = 1.0
    bgd_v = 0
    if rescale:
        if ('RescaleIntercept' in s0) and ('RescaleSlope' in s0):
            r_intercept = float(s0.RescaleIntercept)
            r_slope = float(s0.RescaleSlope)
            bgd_v = int(r_intercept)
        else:
            wrnMsg(
                'Unable to rescale image grey values to Hounsfield units as ' +
                'rescale parameters not in DICOM metadata.')
    sz = m.fabs(slices[1].ImagePositionPatient[2] - s0.ImagePositionPatient[2])
    if (sz < sys.float_info.epsilon) and ('SpacingBetweenSlices' in s0):
        sz = m.fabs(s0.SpacingBetweenSlices)
    if sz < sys.float_info.epsilon:
        if nz > 1:
            wrnMsg(
                'Multiple slices at same position, slice thickness set to 1.0.'
            )
        sz = 1.0
    x1 = int(np.floor(s0.ImagePositionPatient[0] / sx))
    y1 = int(np.floor(s0.ImagePositionPatient[1] / sy))
    z1 = int(np.floor(s0.ImagePositionPatient[2] / sz))
    g_type = w.WlzGreyType(w.WLZ_GREY_ERROR)
    if s0.BitsAllocated == 8:
        g_type = int(w.WLZ_GREY_UBYTE)
    elif s0.BitsAllocated == 16:
        g_type = int(w.WLZ_GREY_SHORT)
    else:
        raise Exception('Unsupported voxel grey type.')
    err_num = w.enum__WlzErrorNum(w.WLZ_ERR_NONE)
    obj = w.WlzMakeCuboidI(z1, z1 + nz - 1, y1, y1 + ny - 1, x1, x1 + nx - 1,
                           g_type, bgd_v, None, None, c.byref(err_num))
    if not bool(err_num):
        err_num = w.enum__WlzErrorNum(w.WlzSetVoxelSize(obj, sx, sy, sz))
    if not bool(err_num):
        vvp = obj.contents.values.vox.contents.values
        for iz in range(0, nz):
            si = slices[iz]
            vp = vvp[iz].r.contents.values
            for iy in range(0, ny):
                offset = nx * iy
                for ix in range(0, nx):
                    if g_type == int(w.WLZ_GREY_UBYTE):
                        ubp = vp.ubp[offset + ix]
                        ubp.contents = c.c_char(si.pixel_array[iy, ix])
                    elif g_type == int(w.WLZ_GREY_SHORT):
                        vp.shp[offset + ix] = c.c_short(
                            int((si.pixel_array[iy, ix] * r_slope) +
                                r_intercept))
                    else:
                        raise Exception('Unsupported voxel grey type.')
    return obj