def main():
    searchSpace = tp.TaskPic(search_space_filename)
    ssx, ssy = searchSpace.size()

    for t in target_filenames:
        target = tp.Target(t, threshhold)
        print(t + ' initialized. now searching...\n')
        tx, ty = target.size()

        most_sim = {
            'sp': [0.0, (0, 0)],  # format: [most_sim, (pixel)]
            'mm': [0.0, (0, 0)],
            'alt': [0.0, (0, 0)]
        }

        subSpace = np.empty((tx, ty))
        #spArr = np.empty((ssx-tx+1,ssy-ty+1))
        #altArr = np.empty((ssx-tx+1,ssy-ty+1))

        nIterations = (ssx - tx + 1) * (ssy - ty + 1)
        counter = 0
        for sx in range(ssx - tx + 1):
            for sy in range(ssy - ty + 1):
                subSpace = np.array(searchSpace.pix[sx:sx + tx, sy:sy + ty])

                sp = sim.sumProd(target.pix, subSpace)
                mm = sim.maxMin(target.pix, subSpace)
                a = sim.alt(target.pix, subSpace)

                #spArr[sx,sy] = sp
                #altArr[sx,sy] = a

                if sp > most_sim['sp'][0]:
                    most_sim['sp'] = [sp, (sx, sy)]
                if mm > most_sim['mm'][0]:
                    most_sim['mm'] = [mm, (sx, sy)]
                if a > most_sim['alt'][0]:
                    most_sim['alt'] = [a, (sx, sy)]

                counter += 1

                if counter % 500 == 0:
                    print(
                        str(round(100 * (float(counter) / nIterations), 1)) +
                        r'% done')

        target.sp = most_sim['sp'][1]
        target.mm = most_sim['mm'][1]
        target.alt = most_sim['alt'][1]

        #debug(spArr,'sp'+target.fname.split('.')[0])
        #debug(altArr,'alt'+target.fname.split('.')[0])

        print(t + ' similarities:\n')
        print('sp: ' + str(most_sim['sp']))
        print('mm: ' + str(most_sim['mm']))
        print('alt: ' + str(most_sim['alt']) + '\n')

        print('Drawing boxes and saving...')
        target.box(searchSpace)
Esempio n. 2
0
def main():
    #choice, easel = tuple([tp.TaskPic(os.path.join(pic_path, pic)) for pic in os.listdir(pic_path)])
    choice, easel = tuple([
        tp.TaskPic(os.path.join(pic_path, pic))
        for pic in [choice_pic, easel_pic]
    ])
    hist_choice, bins = np.histogram(choice.pix, bins=40, range=(0.1, 1.0))
    hist_easel, _ = np.histogram(easel.pix, bins=40, range=(0.1, 1.0))

    #print hist_choice
    #print hist_easel

    width = 0.7 * (bins[1] - bins[0])
    center = (bins[:-1] + bins[1:]) / 2

    plt.bar(center, softmax(hist_choice), align='center', width=width)
    plt.title('Box Choice Distribution')
    #plt.show()
    plt.draw()
    fig = plt.gcf()
    fig.savefig('hist_choice_box.jpg')
    plt.clf()

    plt.bar(center, softmax(hist_easel), align='center', width=width)
    plt.title('Box Easel Distribution')
    #plt.show()
    plt.draw()
    fig = plt.gcf()
    fig.savefig('hist_easel_box.jpg')
    plt.clf()
