def hist_inters_and_col_model_exercises(model, bins = (10, 10, 10)):
    """
    Corresponds to the first exercise of this assignment. Prints a histogram of
    one image for the given colour model; calculates all histograms in the
    "database" of images; calculates and displays a table of intersections of
    all database histograms; calculates and displays a table of intersections of
    the database images against a selection of external images.

    """

    print '\nColour histogram and histogram intersection exercise\n'

    image_paths, stored_model = load_images(('db', 'ext'))
    image = set_model(mpimg.imread(image_paths[1][0] + image_paths[0][0][0]), out_model=model)
    plt.subplot(1, 1, 1)

    print '\nSo, we\'re going to build a 3d colour histogram.'
    raw_input('\nLet\'s have a look at the image in question:\n(Press enter)')
    plt.imshow(np.flipud(image))
    plt.show()

    print '\nNow let\'s calculate and view the corresponding histogram printout.'
    press_enter_and_wait()
    print col_hist(image, bins, model)

    print '\nNow we\'ll build a table of histogram intersections for all the'
    print 'images in our database'
    intersections_table(image_paths, bins, model)

    print '\nOk, next we\'ll build a table of intersections for database images'
    print 'against a selection of external images'
    intersections_table(image_paths, bins, model, with_ext = True)

    menu()
def colour_backproject(target, image, bins, model):
    """ 
    Implementation of "object location via histogram backprojection" algorithm
    in Swain and Ballard's 1990 paper. Uses OpenCV library Filter2D to carry out
    covolution.
    
    """

    print '\nFirst, we build the target\'s colour histogram:'
    press_enter_and_wait()
    target_h = col_hist(target, bins, model)
    print target_h

    print '\nNext, we build the image\'s colour histogram:'
    press_enter_and_wait()
    image_h = col_hist(image, bins, model)
    print image_h
    
    print '\nNow, we compute "ratio", the ratio of target/image histograms:'
    press_enter_and_wait()
    ratio = (target_h * 1.0) / image_h
    print ratio

    print '\nNext, we replace each pixel in the image with the value of the',
    print 'bin in "ratio" that the pixel\'s colour indexes (max value: 1).'
    press_enter_and_wait()
    b = np.empty(((image.shape)[0:2]), dtype = float)
    i = 0
    for row in image:
        j = 0
        for pixel in row:
            index = col2bin(pixel, bins, model)
            b[i][j] = min(ratio[index[0]][index[1]][index[2]], 1)
            j += 1
        i += 1
    print b

    print '\nOk, now to convolve a mask with b'
    press_enter_and_wait()
    b_conv = b
    radius = 40
    w = np.zeros((81,81), dtype = float)
    i = 0
    for row in w:
        j = 0
        for element in row:
            if (sqrt(pow((10-i),2)+pow((10-j),2)) < radius):
                w[i][j] = 1
            j += 1
        i += 1
    cv.Filter2D(cv.fromarray(b), cv.fromarray(b_conv), cv.fromarray(w), (-1, -1))
    b_conv = np.array(b_conv)
    print b_conv

    print '\nFinally, we find the location of the peak of the convolved image:'
    press_enter_and_wait()
    print b_conv

    return np.where(b_conv == b_conv.max()), b_conv
def intersections_table(image_paths, bins, model, with_ext = False):
    """ 
    Returns a table of intersections of database image histograms against
    themselves, or, if "with_ext" == "true", of database histograms against
    "external" image histograms.
    
    """

    print '\nStep 1: calculate histograms'
    press_enter_and_wait()
    db_histograms = []
    for img_name in image_paths[0][0]:
        image = set_model(mpimg.imread(image_paths[1][0]+img_name), out_model=model)
        db_histograms.append(col_hist(image, bins, model))
    ext_histograms = []
    if with_ext:
        for img_name in image_paths[0][1]:
            image = set_model(mpimg.imread(image_paths[1][1]+img_name), out_model=model)
            ext_histograms.append(col_hist(image, bins, model))
    else:
        ext_histograms = db_histograms

    print '\nStep 2: build table of intersections'
    press_enter_and_wait()
    intersections_table = [['I\\M ']]
    for name in image_paths[0][0]:
        intersections_table[0].append(name[0:4])
    image_names = image_paths[0][0]
    if with_ext:
        image_names = image_paths[0][1]
    for name in image_names:
        intersections_table.append([name[0:4]])
    i = 1
    for h1 in ext_histograms:
        for h2 in db_histograms:
            rounded_result = '%.2f'%round(histogram_intersect(h1, h2), 2)
            intersections_table[i].append(rounded_result)
        i += 1

    raw_input('\nA printout of the resulting table follows:\n(press enter)')
    for item in intersections_table[0]:
        print '%s '%item,
    print '\n',
    for row in intersections_table[1:]:
        for item in row:
            print '%s '%item,
        print '\n',