def full_demo_orient_field():
    """
    Estimates orientation field of a random print from FVC2002-1A, and
    displays the result as a vector field overlayed on the original print
    image a la Feng 2012.
    """
    img = data.FVC2002_1A.read_random_image()[0]
    orf = model.estimate_orientation(img, True)[:,:,0]

    # This will plot a red line in the direction of the detected orientation
    # for each block, overlayed on the original print, just like the figures
    # in Chen 2011. This should probably be a utility function.
    for ii in range(orf.shape[0]):
        for jj in range(orf.shape[1]):
            i_base = 16*ii + 8
            j_base = 16*jj + 8
            angle = orf[ii][jj]

            if angle == np.nan:
                continue

            else:
                offset = cmath.rect(8.0, angle)
                plt.plot([j_base-offset.imag, j_base+offset.imag],
                    [i_base-offset.real, i_base+offset.real],
                    color='r')

    plt.imshow(img, cmap = "gray", interpolation = "nearest")
    plt.show()
def show_generated_img(_):
    global canvas
    global olpped_img
    global olpped_pht
    global show_step
    global demo_dat
    global orf

    if show_step == "SHOW_OVERLAPPED":
        print "SHOW OVERLAPPED GEN"
        lhs_img_src = src_rgbt_imgs['CURLHS']
        rhs_img_src = src_rgbt_imgs['CURRHS']

        if (lhs_img_src == 'NONE') or (rhs_img_src == 'NONE'):
            print "LEAVING EARLY FROM SHOW GEN IMG"
            return None

        canvas.itemconfig(lhs_img_id, state=TK.HIDDEN)
        canvas.itemconfig(rhs_img_id, state=TK.HIDDEN)
        gen_img_lhs = PIL.Image.new('L', (CANVAS_WIDTH, CANVAS_HEIGHT), 255)
        # olpped_img_data["gen_img_lhs"] = gen_img_lhs
        gen_img_rhs = PIL.Image.new('L', (CANVAS_WIDTH, CANVAS_HEIGHT), 255)
        # olpped_img_data["gen_img_rhs"] = gen_img_rhs
        lhs_img = src_gray_imgs['CURLHS']
        # olpped_img_data["lhs_img"] = lhs_img
        rhs_img = src_gray_imgs['CURRHS']
        # olpped_img_data["rhs_img"] = rhs_img
        gen_img_lhs.paste(lhs_img, (50, 0))
        gen_img_rhs.paste(rhs_img, (CANVAS_WIDTH-IMG_WIDTH-50, 0))

        eval_exp = "convert(min(a,b), 'L')"
        olpped_img = PIL.ImageMath.eval(eval_exp, a=gen_img_lhs, b=gen_img_rhs)
        demo_dat['olpped_img'] = olpped_img
                    # a=gen_img_lhs.convert('1', dither=0),\
                    # b=gen_img_rhs.convert('1', dither=0))
        olpped_pht = PIL.ImageTk.PhotoImage(olpped_img)
        canvas.itemconfig(olpped_img_id, image=olpped_pht, state=TK.NORMAL)


        prnt_img_lhs_ary = np.array(gen_img_lhs, copy=True)
        demo_dat['prnt_img_lhs_ary'] = prnt_img_lhs_ary
        prnt_img_rhs_ary = np.array(gen_img_rhs, copy=True)
        demo_dat['prnt_img_rhs_ary'] = prnt_img_rhs_ary
        demo_dat['prnt_layers'] =  \
                     np.dstack((prnt_img_lhs_ary, prnt_img_rhs_ary))
        reg_lhs_prnt = utils.extract_region_chull(prnt_img_lhs_ary)
        demo_dat['reg_lhs_prnt'] = reg_lhs_prnt
        reg_rhs_prnt = utils.extract_region_chull(prnt_img_rhs_ary)
        demo_dat['reg_rhs_prnt'] = reg_rhs_prnt

        plhs = PIL.Image.fromarray(reg_lhs_prnt.astype(np.uint8) * 255, \
                                    mode='L')
        prhs = PIL.Image.fromarray(reg_rhs_prnt.astype(np.uint8) * 255, \
                                    mode='L')

        prnt_reg_img_rgb = PIL.Image.merge('RGB', [plhs,prhs,olpped_img])
        demo_dat['prnt_reg_img_rgb'] = prnt_reg_img_rgb.copy()
        prnt_reg_pht_rgb = PIL.ImageTk.PhotoImage(prnt_reg_img_rgb.copy())
        # canvas.itemconfig(olpped_img_id, image=prnt_reg_pht_rgb)
        show_step = "PRINT_REGIONS"


    ## ==== SHOW PRINT REGIONS
    elif show_step == "PRINT_REGIONS":
        print "SHOW PRINT_REGIONS"
        prnt_reg_pht_rgb = PIL.ImageTk.PhotoImage(demo_dat['prnt_reg_img_rgb'])
        demo_dat['prnt_reg_pht_rgb'] = prnt_reg_pht_rgb
        canvas.itemconfig(olpped_img_id, image=prnt_reg_pht_rgb)

        olpped_ary = np.array(demo_dat['olpped_img'], dtype=np.uint8, \
                              copy=True)

        show_step = "OR_FIELD"


    elif show_step == "OR_FIELD":
        either_reg = demo_dat["reg_rhs_prnt"] | demo_dat["reg_lhs_prnt"]
        tka_frame = TK.Frame(root, bd=-2, background="white", padx=0, pady=0)
        tka_frame.grid(column=1, row=0, rowspan=5, sticky=TK.N+TK.S+TK.E+TK.W)
        demo_dat['tka_frame'] = tka_frame

        fig = Figure(figsize=(7, 5.5), facecolor="w", frameon=False, \
                     edgecolor='w')
        demo_dat['fig'] = fig
        ax = fig.add_axes((0,0,1,1), frameon=False, axis_bgcolor='w',\
                            axisbg='w')
        demo_dat['ax'] = ax
        tkagg = FigureCanvasTkAgg(fig, master=tka_frame)
        demo_dat['tkagg'] = tkagg
        tkagg.get_tk_widget().place(relx=0.5, rely=0.5, anchor=TK.CENTER)
        tkagg.get_tk_widget().config(height=(CANVAS_HEIGHT+100), \
                                     width=(CANVAS_WIDTH+150), bd=-2, \
                                     bg='white', selectborderwidth=-2,
                                     highlightthickness=0)
        ax.axis('off')
        fig.patch.set_visible(False)

        canvas.delete(TK.ALL)
        # canvas.place(relx=0.5, rely=0.5, anchor=TK.CENTER)

        olpped_ary = np.array(demo_dat['olpped_img'], dtype=np.uint8, \
                      copy=True)
        ax.imshow(olpped_ary, cmap="gray", interpolation="nearest")
        either_reg = model._blockify_print_region(either_reg)
        if 'orf' not in globals().keys():
            orf = model.estimate_orientation(olpped_ary)

        # demo_dat['orf'] = orf
        for ii in range(orf.shape[0]):
            for jj in range(orf.shape[1]):

                angle = orf[ii, jj, 0]
                if angle == np.nan or not (either_reg[ii,jj]):
                    continue

                i_base = 16*ii + 8
                j_base = 16*jj + 8
                ioffst = 8*np.sin(angle+cmath.pi/2)
                joffst = 8*np.cos(angle+cmath.pi/2)
                ax.plot([j_base-joffst, j_base+joffst],
                         [i_base-ioffst, i_base+ioffst],
                         color='b', lw=1.5)

        for ii in range(orf.shape[0]):
            for jj in range(orf.shape[1]):


                angle = orf[ii, jj, 1]
                if angle == np.nan or not (either_reg[ii,jj]):
                    continue

                i_base = 16*ii + 8
                j_base = 16*jj + 8
                ioffst = 8*np.sin(angle+cmath.pi/2)
                joffst = 8*np.cos(angle+cmath.pi/2)
                ax.plot([j_base-joffst, j_base+joffst],
                         [i_base-ioffst, i_base+ioffst],
                         color='r', lw=1.5)

        ax.xaxis.set_visible(False)
        ax.yaxis.set_visible(False)
        tkagg.show()

        show_step = "RELAX_LABEL_PROC"

    if show_step == "RELAX_LABEL_PROC":
        # orf = demo_dat['orf']
        # oc = np.copy(orf)

        pl_lhs = model._blockify_print_region(\
                 np.array(demo_dat["reg_lhs_prnt"], dtype=np.bool, copy=True))
        pl_rhs = model._blockify_print_region( \
                 np.array(demo_dat["reg_rhs_prnt"], dtype=np.bool, copy=True))

        p_lyrs = np.dstack((pl_lhs, pl_rhs))
        tkagg = demo_dat['tkagg']
        ax = demo_dat['ax']

        print "orf.shape:" + str(orf.shape)
        print "orf.dtype:" + str(orf.dtype)
        print "p_lyrs.shape:" + str(p_lyrs.shape)
        print "p_lyrs.dtype:" + str(p_lyrs.dtype)
        _ = model.relax_label_two(orf, p_lyrs, tkagg, view_axis=ax)