Esempio n. 3
0
def main():

    print('Initializing task elements...')
    choices = [
        tp.TaskPic(os.getcwd() + '\\%s\\%s' % (choices_dir, c))
        for c in os.listdir(choices_dir)
    ]
    targets = [
        tp.TaskPic(os.getcwd() + '\\%s\\%s' % (targets_dir, t))
        for t in os.listdir(targets_dir)
    ]
    print('...DONE!\n')

    for t in targets:
        # TODO identify slices
        print(t.fname + ':\n')

        print('Identifying densest sqaure...')
        rot_ret, r_start = densest_square(
            t)  # returns retina for rotated target
        print('...DONE!\n')

        print('Starting density search...')
        locations = sim_density_search(choices, rot_ret, priority_queue_size)
        #print locations
        print('...DONE!\n')

        print('Starting rotational search...')
        result = search(choices, rot_ret,
                        locations)  # format: [sim, location, wedge_index]
        print('...DONE!\n')

        local_t_fname = t.fname.split('\\')[-1] if '\\' in t.fname else t.fname
        local_c_fname = choices[result[1][0]].fname.split(
            '\\')[-1] if '\\' in choices[result[1][0]].fname else choices[
                result[1][0]].fname
        print('%s densest at pixel %s with density %f:' %
              (local_t_fname, str(r_start), rot_ret.density))
        print('\t-Location: choice %d (AKA %s) at pixel %s' %
              (result[1][0], local_c_fname, str((result[1][1:]))))
        print(
            '\t-Rotation: wedge %d out of %d, which corresponds to the target being rotated %.2f degrees anti-clockwise'
            % (result[2], template.nWedges,
               round(float(result[2]) / template.nWedges * 360, 2)))
        print('\t-Similarity: %f' % result[0])
Esempio n. 4
0
def main():
    original = tp.TaskPic(original_filename)
    original.blur()
    #original.save()
    original.pix2retina()

    #original.pix = p2r.main(original.pix)

    rotated = tp.TaskPic(rotated_filename)
    rotated.blur()
    #rotated.save()
    rotated.pix2retina()

    #rotated.pix = p2r.main(rotated.pix)

    print('pictures initialized. Now beginning search...\n')
    results = search(original, rotated)

    for key in results.keys():
        print('%s:\t%f at %s' %
              (key, round(results[key][0], 3), str(results[key][1])))
Esempio n. 5
0
def main():
    searchSpace = tp.TaskPic(search_space_filename)
    ssx, ssy = searchSpace.size()

    ssSmall = searchSpace.resize(resize_factor)
    sssx, sssy = ssSmall.size()

    for t in target_filenames:
        target = tp.Target(t, threshhold)
        tx, ty = target.size()

        targetSmall = target.resize(resize_factor)
        tsx, tsy = targetSmall.size()

        print(t + ' initialized. Now beginning initial search...\n')
        search(ssSmall, targetSmall, [(0, 0, sssx - tsx + 1, sssy - tsy + 1)],
               priority_queue_size)

        #refined_search_locations = addLocations(targetSmall.most_sim['alt'],(ssx,ssy),(tx,ty))

        refined_search_locations = []
        for key in targetSmall.most_sim.keys():
            temp = [
                refined_search_locations,
                addLocations(targetSmall.most_sim[key], (ssx, ssy), (tx, ty))
            ]
            refined_search_locations = set().union(*temp)

        print('Initial search completed. Now beginning refined search...\n')
        results = search(searchSpace, target, refined_search_locations, 1)

        #debug(spArr,'sp'+target.fname.split('.')[0])
        #debug(altArr,'alt'+target.fname.split('.')[0])

        print(t + ' similarities:\n')
        for key in results.keys():
            print('%s:\t%f at %s' %
                  (key, round(results[key][0][0], 3), str(results[key][0][1])))
        #print results

        print('Drawing boxes and saving...')
        target.box(searchSpace)
