I have two functions declared in my program, and i want to use the variables in another function to display the matched images. My code is:

def messageWindow():
    win = Toplevel()
    path = 'C:\Users\HP\Desktop\dataset'
    COLUMNS = 12
    image_count = 0
    for infile in glob.glob(os.path.join(path, '*.jpg')):
        image_count += 1
        r, c = divmod(image_count, COLUMNS)
        im = Image.open(infile)
        resized = im.resize((100, 100), Image.ANTIALIAS)
        tkimage = ImageTk.PhotoImage(resized)
        myvar = Label(win, image=tkimage)
        myvar.image = tkimage
        myvar.grid(row=r, column=c)
    i=0
    cont_list = list()
    ene_list = list()
    homo_list = list()
    cor_list = list()
    dis_list = list()
    B_mean = list()
    G_mean = list()
    R_mean = list()
    piclist = list()
    graylist = list()
    resizelist = list()
    eq_graylist = list()

    for infile in glob.glob(os.path.join(path,'*.jpg')):
        imge = cv2.imread(infile)
        arr = array(imge)
        piclist.append(imge)

        g_img = cv2.imread(infile,0)
        gray_re_img = cv2.resize(g_img,(256,256))
        graylist.append(gray_re_img)

        equ = cv2.equalizeHist(gray_re_img)
        eq_graylist.append(equ)

        re_img = cv2.resize(imge,(256,256))
        resizelist.append(imge)
        i = i + 1

    for infiles in glob.glob(os.path.join(path,'*.jpg')):
        img = cv2.imread(infiles)
        blue, green, red = cv2.split(img)
        total = img.size
        B = sum(blue) / total
        G = sum(green) / total
        R = sum(red) / total
        B_mean.append(B)
        G_mean.append(G)
        R_mean.append(R)

        im = skimage.io.imread(infile, as_grey=True)
        im = skimage.img_as_ubyte(im)
        im /= 32
        g = skimage.feature.greycomatrix(im, [1], [0], levels=8, symmetric=False, normed=True)
        cont = skimage.feature.greycoprops(g, 'contrast')[0][0]
        cont_list.append(cont)
        ene = skimage.feature.greycoprops(g, 'energy')[0][0]
        ene_list.append(ene)
        homo = skimage.feature.greycoprops(g, 'homogeneity')[0][0]
        homo_list.append(homo)
        cor = skimage.feature.greycoprops(g, 'correlation')[0][0]
        cor_list.append(cor)
        dis = skimage.feature.greycoprops(g, 'dissimilarity')[0][0]
        dis_list.append(dis)

    feature_matrix_db = zip( B_mean , G_mean , R_mean, cont_list , ene_list , homo_list , cor_list, dis_list)
    blue2.set(B_mean)
    green2.set(G_mean)
    red2.set(R_mean)
    con2.set(cont_list)
    ene2.set(ene_list)
    homo2.set(homo_list)
    corr2.set(cor_list)
    diss2.set(dis_list)        
    return(feature_matrix_db,resizelist)

def OPEN():
    path=tkFileDialog.askopenfilename(filetypes=[("Image File",'.jpg')])
    custName.set(path)
    im = Image.open(path)
    resized = im.resize((200, 200),Image.ANTIALIAS)
    tkimage = ImageTk.PhotoImage(resized)
    myvar=Label(root,image = tkimage)
    myvar.image = tkimage
    myvar.pack()
    myvar.place(x = 30, y = 100) 
    graylist1 = list()
    resizelist1 = list()
    eq_graylist1 = list()
    cont_list1 = list()
    ene_list1 = list()
    homo_list1 = list()
    cor_list1 = list()
    B_mean1 = list()
    G_mean1 = list()
    R_mean1 = list()
    dis_list1 = list()

    imge = cv2.imread(path)
    arr = array(imge)
    g_img = cv2.imread(path,0)
    gray_re_img = cv2.resize(g_img,(256,256))
    graylist1.append(gray_re_img)

    equ = cv2.equalizeHist(gray_re_img)
    eq_graylist1.append(equ)

    re_img = cv2.resize(imge,(256,256))
    resizelist1.append(re_img)

    blue, green, red = cv2.split(re_img)
    total = re_img.size
    B = sum(blue) / total
    G = sum(green) / total
    R = sum(red) / total
    B_mean1.append(B)
    G_mean1.append(G)
    R_mean1.append(R)

    im = skimage.io.imread(path, as_grey=True)
    im = skimage.img_as_ubyte(im)
    im /= 32
    g = skimage.feature.greycomatrix(im, [1], [0], levels=8, symmetric=False, normed=True)
    cont = skimage.feature.greycoprops(g, 'contrast')[0][0]
    cont_list1.append(cont)
    ene = skimage.feature.greycoprops(g, 'energy')[0][0]
    ene_list1.append(ene)
    homo = skimage.feature.greycoprops(g, 'homogeneity')[0][0]
    homo_list1.append(homo)
    cor = skimage.feature.greycoprops(g, 'correlation')[0][0]
    cor_list1.append(cor)
    dis = skimage.feature.greycoprops(g, 'dissimilarity')[0][0]
    dis_list1.append(dis)

    feature_matrix_ip = zip( B_mean1 , G_mean1 , R_mean1, cont_list1 , ene_list1 , homo_list1 , cor_list1 , dis_list1)
    blue1.set(B_mean1)
    green1.set(G_mean1)
    red1.set(R_mean1)
    con1.set(cont_list1)
    ene1.set(ene_list1)
    homo1.set(homo_list1)
    corr1.set(cor_list1)
    diss1.set(dis_list1)
    return(feature_matrix_ip)

