Exemple #1
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