Esempio n. 6
0
def solve_problem(prob):
    start_t = time.time()
    cwd = os.path.join(problems_dir, prob)

    print('Initializing choices...')
    # for later problems (09 thru 15) where there are easel choices
    choices = [
        tp.TaskPic(os.path.join(cwd, choices_dir, c))
        for c in os.listdir(os.path.join(cwd, choices_dir))
    ]
    # for earlier problems (03 thru 08) where there are no easel choices
    #choices = [tp.TaskPic(os.path.join(cwd,'easel.jpg'))]
    #targets = [tp.TaskPic(os.getcwd() + '\\%s\\%s' % (targets_dir,t)) for t in os.listdir(targets_dir)]
    print('...DONE!\n')

    target_path = os.path.join(cwd, targets_dir)
    outfile_path = os.path.join(os.getcwd(), results_dir, prob)

    for target in os.listdir(target_path):
        # TODO identify slices automatically

        target_outfile_path = os.path.join(outfile_path, 'choice_%s' % target)
        target_infile_path = os.path.join(target_path, target)
        for c_slice in os.listdir(target_infile_path):
            slice_name = c_slice.split('.')[0]
            slice_path = os.path.join(target_outfile_path, slice_name)
            if not os.path.exists(slice_path):
                os.makedirs(slice_path)

            with open(os.path.join(slice_path, 'console_readout.txt'),
                      'w') as f:
                print('Target: %s\nSlice: %s\n' % (target, slice_name))

                slicePic = tp.TaskPic(os.path.join(target_infile_path,
                                                   c_slice))

                pix = slicePic.pix
                s = None

                sx, sy = slicePic.size()
                max_dim = max(sx, sy)

                start_x = int((max_dim - sx)) / 2
                start_y = int((max_dim - sy)) / 2

                # creates a square matrix around pix, padding with zeros
                # adds 1 to make sure getTransparent() will reach all possible pixels
                padded = np.zeros((max_dim + 1, max_dim + 1), dtype=pix.dtype)
                padded[start_x:start_x + sx, start_y:start_y + sy] = pix
                slicePic.pix = np.copy(padded)
                slicePic.update()
                pix = slicePic.pix

                # resizes image for faster density_delta search
                slicePic_small = slicePic.resize(resize_factor)

                padded_choices = []
                padded_choices_small = []
                # pads each choice with zeros just in case slice and/or subslice is on edge
                for choice in choices:
                    cx, cy = choice.size()
                    start = s.size / 2
                    padded_pix = np.zeros((cx + s.size, cy + s.size),
                                          dtype=choice.pix.dtype)
                    padded_pix[start:start + cx, start:start + cy] = choice.pix

                    new_choice = choice.copy()
                    new_choice.pix = padded_pix
                    new_choice.update()

                    padded_choices.append(new_choice)

                    # resizes image for faster density_delta search
                    new_choice_small = new_choice.resize(resize_factor)

                    padded_choices.append(new_choice)
                    padded_choices_small.append(new_choice_small)

                print(
                    'Initializing....creating templates and retina objects...may take some time....'
                )

                # # empirically this has been found to be a good tradeoff of speed vs.
                # # efficiency as the retina gets bigger
                # hn_refined = int(round(max_dim / 25.0))
                # s_small = r.Slice(slicePic_small,prob,target,useTransparentPix=useTransparentPix,hn=hn_coarse)
                # # s_small.ret.visualize().show()
                # s = r.Slice(slicePic,prob,target,useTransparentPix=useTransparentPix,hn=hn_refined)
                # # s.ret.visualize().show()
                # print('\n....DONE!!!\n')

                # empirically this has been found to be a good tradeoff of speed vs.
                # efficiency as the retina gets bigger
                # hn = int(round(max_dim+1 / 25.0))
                hn = int(round((max_dim + 1) / 50.0))
                print('Creating slice template...')
                template = r.Template(max_dim + 1, hn=hn)
                print('....DONE!!!\n')

                # slice is too small for default subsize
                if subsize > min(pix.shape):
                    print('Using smaller subtemplate for this slice...')
                    s = r.HybridSlice(slicePic,
                                      prob,
                                      target,
                                      useTransparentPix=useTransparentPix,
                                      template=template,
                                      subsize=min(pix.shape) - 1,
                                      sub_hn=sub_hn)
                else:
                    s = r.HybridSlice(slicePic,
                                      prob,
                                      target,
                                      useTransparentPix=useTransparentPix,
                                      template=template,
                                      subtemplate=subtemplate)

                subtemp = s.subtemplate
                f.write('Using subretina with following parameters:\n')
                f.write('\t-size: %d x %d\n' % (subtemp.size, subtemp.size))
                f.write('\t-number of rings: %d\n' % subtemp.nRings)
                f.write('\t-number of wedges: %d\n' % subtemp.nWedges)
                f.write('\t-blindspot_radius: %f\n\n' % subtemp.bs_radius)

                temp = s.template
                f.write('Using retina with following parameters:\n')
                f.write('\t-size: %d x %d\n' % (temp.size, temp.size))
                f.write('\t-number of rings: %d\n' % temp.nRings)
                f.write('\t-number of wedges: %d\n' % temp.nWedges)
                f.write('\t-blindspot_radius: %f\n\n' % temp.bs_radius)

                print('Starting density search...')
                locations = sim_density_search(padded_choices, s.subslice.ret,
                                               priority_queue_size, slice_path)
                '''
				locations = [[np.array([141, 56])],
							 [np.array([60, 97])],
							 [np.array([116, 188])],
							 [np.array([60, 81])]]
							 #[np.array([129,100])]]
				'''

                #print locations
                print('...DONE!\n')

                print('Starting rotational search...')
                s_flipped = s.flip()
                primarySearch(padded_choices, s, s_flipped, locations)
                print('...DONE!\n')
                '''
				for slice in [s, s_flipped]:
					im = slice.taskpic.im
					name = slice.taskpic.fname.split('\\')[-1]
					boxes = []
					box_index = 0
					for start in [slice.primary.start,slice.secondary.start]:
						end = start + np.array([s.size-1,s.size-1])
						boxes.append(([tuple(start),tuple(end)],box_colors[box_index]))
						box_index += 1

					drawBoxes(im,boxes,slice_path,name)
				'''

                #sys.exit(1)

                sliceIm = slicePic.im
                boxes = []
                box_index = 0
                for start in [s.subslice.start]:
                    end = start + np.array([s.subsize - 1, s.subsize - 1])
                    boxes.append(([tuple(start),
                                   tuple(end)], box_colors[box_index]))
                    box_index += 1

                drawBoxes(sliceIm, boxes, slice_path, 'subslice.jpg')

                sliceImFlipped = s_flipped.taskpic.im
                boxes = []
                box_index = 0
                for start in [s_flipped.subslice.start]:
                    end = start + np.array([s.subsize - 1, s.subsize - 1])
                    boxes.append(([tuple(start),
                                   tuple(end)], box_colors[box_index]))
                    box_index += 1

                drawBoxes(sliceImFlipped, boxes, slice_path,
                          'subslice_flipped.jpg')
                print('Writing results...')

                f.write('subslice identified in %s:...\n\n' % slice_name)
                f.write('\t-Location in target slice: ' +
                        str(s.subslice.start) + '\n')
                f.write('\t-Variance (within retinal rings): ' +
                        str(s.subslice.ret.getVar()) + '\n')
                #f.write('\t-Unrefined Density: ' + str(s.primary.ret.getUnrefinedDensity()) + '\n')
                f.write('\t-Density: ' + str(s.subslice.ret.getDensity()) +
                        '\n')

                f.write('\nResults:...\n\n')

                writeResults(padded_choices, s, s_flipped, f, slice_path)
                print('...DONE!\n')

    end_t = time.time()

    print('\nTime elapsed: %f' % (end_t - start_t))
