示例#1
0
def find_bbox(filenames, return_slice_ticks=False, slice_axis=2):
    """
    It can be used for slice ticks localization.

    """
    data_min = []
    data_max = []
    slice_ticks = []

    for filename in filenames:
        Vraw, Fraw = readFile(filename)
        V = np.asarray(Vraw)
        data_min.append(np.min(V, axis=0))
        data_max.append(np.max(V, axis=0))
        if return_slice_ticks:
            slice_ticks_one = np.unique(V[:, slice_axis])
            slice_ticks = slice_ticks + slice_ticks_one.tolist()

    mx = np.max(data_max, axis=0)
    mi = np.min(data_min, axis=0)

    if return_slice_ticks:
        return mi, mx, np.unique(slice_ticks).tolist()
    else:
        return mi, mx
示例#2
0
def main(numSets,accuracy,flag,length=3):
    if flag == 2:
        n = int(sanitizeInput("Input the block size here:")) 
        mostRandom = int(sanitizeInput("Print 1 for purely random, 0 for predefined clusters"))
        increaseN(n,mostRandom,numSets)
        return
    elif flag == 1:
        n = int(sanitizeInput("Input the sample size here:") )
        low = float(sanitizeInput("Input the range minimum here:"))
        high = float(sanitizeInput("Input the range maximum here:"))
        points = []
        theRange = high - low
        spacing = float(theRange)/numSets
        means = []
        thePoint = ()
        midpoint = ()
        for j in range(length-1):
            thePoint = thePoint + (0,)
            midpoint = midpoint + (1/(numSets-1)**0.5,)
        thePoint = thePoint + (1,)
        midpoint = midpoint + (0,)
        increment = helpers.add(thePoint,helpers.mult(-1,midpoint))
        for i in range(numSets):
            means.append(helpers.add(thePoint,helpers.mult(float(i+0.5)/numSets,increment)))
        for i in range(n):
            thePoint = ()
            j = 0
            while j < length:
                thePoint = thePoint + (rand.uniform(low,high),)
                j = j + 1
            points.append(thePoint)
    else:
        testnum = sanitizeInput("Input the test number here:")
        filepath = "../Testing/test"+testnum+".csv"
        points = fileio.readFile(filepath)
#       low = helpers.theMin(points)
#       high = helpers.theMax(points)
#       spacing = ()
#       for i in range(length):
#           spacing = spacing + ((high[i]-low[i])/numSets,)
        means = []
        n = len(points)
        thePoint = ()
        midpoint = ()
        for j in range(length-1):
            thePoint = thePoint + (0,)
            midpoint = midpoint + (1/float(length-1),)
        thePoint = thePoint + (1,)
        midpoint = midpoint + (0,)
        increment = helpers.add(midpoint,helpers.mult(-1,thePoint))
#       print thePoint, midpoint, increment
        thePoint = helpers.add(thePoint,helpers.mult(0.25,increment))
        increment = helpers.mult(0.5,increment)
#       print thePoint, increment
        for i in range(numSets):
            means.append(helpers.add(thePoint,helpers.mult(float(i+0.5)/numSets,increment)))

#   print means
    doKMeans(points,means)
示例#3
0
def visualizeObj(objfile, explode=False):
    """
    Try use Batch.openObj it is fast. But cannot read quadrilaterals and
    floating point number.
    If it fail there is backup version.
    If explode fucntionality is wanted, it is always using LAR visualization
    wich is slow.
    """
    import step_loadmodel
    if explode:
        try:
            step_loadmodel(objfile)
        except:
            V, FV = readFile(objfile)  # , ftype='obj')
            visualize(V, FV, explode)
    else:
        V, FV = readFile(objfile)  # , ftype='obj')
        visualize(V, FV, explode)
def main():

    logger = logging.getLogger()
    logger.setLevel(logging.WARNING)
    ch = logging.StreamHandler()
    logger.addHandler(ch)

    # logger.debug('input params')

    # input parser
    parser = argparse.ArgumentParser(description="Laplacian smoothing")
    parser.add_argument('-i',
                        '--inputfile',
                        default=None,
                        required=True,
                        help='input file')
    parser.add_argument('-o',
                        '--outputfile',
                        default='smooth.obj',
                        help='input file')
    parser.add_argument('-v',
                        '--visualization',
                        action='store_true',
                        help='Use visualization')
    parser.add_argument('-d',
                        '--debug',
                        action='store_true',
                        help='Debug mode')

    args = parser.parse_args()
    if args.debug:
        logger.setLevel(logging.DEBUG)

    t0 = time.time()
    V, FV = readFile(args.inputfile)

    t1 = time.time()
    logger.info('Data imported                   %ss. #V: %i, #FV: %i' %
                (str(t1 - t0), len(V), len(FV)))

    # V2 = makeSmoothing(V, FV)
    V2 = iterativeLaplacianSmoothing(V, FV)

    if args.visualization:
        # t7 = time.time()
        # FV = triangulateSquares(FV)
        # tv1 = time.time()
        # logger.info('triangulation               %ss' %
        #             (str(tv1 - t7)))
        VIEW(STRUCT(MKPOLS((V2, FV))))


# write outputs
    writeFile(args.outputfile + '.pkl', V2, FV)
    writeFile(args.outputfile, V2, FV)
    logger.info("Data stored to ' %s" % (args.outputfile))