def result():
    COLUMNS = 12
    image_count = 0
    resultlist_key = []
    result_list = list()
    i = 0
    a_list = list()
    b_list = list()
    a_list.append(feature_matrix_ip)
    while i < 70:
        b_list.append(feature_matrix_db[i])
        dist = distance.euclidean(a_list,b_list[i])
        result_list.append(dist)
        resultlist_key = OrderedDict(sorted(enumerate(result_list),key=lambda x: x[0])).keys()
        i = i + 1 

    res_lst_srt = {'values': result_list,'keys':resultlist_key}
    res_lst_srt['values'], res_lst_srt['keys'] = zip(*sorted(zip(res_lst_srt['values'], res_lst_srt['keys'])))
    key = res_lst_srt['keys']

    for i1,val in enumerate(key):
        if i1 < 4:
            image_count += 1
            r, c = divmod(image_count, COLUMNS)
            img = cv2.imread(resizelist[val])
            im = Image.open(img)
            tkimage = ImageTk.PhotoImage(im)
            myvar1 = Label(win, image=tkimage)
            myvar1.image = tkimage
            myvar1.grid(row=r, column=c)

I want to use the variables from messageWindow() and OPEN() into result(), when i tried this out, then i get this error:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Enthought\Canopy32\App\appdata\canopy-1.0.3.1262.win-x86\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "D:\6th sem\Major project\Code\frame.py", line 198, in result
im = Image.open(resizelist[val])
File "E:\Canopy\System\lib\site-packages\PIL\Image.py", line 1956, in open
prefix = fp.read(16)
AttributeError: 'numpy.ndarray' object has no attribute 'read'

So, can any one help me to solve this problem?

Thanks in advance!

Can you please post the code you are using to call each of the three functions, and especially the section where the error is arising?

Also, who originally wrote this code? It involves some moderately sophisticated techniques, and look it over, I would expect that anyone who knows enough Python (and programming in general) t write these functions would already know the answer to you question.

Anyway... while there is no way to use a local variable that is in one function inside another directly, there are a few different options for sharing variables, or at least values. The first, and least advisable, is to use global functions rather than local ones:

my_global = []

def my_func():
   global my_global
    # ... and so on

This would allow the functions free access to the variables, but it is poor design, as it binds the different functions too closely, and would allow any function access to the variables.

The second solution is to pass the values to result() as function arguments; this would be the most obvious solution, as the other two functions are in fact returning the values you want.

def result(feature_matrix_ip, feature_matrix_db):
    # the rest of the function

ip, rszlist = messageWindow()
db = OPEN()
results(ip, db)

However, that is only an option if you can change the function's signature this way. Finally, you change them from free functions to methods in a class, though you'd have to know more about classes than you seem to in order to do that. I can explain it in more detail if you would like, though, as it would have most of the advantages of globals without as many disadvantages.

I don't see the error line in the code you posted either, but in any case in the line

im = Image.open(resizelist[val])

resizelist is used to to store images throughout the code and not the file names which are necessary for Image.open(). A simple print statement should help you understand the problem, so if you print val, type(resizelist[val]), and resizelist[val] if you want, it will show that it is not a file name, based on the error message provided.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.