Esempio n. 7
0
def solve_problem(prob):
    start_t = time.time()
    cwd = os.path.join(problems_dir, prob)

    print('Initializing choices...')
    # for later problems (09 thru 15) where there are easel choices
    choices = [
        tp.TaskPic(os.path.join(cwd, choices_dir, c))
        for c in os.listdir(os.path.join(cwd, choices_dir))
    ]
    # for earlier problems (03 thru 08) where there are no easel choices
    #choices = [tp.TaskPic(os.path.join(cwd,'easel.jpg'))]
    #targets = [tp.TaskPic(os.getcwd() + '\\%s\\%s' % (targets_dir,t)) for t in os.listdir(targets_dir)]
    print('...DONE!\n')

    target_path = os.path.join(cwd, targets_dir)
    outfile_path = os.path.join(os.getcwd(), results_dir, prob)

    for target in os.listdir(target_path):
        # TODO identify slices automatically

        target_outfile_path = os.path.join(outfile_path, 'choice_%s' % target)
        target_infile_path = os.path.join(target_path, target)
        for c_slice in os.listdir(target_infile_path):
            slice_name = c_slice.split('.')[0]
            slice_path = os.path.join(target_outfile_path, slice_name)
            if not os.path.exists(slice_path):
                os.makedirs(slice_path)

            with open(os.path.join(slice_path, 'console_readout.txt'),
                      'w') as f:
                print('Target: %s\nSlice: %s\n' % (target, slice_name))

                slicePic = tp.TaskPic(os.path.join(target_infile_path,
                                                   c_slice))

                pix = slicePic.pix
                s = None

                sx, sy = slicePic.size()
                max_dim = max(sx, sy)

                start_x = int((max_dim - sx)) / 2
                start_y = int((max_dim - sy)) / 2

                # creates a square matrix around pix, padding with zeros
                padded = np.zeros((max_dim, max_dim), dtype=pix.dtype)
                padded[start_x:start_x + sx, start_y:start_y + sy] = pix
                pix = padded

                padded_choices = []
                # pads each choice with zeros just in case slice is on edge
                for choice in choices:
                    cx, cy = choice.size()
                    start = max_dim / 2
                    padded_pix = np.zeros((cx + max_dim, cy + max_dim),
                                          dtype=choice.pix.dtype)
                    padded_pix[start:start + cx, start:start + cy] = choice.pix

                    new_choice = choice.copy()
                    new_choice.pix = padded_pix
                    new_choice.update()

                    padded_choices.append(new_choice)

                print(
                    'Initializing....creating template and retina object...may take some time....'
                )

                # empirically this has been found to be a good tradeoff of speed vs.
                # efficiency as the retina gets bigger
                hn = int(round(max_dim / 25.0))
                s = r.CompleteTargetSlice(pix, prob, target, hn=hn)

                print('\n....DONE!!!\n')

                temp = s.template
                f.write('Using retina with following parameters:\n')
                f.write('\t-size: %d x %d\n' % (temp.size, temp.size))
                f.write('\t-number of rings: %d\n' % temp.nRings)
                f.write('\t-number of wedges: %d\n' % temp.nWedges)
                f.write('\t-blindspot_radius: %f\n\n' % temp.bs_radius)

                print('Starting density search...')
                locations = sim_density_search(padded_choices, s.ret,
                                               priority_queue_size, slice_path)

                #print locations
                print('...DONE!\n')

                print('Starting rotational search...')
                primarySearch(padded_choices, s, locations)
                print('...DONE!\n')

                print('Writing results...')

                f.write('Using slice %s:...\n' % slice_name)

                f.write('\nResults:...\n\n')

                writeResults(padded_choices, s, f, slice_path)
                print('...DONE!\n')

    end_t = time.time()

    print('\nTime elapsed: %f' % (end_t - start_t))