示例#5
0
def read_one_file_add_to_labeled_image(filename,
                                       data3d,
                                       data_offset,
                                       int_multiplicator,
                                       slice_ticks=None,
                                       slice_axis=2,
                                       squeeze_number=2):
    """
    squeeze_number
    """

    Vraw, Fraw = readFile(filename)

    # parse filename
    nums = re.findall(r'\d+', filename)
    label = int(nums[0])

    V = np.asarray(Vraw)
    # data_offset = np.min(V, axis=0)
    V = V - data_offset

    # TODO rozpracovat do obecnější formy
    # low number of unique numbers in axix - axis of slices
    # slice_axis = argmin  pro kazdou osu z:   len(np.unique(VVV[:,1]))
    # slice_axis = 2

    # import ipdb; ipdb.set_trace() #  noqa BREAKPOINT
    # first_slice_offset = slice_ticks.index(
    #     np.min(unV2) + data_offset[slice_axis])

    # not nice discretization
    V[:, 0] = V[:, 0] * int_multiplicator
    V[:, 1] = V[:, 1] * int_multiplicator

    slice_ticks_0 = np.asarray(slice_ticks) - data_offset[slice_axis]

    slice_indexes = range(0, len(slice_ticks))
    for i in slice_indexes[:-squeeze_number:squeeze_number]:

        in_slice_idx =  \
            (V[:, slice_axis] >= slice_ticks_0[i]) & \
            (V[:, slice_axis] < slice_ticks_0[i + squeeze_number])
        if np.sum(in_slice_idx) > 0:
            # import ipdb; ipdb.set_trace() #  noqa BREAKPOINT
            points = V[in_slice_idx, :]
            points[:, 2] = i / squeeze_number
            points = points.astype(np.int)

            if points.shape[0] > 2:
                points_to_volume_slice(data3d, points, label)
                # points_to_volume_3D(data3d, points)
            else:
                print "low number of points", points.shape[0], \
                    " z-level ", points[0, slice_axis]
示例#6
0
def main():
    logger = logging.getLogger()
    logger.setLevel(logging.WARNING)
    ch = logging.StreamHandler()
    logger.addHandler(ch)

    # logger.debug('input params')

    # input parser
    parser = argparse.ArgumentParser(
        description="Remove faces from file"
    )
    parser.add_argument(
        '-i', '--inputfile',
        default=None,
        required=True,
        help='input file'
    )
    parser.add_argument(
        '-o', '--outputfile',
        default=None,
        required=True,
        help='output file'
    )
    parser.add_argument(
        '-b', '--boxsize',
        default=None,
        type=int,
        metavar='N',
        nargs='+',
        help='Size of box'
    )
    parser.add_argument(
        '-a', '--alberto', action='store_true',
        help='Albertos algorithm')
    parser.add_argument(
        '-d', '--debug', action='store_true',
        help='Debug mode')
    args = parser.parse_args()
    if args.debug:
        logger.setLevel(logging.DEBUG)
    v, f = readFile(args.inputfile)
    print "Before"
    print "Number of vertexes: %i    Number of faces %i" % (len(v), len(f))
    # findBoxVertexesForAxis(v, 2, 0)
    # v, f = findBoundaryFaces(v, f, 2)
    v, f = removeDoubleVertexesAndFaces(v, f, args.boxsize,
                                        use_dict_algorithm=args.alberto)
    writeFile(args.outputfile, v, f)
    print "After"
    print "Number of vertexes: %i    Number of faces %i" % (len(v), len(f))
示例#7
0
def makeSmooth(inputfile,
               bordersize=[2, 2, 2],
               outputdir='output',
               outputfile='out',
               visualization=False,
               borderdir='border',
               make_triangulation=True,
               label=2,
               smoothing=True):
    """

    :param inputfile: path to input data. It can be tiff, pklz, dicom or other 3d file or
     directory with dicom files or jpegs
    :param bordersize: Data are processed per partes. bordersize specify size of one part
    :param outputdir: directory with output stl files and temporary files. Acronyms in file names are:
    sm - smoothing, i - converted to integer, tr - triangulation, cl - cleaning done, do double faces.
    :param outputfile: name of outpu file
    :param visualization: output can be visualized by setting this parametr True
    :param borderdir: temporary directory with bordermatrix computation
    :param make_triangulation:
    :param label: expected value in object pixels of input data
    :return:
    """
    filepath, ext = os.path.splitext(inputfile)
    if ext == "obj":
        obj_input = inputfile
    else:
        print 'Processing pklz data'
        convert(inputfile,
                bordersize,
                outputdir,
                borderdir=borderdir,
                label=label)
        obj_input = 'stl/model-2.obj'
    # V, F = readFile(args.inputfile)
    V, F = readFile(os.path.join(outputdir, obj_input))
    print "Before"
    print "Number of vertexes: %i    Number of faces %i" % (len(V), len(F))
    # F = rmbox.shiftFaces(F, -1)
    V, F = makeCleaningAndSmoothing(V, F, os.path.join(outputdir, outputfile),
                                    smoothing)
    print "After"
    print "Number of vertexes: %i    Number of faces %i" % (len(V), len(F))
    # write to ints
    # fill empty vertexes
    V = [v if len(v) == 3 else [0, 0, 0] for v in V]
    # make tenimes bigger
    Vint = (np.asarray(V) * 10).astype(np.int).tolist()
    if outputfile is not None:
        writeFile(os.path.join(outputdir, outputfile + "_sm_i.obj"),
                  Vint,
                  F,
                  ignore_empty_vertex_warning=True)


# make triangulation
    if make_triangulation:
        Ftr = save_triangulated(V, Vint, F, outputdir, outputfile)

    if visualization:
        Ftr = triangulate_quads(F)
        vis.visualize(V, Ftr)

    return V, F