def main():

    start_t = time.time()

    print('Initializing choices...')
    choices = [
        tp.TaskPic(os.getcwd() + '\\%s\\%s' % (choices_dir, c))
        for c in os.listdir(choices_dir)
    ]
    #targets = [tp.TaskPic(os.getcwd() + '\\%s\\%s' % (targets_dir,t)) for t in os.listdir(targets_dir)]
    print('...DONE!\n')

    target_path = os.getcwd() + '\\' + targets_dir
    outfile_path = os.getcwd() + '\\' + results_dir + '\\'

    for target in os.listdir(targets_dir):
        # TODO identify slices automatically

        target_outfile_path = outfile_path + target
        if not os.path.exists(target_outfile_path):
            os.makedirs(target_outfile_path)

        with open(target_outfile_path + '\\console_readout.txt', 'w') as f:
            print(target + ':\n')

            path = target_path + '\\' + target

            print('Initializing slices...')
            slicePics = [
                tp.TaskPic(path + '\\%s' % s) for s in os.listdir(path)
            ]

            slices = [
                r.TargetSlice(s.pix, target, size=search_size)
                for s in slicePics
            ]
            s = slices[
                slice_index]  #********** TODO this is arbitrary; should be traditionally densest slice
            print('...DONE!\n')

            print('Starting density search...')
            locations = sim_density_search(choices, s.primary.ret,
                                           priority_queue_size)
            '''
            locations = []
            for i in xrange(len(choices)):
                locs = []
                for n in xrange(20):
                    locs.append((i,n))
                locations.append(locs)
            '''
            #print locations
            print('...DONE!\n')

            print('Starting rotational search...')
            primarySearch(choices, s, locations)
            print('...DONE!\n')

            sliceIm = slicePics[slice_index].im
            boxes = []
            box_index = 0
            for start in [s.primary.start, s.secondary.start]:
                end = start + np.array([s.size - 1, s.size - 1])
                boxes.append(([tuple(start),
                               tuple(end)], box_colors[box_index]))
                box_index += 1

            drawBoxes(sliceIm, boxes,
                      os.getcwd() + '\\%s\\%s' % (results_dir, target),
                      'slice_%d_regions.jpg' % slice_index)
            print('Writing results...')

            f.write('Regions identified in target slice:...\n\n')

            f.write('Primary region:\n')
            f.write('\t-Location in target slice: ' + str(s.primary.start) +
                    '\n')
            f.write('\t-Unrefined Density: ' +
                    str(s.primary.ret.getUnrefinedDensity()) + '\n')
            f.write('\t-Density: ' + str(s.primary.ret.getDensity()) + '\n')

            f.write('\nSecondary region:\n')
            f.write('\t-Location in target slice: ' + str(s.secondary.start) +
                    '\n')
            f.write('\t-Unrefined Density: ' +
                    str(s.secondary.ret.getUnrefinedDensity()) + '\n')
            f.write('\t-Density: ' + str(s.secondary.ret.getDensity()) + '\n')

            f.write('\nResults:...\n\n')

            writeResults(choices, s, f)
            print('...DONE!\n')

    end_t = time.time()

    print('\nTime elapsed: %f' % (end_t - start_t))
Esempio n. 9
0
def solve_problem(prob):
    start_t = time.time()
    cwd = os.path.join(problems_dir, prob)

    print('Initializing choices...')
    # for later problems (09 thru 15) where there are easel choices
    choices = [
        tp.TaskPic(os.path.join(cwd, choices_dir, c))
        for c in os.listdir(os.path.join(cwd, choices_dir))
    ]
    # for earlier problems (03 thru 08) where there are no easel choices
    #choices = [tp.TaskPic(os.path.join(cwd,'easel.jpg'))]
    #targets = [tp.TaskPic(os.getcwd() + '\\%s\\%s' % (targets_dir,t)) for t in os.listdir(targets_dir)]
    print('...DONE!\n')

    target_path = os.path.join(cwd, targets_dir)
    outfile_path = os.path.join(os.getcwd(), results_dir, prob)

    for target in os.listdir(target_path):
        # TODO identify slices automatically

        target_outfile_path = os.path.join(outfile_path, 'choice_%s' % target)
        target_infile_path = os.path.join(target_path, target)
        for c_slice in os.listdir(target_infile_path):
            slice_name = c_slice.split('.')[0]
            slice_path = os.path.join(target_outfile_path, slice_name)
            if not os.path.exists(slice_path):
                os.makedirs(slice_path)

            with open(os.path.join(slice_path, 'console_readout.txt'),
                      'w') as f:
                print('Target: %s\nSlice: %s\n' % (target, slice_name))

                slicePic = tp.TaskPic(os.path.join(target_infile_path,
                                                   c_slice))

                pix = slicePic.pix
                s = None

                # slice is too small for default search_size
                if search_size > min(pix.shape):
                    print('Using smaller template for this slice...')
                    s = r.Subslice(slicePic,
                                   prob,
                                   target,
                                   useTransparentPix=useTransparentPix,
                                   size=min(pix.shape) - 1,
                                   hn=hn,
                                   nRegions=3)
                else:
                    s = r.Subslice(slicePic,
                                   prob,
                                   target,
                                   useTransparentPix=useTransparentPix,
                                   template=template,
                                   nRegions=3)

                temp = s.template
                f.write('Using retina with following parameters:\n')
                f.write('\t-size: %d x %d\n' % (temp.size, temp.size))
                f.write('\t-number of rings: %d\n' % temp.nRings)
                f.write('\t-number of wedges: %d\n' % temp.nWedges)
                f.write('\t-blindspot_radius: %f\n\n' % temp.bs_radius)

                padded_choices = []
                # pads each choice with zeros just in case subslice is on edge
                for choice in choices:
                    cx, cy = choice.size()
                    start = s.size / 2
                    padded_pix = np.zeros((cx + s.size, cy + s.size),
                                          dtype=choice.pix.dtype)
                    padded_pix[start:start + cx, start:start + cy] = choice.pix

                    new_choice = choice.copy()
                    new_choice.pix = padded_pix
                    new_choice.update()

                    padded_choices.append(new_choice)

                print('Starting density search...')
                locations = sim_density_search(padded_choices, s.primary.ret,
                                               priority_queue_size, slice_path)
                '''
				locations = [[np.array([83,15])],
							 [np.array([1,15])],
							 [np.array([117,126])],
							 [np.array([129,100])]]
							 #[np.array([129,100])]]
				'''

                #print locations
                print('...DONE!\n')

                print('Starting rotational search...')
                s_flipped = s.flip()
                # sys.exit(0)
                primarySearch(padded_choices, s, s_flipped, locations)
                print('...DONE!\n')
                '''
				for slice in [s, s_flipped]:
					im = slice.taskpic.im
					name = slice.taskpic.fname.split('\\')[-1]
					boxes = []
					box_index = 0
					for start in [slice.primary.start,slice.secondary.start]:
						end = start + np.array([s.size-1,s.size-1])
						boxes.append(([tuple(start),tuple(end)],box_colors[box_index]))
						box_index += 1

					drawBoxes(im,boxes,slice_path,name)
				'''

                #sys.exit(1)

                sliceIm = slicePic.im
                boxes = []
                box_index = 0
                for start in [
                        s.primary.start, s.secondary.start, s.tertiary.start
                ]:
                    end = start + np.array([s.size - 1, s.size - 1])
                    boxes.append(([tuple(start),
                                   tuple(end)], box_colors[box_index]))
                    box_index += 1

                drawBoxes(sliceIm, boxes, slice_path, 'pst_regions.jpg')

                sliceImFlipped = s_flipped.taskpic.im
                boxes = []
                box_index = 0
                for start in [
                        s_flipped.primary.start, s_flipped.secondary.start,
                        s_flipped.tertiary.start
                ]:
                    end = start + np.array([s.size - 1, s.size - 1])
                    boxes.append(([tuple(start),
                                   tuple(end)], box_colors[box_index]))
                    box_index += 1

                drawBoxes(sliceIm, boxes, slice_path,
                          'pst_regions_flipped.jpg')
                print('Writing results...')

                f.write('Regions identified in %s:...\n\n' % slice_name)

                for name, region in [('Primary', s.primary), \
                      ('Secondary', s.secondary), \
                      ('Tertiary', s.tertiary)]:

                    f.write('%s region:\n' % name)
                    f.write('\t-Location in target slice: ' +
                            str(region.start) + '\n')
                    f.write('\t-Variance (within retinal rings): ' +
                            str(region.ret.getVar()) + '\n')
                    #f.write('\t-Unrefined Density: ' + str(s.primary.ret.getUnrefinedDensity()) + '\n')
                    f.write('\t-Density: ' + str(region.ret.getDensity()) +
                            '\n')

                f.write('\nResults:...\n\n')

                writeResults(padded_choices, s, s_flipped, f, slice_path)
                print('...DONE!\n')

    end_t = time.time()

    print('\nTime elapsed: %f' % (end_t - start_t))
Esempio n. 10
0
def solve_problem(prob):
	start_t = time.time()
	cwd = os.path.join(problems_dir, prob)

	print('Initializing choices...')
	# for later problems (09 thru 15) where there are easel choices
	#choices = [tp.TaskPic(os.path.join(cwd,choices_dir,c)) for c in os.listdir(os.path.join(cwd,choices_dir))]
	# for earlier problems (03 thru 08) where there are no easel choices
	choices = [tp.TaskPic(os.path.join(cwd,'easel.jpg'))]
	#targets = [tp.TaskPic(os.getcwd() + '\\%s\\%s' % (targets_dir,t)) for t in os.listdir(targets_dir)]
	print('...DONE!\n')

	target_path = os.path.join(cwd, targets_dir)
	outfile_path = os.path.join(os.getcwd(), results_dir, prob)

	for target in os.listdir(target_path):
		# TODO identify slices automatically

		target_outfile_path = os.path.join(outfile_path, target)
		if not os.path.exists(target_outfile_path):
			os.makedirs(target_outfile_path)

		with open(os.path.join(target_outfile_path,'console_readout.txt'), 'w') as f:
			print(target + ':\n')

			path = os.path.join(target_path, target)

			print('Initializing slices...')
			slicePics = [tp.TaskPic(os.path.join(path, s)) for s in os.listdir(path)]
			slice_index = np.random.randint(0,len(slicePics))   #********** TODO this is arbitrary; could use all of them

			pix = slicePics[slice_index].pix
			s = None

			print('\n\t....Slice %d chosen....\n' % slice_index)

			# slice is too small for default search_size
			if search_size > min(pix.shape):
				print('Using smaller template for this slice...')
				s = r.TargetSlice(pix,prob,target,size=min(pix.shape))
			else:
				s = r.TargetSlice(pix,prob,target,template=template)

			print('...DONE!\n')

			temp = s.template
			f.write('Using retina with following parameters:\n')
			f.write('\t-size: %d x %d\n' % (temp.size, temp.size))
			f.write('\t-number of rings: %d\n' % temp.nRings)
			f.write('\t-number of wedges: %d\n' % temp.nWedges)
			f.write('\t-blindspot_radius: %f\n\n' % temp.bs_radius)

			print('Starting density search...')
			locations = sim_density_search(choices,s.primary.ret,priority_queue_size)
			'''
			locations = []
			for i in range(len(choices)):
				locs = []
				for n in range(20):
					locs.append((i,n))
				locations.append(locs)
			'''
			#print locations
			print('...DONE!\n')

			print('Starting rotational search...')
			primarySearch(choices,s,locations)
			print('...DONE!\n')

			sliceIm = slicePics[slice_index].im
			boxes = []
			box_index = 0
			for start in [s.primary.start,s.secondary.start]:
				end = start + np.array([s.size-1,s.size-1])
				boxes.append(([tuple(start),tuple(end)],box_colors[box_index]))
				box_index += 1

			drawBoxes(sliceIm,boxes,target_outfile_path,'slice_%d_regions.jpg' % slice_index)
			print('Writing results...')

			f.write('Regions identified in target slice%d:...\n\n' % slice_index)

			f.write('Primary region:\n')
			f.write('\t-Location in target slice: ' + str(s.primary.start) + '\n')
			f.write('\t-Variance (within retinal rings): ' + str(s.primary.ret.getVar()) + '\n')
			#f.write('\t-Unrefined Density: ' + str(s.primary.ret.getUnrefinedDensity()) + '\n')
			f.write('\t-Density: ' + str(s.primary.ret.getDensity()) + '\n')

			f.write('\nSecondary region:\n')
			f.write('\t-Location in target slice: ' + str(s.secondary.start) + '\n')
			f.write('\t-Variance (within retinal rings): ' + str(s.secondary.ret.getVar()) + '\n')
			#f.write('\t-Unrefined Density: ' + str(s.secondary.ret.getUnrefinedDensity()) + '\n')
			f.write('\t-Density: ' + str(s.secondary.ret.getDensity()) + '\n')

			f.write('\nResults:...\n\n')

			writeResults(choices,s,f)
			print('...DONE!\n')

	end_t = time.time()

	print('\nTime elapsed: %f' % (end_t - start_t))