Beispiel #1
0
    def test_kw(self):
        TEST_JPG = "Tests/images/hopper.jpg"
        TEST_PNG = "Tests/images/hopper.png"
        im1 = Image.open(TEST_JPG)
        im2 = Image.open(TEST_PNG)
        with open(TEST_PNG, 'rb') as fp:
            data = fp.read()
        kw = {"file": TEST_JPG, "data": data}

        # Test "file"
        im = ImageTk._get_image_from_kw(kw)
        self.assert_image_equal(im, im1)

        # Test "data"
        im = ImageTk._get_image_from_kw(kw)
        self.assert_image_equal(im, im2)

        # Test no relevant entry
        im = ImageTk._get_image_from_kw(kw)
        self.assertIsNone(im)
Beispiel #2
0
    def test_photoimage(self):
        for mode in TK_MODES:
            # test as image:
            im = hopper(mode)

            # this should not crash
            im_tk = ImageTk.PhotoImage(im)

            self.assertEqual(im_tk.width(), im.width)
            self.assertEqual(im_tk.height(), im.height)

            reloaded = ImageTk.getimage(im_tk)
            self.assert_image_equal(reloaded, im.convert("RGBA"))
Beispiel #3
0
    def create_tool_bar(self):
        #Barra de herramientas
        myTool = Frame(self.ventana)

        #Botones de la barra de herramientas
        imgOpen = Image.open(self.dir_os + '/assets/open.png')
        imgOpen = imgOpen.resize((20, 20), Image.ANTIALIAS)
        imgOpen = ImageTk.PhotoImage(imgOpen)
        OpenBtn = Button(myTool, image=imgOpen, command=self.open_file)
        OpenBtn.image = imgOpen
        OpenBtn.pack(side=LEFT, padx=2, pady=2)

        imgFile = Image.open(self.dir_os + '/assets/file.png')
        imgFile = imgFile.resize((20, 20), Image.ANTIALIAS)
        imgFile = ImageTk.PhotoImage(imgFile)
        FileBtn = Button(myTool, image=imgFile, command=self.new_file)
        FileBtn.image = imgFile
        FileBtn.pack(side=LEFT, padx=2, pady=2)

        imgSave = Image.open(self.dir_os + '/assets/save.png')
        imgSave = imgSave.resize((20, 20), Image.ANTIALIAS)
        imgSave = ImageTk.PhotoImage(imgSave)
        SaveBtn = Button(myTool, image=imgSave, command=self.save_as)
        SaveBtn.image = imgSave
        SaveBtn.pack(side=LEFT, padx=2, pady=2)

        imgSearch = Image.open(self.dir_os + '/assets/search.png')
        imgSearch = imgSearch.resize((20, 20), Image.ANTIALIAS)
        imgSearch = ImageTk.PhotoImage(imgSearch)
        SearchBtn = Button(myTool, image=imgSearch, command=self.find_popup)
        SearchBtn.image = imgSearch
        SearchBtn.pack(side=LEFT, padx=2, pady=2)

        imgDebug = Image.open(self.dir_os + '/assets/debug.png')
        imgDebug = imgDebug.resize((20, 20), Image.ANTIALIAS)
        imgDebug = ImageTk.PhotoImage(imgDebug)
        DebugBtn = Button(myTool, image=imgDebug, command=self.open_file)
        DebugBtn.image = imgDebug
        DebugBtn.pack(side=RIGHT, padx=2, pady=2)

        imgExecute = Image.open(self.dir_os + '/assets/execute.png')
        imgExecute = imgExecute.resize((20, 20), Image.ANTIALIAS)
        imgExecute = ImageTk.PhotoImage(imgExecute)
        ExecuteBtn = Button(myTool,
                            image=imgExecute,
                            command=self.ejecutar_codigo)
        ExecuteBtn.image = imgExecute
        ExecuteBtn.pack(side=RIGHT, padx=2, pady=2)

        imgAbout = Image.open(self.dir_os + '/assets/about.png')
        imgAbout = imgAbout.resize((20, 20), Image.ANTIALIAS)
        imgAbout = ImageTk.PhotoImage(imgAbout)
        AboutBtn = Button(myTool, image=imgAbout, command=self.popup_about)
        AboutBtn.image = imgAbout
        AboutBtn.pack(side=LEFT, padx=2, pady=2)

        imgClose = Image.open(self.dir_os + '/assets/close.png')
        imgClose = imgClose.resize((20, 20), Image.ANTIALIAS)
        imgClose = ImageTk.PhotoImage(imgClose)
        CloseBtn = Button(myTool, image=imgClose, command=self.delete_tab)
        CloseBtn.image = imgClose
        CloseBtn.pack(side=LEFT, padx=2, pady=2)

        imgClear = Image.open(self.dir_os + '/assets/clear.png')
        imgClear = imgClear.resize((20, 20), Image.ANTIALIAS)
        imgClear = ImageTk.PhotoImage(imgClear)
        ClearBtn = Button(myTool, image=imgClear, command=self.clear_consola)
        ClearBtn.image = imgClear
        ClearBtn.pack(side=LEFT, padx=2, pady=2)

        imgAst = Image.open(self.dir_os + '/assets/ast.png')
        imgAst = imgAst.resize((20, 20), Image.ANTIALIAS)
        imgAst = ImageTk.PhotoImage(imgAst)
        AstBtn = Button(myTool, image=imgAst, command=self.compilar_AST_png)
        AstBtn.image = imgAst
        AstBtn.pack(side=LEFT, padx=2, pady=2)

        myTool.pack(side=TOP, fill=X)
Beispiel #4
0
def Demo(options):
    assert len(options) > 0
    # 初始化
    root = Tk()
    root.title('视频下载器V1.3——公众号:Charles的皮卡丘')
    root.resizable(False, False)
    root.geometry('600x375+400+120')
    image_path = './bgimgs/bg1_demo.jpg'
    bgimg = Image.open(image_path)
    bgimg = ImageTk.PhotoImage(bgimg)
    lb_bgimg = Label(root, image=bgimg)
    lb_bgimg.grid()
    # Menu
    menubar = Menu(root)
    filemenu = Menu(menubar, tearoff=False)
    filemenu.add_command(label='退出',
                         command=lambda: stopDemo(root),
                         font=('楷体', 10))
    menubar.add_cascade(label='文件', menu=filemenu)
    filemenu = Menu(menubar, tearoff=False)
    filemenu.add_command(label='关于作者', command=ShowAuthor, font=('楷体', 10))
    menubar.add_cascade(label='更多', menu=filemenu)
    root.config(menu=menubar)
    # Label组件(标题)
    lb_title1 = Label(root, text='视频下载', font=('楷体', 15), bg='white')
    lb_title1.place(relx=0.5, rely=0.05, anchor=CENTER)
    lb_title2 = Label(root, text='视频转换', font=('楷体', 15), bg='white')
    lb_title2.place(relx=0.5, rely=0.55, anchor=CENTER)
    # 视频下载部分:
    # 	Label+Entry组件(视频地址)
    lb_videourl = Label(root, text='视频地址:', font=('楷体', 10), bg='white')
    lb_videourl.place(relx=0.1, rely=0.15, anchor=CENTER)
    en_videourl_var = StringVar()
    en_videourl = Entry(root,
                        textvariable=en_videourl_var,
                        width=55,
                        fg='gray',
                        relief=GROOVE,
                        bd=3)
    en_videourl.insert(
        0, 'http://study.163.com/course/courseMain.htm?courseId=1003842018')
    en_videourl.place(relx=0.49, rely=0.15, anchor=CENTER)
    # 	Label+OptionMenu组件(搜索平台)
    lb_engine = Label(root, text='搜索平台:', font=('楷体', 10), bg='white')
    lb_engine.place(relx=0.1, rely=0.25, anchor=CENTER)
    op_engine_var = StringVar()
    op_engine_var.set(options[0])
    op_engine = OptionMenu(root, op_engine_var, *options)
    op_engine.place(relx=0.26, rely=0.25, anchor=CENTER)
    # 	Button组件(下载与退出)
    bt_download = Button(
        root,
        text='下载视频',
        bd=2,
        width=15,
        height=2,
        command=lambda: downloader(options, op_engine_var, en_videourl_var),
        font=('楷体', 10))
    bt_download.place(relx=0.26, rely=0.38, anchor=CENTER)
    bt_quit = Button(root,
                     text='退出程序',
                     bd=2,
                     width=15,
                     height=2,
                     command=lambda: stopDemo(root),
                     font=('楷体', 10))
    bt_quit.place(relx=0.52, rely=0.38, anchor=CENTER)
    # 视频转换部分:
    # 	Label+Entry+Button组件(视频路径)
    lb_originvideo = Label(root, text='视频路径:', font=('楷体', 10), bg='white')
    lb_originvideo.place(relx=0.1, rely=0.65, anchor=CENTER)
    en_originvideo_var = StringVar()
    en_originvideo = Entry(root,
                           textvariable=en_originvideo_var,
                           width=55,
                           fg='gray',
                           relief=GROOVE,
                           bd=3)
    en_originvideo.insert(0, '请输入/选择视频路径')
    en_originvideo.place(relx=0.49, rely=0.65, anchor=CENTER)
    bt_choice = Button(root,
                       text='打开',
                       bd=1,
                       width=5,
                       height=1,
                       command=lambda: ChoiceVideo(en_originvideo),
                       font=('楷体', 10))
    bt_choice.place(relx=0.86, rely=0.65, anchor=CENTER)
    # 	Label+OptionMenu组件(目标格式)
    lb_tarformat = Label(root, text='目标格式:', font=('楷体', 10), bg='white')
    lb_tarformat.place(relx=0.1, rely=0.75, anchor=CENTER)
    options_format = ['mp4', 'flv', 'avi']
    op_tarformat_var = StringVar()
    op_tarformat_var.set(options_format[0])
    op_tarformat = OptionMenu(root, op_tarformat_var, *options_format)
    op_tarformat.place(relx=0.22, rely=0.75, anchor=CENTER)
    # 	Button组件(视频转换)
    bt_transfer = Button(
        root,
        text='开始转换',
        bd=2,
        width=15,
        height=2,
        command=lambda: converter(en_originvideo_var, op_tarformat_var),
        font=('楷体', 10))
    bt_transfer.place(relx=0.52, rely=0.75, anchor=CENTER)
    root.mainloop()
Beispiel #5
0
from tkinter import *
from PIL import Image, ImageTk

from tkinter import colorchooser

IMAGE_PATH = 'background.jpg'
WIDTH, HEIGTH = 500, 500

root = Tk()
root.geometry('{}x{}+100+100'.format(WIDTH, HEIGTH))

canvas = Canvas(root, width=WIDTH, height=HEIGTH)
canvas.pack()

img = ImageTk.PhotoImage(
    Image.open(IMAGE_PATH).resize((WIDTH, HEIGTH), Image.ANTIALIAS))
canvas.background = img  # Keep a reference in case this code is put in a function.
bg = canvas.create_image(0, 0, anchor=NW, image=img)


def colour():
    colour = colorchooser.askcolor()
    bg = colour[1]
    cBtn.config(bg=bg)
    button.config(bg=bg)
    lab.config(bg=bg)
    print(colour[1])


# Put a tkinter widget on the canvas.
button = Button(root, text="Start", relief=GROOVE)
Beispiel #6
0
def refesh_persone():
    global all_person, person, selected_persone, max_in_page, listbox_faces, frame5, frame6, page_win_person_main, panel, present
    #page_win_person_main = read_page()
    if present == False:
        panel.destroy()
    if selected_persone:
        e_name.grid(row=0, column=1, padx=20)
        l_name.grid(row=0, column=0, padx=20)
        but_save.grid(row=0, column=2, padx=20)

        print("page_win_person", page_win_person_main)
        e_name.delete(0, END)
        e_name.insert(END, person.name)

        but_step1 = Button(frame5,
                           text='<<',
                           command=lambda i=-1: page_change(i)).grid(
                               row=5, column=0, sticky=(N, W, E, S))
        but_step2 = Button(frame5,
                           text='>>',
                           command=lambda i=1: page_change(i)).grid(
                               row=6, column=0, sticky=(N, W, E, S))
        but_cut = Button(frame5, text='Вырезать',
                         command=onCut).grid(row=2,
                                             column=0,
                                             sticky=(N, W, E, S))
        but_paste = Button(frame5, text='Вставить',
                           command=onPaste).grid(row=1,
                                                 column=0,
                                                 sticky=(N, W, E, S))

        row_c = 0
        col_c = 0
        c = 0
        listbox_faces.delete(0, END)

        list = frame6.grid_slaves()
        for l in list:
            l.destroy()

        count_faces = 0
        for face in person.face:
            # print(page_win_person*max_in_page, page_win_person*max_in_page+max_in_page)

            if count_faces >= page_win_person_main * max_in_page and count_faces < page_win_person_main * max_in_page + max_in_page:
                try:
                    listbox_faces.insert(END, face)
                    frame = cv2.imread(face.image_path)
                    height, width = frame.shape[:-1]
                    if height > 0 and width > 0:
                        frame = cv2.resize(frame, (115, 115),
                                           interpolation=cv2.INTER_CUBIC)
                        cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
                        img = Image.fromarray(cv2image)
                        # imgtk = ImageTk.PhotoImage(image=img)

                        # img = ImageTk.PhotoImage(Image.open(face.image_path))
                        img = ImageTk.PhotoImage(image=img)

                        #print(face.image_path, c)
                        # panel = Label(t, image=img)

                        # panel = Label(t, text = face.image_path)

                        panel = Button(frame6,
                                       image=img,
                                       command=lambda i=c: onClick(i))
                        # panel = Button(t, image=img, text=c)
                        # panel.bind('<Button-1>', push_image)

                        panel.image = img
                        panel.grid(row=row_c,
                                   column=col_c,
                                   sticky=(N, W, E, S))
                        col_c += 1
                        if col_c > 6:
                            col_c = 0
                            row_c += 1
                        c += 1
                except:
                    print("ошибка вывода картинки", face.image_path)
                    db.del_face(face)
            count_faces += 1

        listbox_faces.grid(row=0, column=0, padx=10, pady=10)
Beispiel #7
0
def button1():
    global headimage#大头照
    global halfimage#半身照
    name, idnum = getnameandID()
    if idnum=="IDCardNo'].value='":
        idnum = simpledialog.askstring('手动输入身份证', '无法读取,请输入', initialvalue="请输入身份证号码")
    ref, frame = capture.read()
    cvimage = cv.cvtColor(frame, cv.COLOR_BGR2RGBA)
    face_cascade = cv.CascadeClassifier('./config.xml')
    faces = face_cascade.detectMultiScale(cvimage, 1.15,3) #人脸检测
    try:
        x=faces[0][0]
        y=faces[0][1]
        w=faces[0][2]
        h=faces[0][3]
        # 抓取1寸照
        headimage = frame[y - int(h / 2): y + h + int(h * 0.6), x - int(w / 3): x + w + int(w / 3)]
        headimage = cv.resize(headimage, (206, 289), interpolation=cv.INTER_CUBIC)
        cv.imencode('.jpg', headimage)[1].tofile(lb1["text"] + '/' + idnum + '.jpg')  # 支持中文路径

        #打开图片调亮度
        headimg=Image.open(lb1["text"] + '/' + idnum + '.jpg')
        # 获取亮度调整期
        image_bright = ImageEnhance.Brightness(headimg)
        # 亮度增强, 参数大于1增强
        headimg = image_bright.enhance(brparam)

        # 获取色彩调整期
        image_color = ImageEnhance.Color(headimg)
        # 色彩, 参数大于1增强
        headimg = image_color.enhance(clparam)

        # 对比度调解
        headimg = headimg.point(lambda i: i * lmparam)
        #保存图片
        headimg.save(lb1["text"] + '/' + idnum + '.jpg',quality=95, subsampling=0)




        # 抓取半身照
        halfimage = frame[y - int(h * 0.8): y + h + int(h *3), x - int(w * 1.6): x + w + int(w * 1.6)]
        halfimage = cv.resize(halfimage, (413, 500), interpolation=cv.INTER_CUBIC)
        cv.imencode('.jpg', halfimage)[1].tofile(lb2["text"]+ '/' + idnum + '.jpg')  # 支持中文路径

        # 打开图片调亮度
        halfimg = Image.open(lb2["text"] + '/' + idnum + '.jpg')
        # 获取亮度调整期
        image_bright = ImageEnhance.Brightness(halfimg)
        # 亮度增强, 参数大于1增强
        halfimg = image_bright.enhance(brparam)

        # 获取色彩调整期
        image_color = ImageEnhance.Color(halfimg)
        # 色彩, 参数大于1增强
        halfimg = image_color.enhance(clparam)

        # 对比度调解
        halfimg = halfimg.point(lambda i: i * lmparam)
        # 保存图片
        halfimg.save(lb2["text"] + '/' + idnum + '.jpg', quality=95, subsampling=0)



    except:
        pass
    #显示身份证号码和姓名
    ft =tkFont.Font(family='楷体', size=10, weight=tkFont.BOLD)
    lb=Label(top, text=name+":"+idnum, font=ft, width=30, height=2,fg="red")
    lb.place(x=170, y=490)
    #预览1寸照片
    global img
    global tkImage1
    img = Image.open(lb1["text"]+'/'+idnum+".jpg")  # 打开图片
    tkImage1 = ImageTk.PhotoImage(image=img)
    canvas1.create_image(0, 0, anchor=NW, image=tkImage1)

    # 预览半身照片
    global img2
    global tkImage11
    img2 = Image.open(lb2["text"]+'/'+idnum+".jpg")  # 打开图片
    tkImage11 = ImageTk.PhotoImage(image=img2)
    canvas2.create_image(0, 0, anchor=NW, image=tkImage11)
    top.update()
    image = Image.fromarray(image)
    imgtk = ImageTk.PhotoImage(image=image)
    detection.config(image=imgtk)
    detection.image = imgtk


main = Tk()
main.title(title_name)
main.geometry()

# load the input image and convert it from BGR to RGB
read_image = cv2.imread(image_file)
(height, width) = read_image.shape[:2]
image = cv2.cvtColor(read_image, cv2.COLOR_BGR2RGB)
image = Image.fromarray(image)
imgtk = ImageTk.PhotoImage(image=image)

label = Label(main, text=title_name)
label.config(font=("Courier", 18))
label.grid(row=0, column=0, columnspan=4)

fileLabel = Label(main, text=image_file)
fileLabel.grid(row=1, column=0, columnspan=2)
Button(main, text="File Select", height=2,
       command=lambda: selectFile()).grid(row=1,
                                          column=2,
                                          columnspan=2,
                                          sticky=(N, S, W, E))
detection = Label(main, image=imgtk)
detection.grid(row=2, column=0, columnspan=4)
def open_image():
    global img
    img = ImageTk.PhotoImage(Image.open(root.filename))
    top = Toplevel()
    Label(top, image=img).pack()
    Button(top, text='Close image', command=top.destroy).pack(padx=5, pady=5)
import tkinter
import os
from PIL import ImageTk, Image

window = tkinter.Tk()
window.title("Gotham Bat")
window.geometry("840x580")
canvas = tkinter.Canvas(window, width=1000, height=1000)

image = ImageTk.PhotoImage(Image.open('imgs2\\main_bg.jpg'))

canvas.create_image(0, 0, anchor='nw', image=image)
canvas.place(x=0, y=0, relwidth=1, relheight=1)

# background_image=tkinter.PhotoImage('C:\\Users\\333ya\\Desktop\\Flappy Bird AI incomplete - Copy\\imgs\\main_bg.jpg')
# background_label = tkinter.Label(window, image=background_image)
# background_label.place(x=0, y=0, relwidth=1, relheight=1)
# # background_label.image=background_image


def single_player():
    os.system('single_player.py')


def ai_player():
    os.system('ai_player.py')


def p1_vs_p2():
    os.system('p1_vs_p2.py')
Beispiel #11
0
def log_to_fire(*args):
    if (len(entry_id.get()) == 0):
        global id_msg
        id_msg = tk.Label(root,
                          text="Email Field Must Required",
                          width=20,
                          font=("bold", 8),
                          pady=10,
                          fg='red')
        id_msg.grid(row=5, column=4)
    elif (len(entry_password.get()) == 0):

        try:
            id_msg.grid_forget()
        except:
            pass

        global password_msg
        password_msg = tk.Label(root,
                                text="Password Field Must Required",
                                width=20,
                                font=("bold", 8),
                                pady=10,
                                fg='red')
        password_msg.grid(row=7, column=4)

    else:

        try:
            password_msg.grid_forget()
        except:
            pass

        login = LogSign()
        data_src = login.login_method(email=entry_id.get(),
                                      password=entry_password.get())
        msg = tk.Label(root,
                       text=data_src[0],
                       width=20,
                       font=("bold", 12),
                       pady=10,
                       fg='green')
        msg.grid(row=10, column=4)

        data = data_src[1]

        profile_img = Image.open(data_src[2])
        profile_img = profile_img.resize((100, 100), Image.ANTIALIAS)
        profile_img = ImageTk.PhotoImage(profile_img)
        panel = tk.Label(root, image=profile_img)
        panel.image = profile_img
        panel.grid(row=12, column=2)

        name_msg_show = tk.Label(root,
                                 text="Name : " + data['name'],
                                 width=20,
                                 font=("bold", 12),
                                 pady=10,
                                 fg='green')
        name_msg_show.grid(row=14, column=2)

        email_msg_show = tk.Label(root,
                                  text="Email : " + data['email'],
                                  width=20,
                                  font=("bold", 12),
                                  pady=10,
                                  fg='green')
        email_msg_show.grid(row=16, column=2)
    global sesklaörü
    sesklasörü = filedialog.askopenfile()


def listeye_ekle(dosya):
    global seslisteyazısı
    global baslangicindex
    seslisteyazısı.insert(baslangicindex, os.path.basename(dosya))
    oynatmalistesi.append(dosya)
    print(oynatmalistesi)
    baslangicindex += 1


#fotoları çek
im = Image.open("simgeler/oynat.png")
ph1 = ImageTk.PhotoImage(im)
im = Image.open("simgeler/pause.png")
ph2 = ImageTk.PhotoImage(im)
im = Image.open("simgeler/durdur.png")
ph3 = ImageTk.PhotoImage(im)
im = Image.open("simgeler/sesli.png")
ph4 = ImageTk.PhotoImage(im)
im = Image.open("simgeler/sessiz.png")
ph5 = ImageTk.PhotoImage(im)
im = Image.open("simgeler/buton.png")
butonresmi = ImageTk.PhotoImage(im)
#Menüler
menubar = Menu(root)
root.config(menu=menubar)
#Dosya menüsü
dosyaMenu = Menu(menubar)
Beispiel #13
0
top.title('来自一位喜欢你的小哥哥')
# 本地运行用这里
top.iconbitmap(path.join('res/heart.ico'))
# 打包用这里
# top.iconbitmap(path.join(sys._MEIPASS, 'res/heart.ico'))
top.geometry("650x350")

top.protocol('WM_DELETE_WINDOW', lambda: 0)


def closeWindow():
    top.destroy()


# 本地运行用这里
photo = ImageTk.PhotoImage(Image.open(path.join('res/heart.png')).resize((150, 150)))
# 打包用这里
# photo = ImageTk.PhotoImage(Image.open(path.join(sys._MEIPASS, 'res/heart.png')).resize((150, 150)))
a_label = Label(top, **{'text': '小姐姐,我观察你很久了', 'font': ('', 19)})
b_label = Label(top, **{'text': '做我女朋友好不好?', 'font': ("Arial Bold", 20)})
a_button = Button(top, **{'text': '好呀', 'width': 13, 'height': 1}, command=closeWindow)
b_button = Button(top, **{'text': '算了吧', 'width': 13, 'height': 1})
label_img = Label(top, image=photo)

a_label.place(x=50, y=80)
b_label.place(x=50, y=130)
a_button.place(x=130, y=250)
label_img.place(x=420, y=40)

x = 330
y = 250
    def __init__(self, dataset):
        # Initialize our editor on this user's last edited image
        self.dataset = dataset
        root = Tk()
        root.title("L.I.R.A.")
        root.withdraw()
        center_left_window(root, 0, 0)
        # Ask them if they want to change the current values for resize and transparency if
        if messagebox.askyesno("Change Values",
                               "Would you like to change the transparency and resize factors from their current "
                               "values? (These are the default values if you have not started editing)"):
            dialog = GetResizeTransparencyDialog(root)
            center_left_window(dialog, 158, 193)
            dialog.resizable(False, False)
            self.editor_resize_factor, self.editor_transparency_factor = dialog.show()
            if self.editor_transparency_factor < 0.01 or self.editor_transparency_factor < 0.01:
                self.editor_resize_factor = self.dataset.progress["prediction_grids_resize_factor"]
                self.editor_transparency_factor = self.dataset.progress["prediction_grids_transparency_factor"]
            root.destroy()
        else:
            # Just use the current values
            self.editor_resize_factor = self.dataset.progress["prediction_grids_resize_factor"]
            self.editor_transparency_factor = self.dataset.progress["prediction_grids_transparency_factor"]
            root.destroy()

        # Parameters
        self.classification_key = ["Healthy Tissue", "Type I - Caseum", "Type II", "Empty Slide", "Type III",
                                   "Type I - Rim", "Unknown/Misc."]
        self.color_key = [(255, 0, 255), (0, 0, 255), (0, 255, 0), (200, 200, 200), (0, 255, 255), (255, 0, 0),
                          (244, 66, 143)]
        self.color_index = 3
        self.title = "L.I.R.A. Prediction Grid Editing"

        self.tools = ["pencil", "draw-square", "paint-bucket", "zoom"]
        self.tool_cursors = ["pencil", "crosshair", "coffee_mug", "target"]
        self.tool_icons = ["pencil-alt-solid.png", "edit-solid.png", "fill-drip-solid.png", "search-plus-solid.png"]
        tool_tips = ["Pencil tool", "Color selected rectangle", "Fill tool", "Zoom in on selected area"]
        self.tool_index = -1
        base_dir = os.path.dirname(os.getcwd())
        icon_dir = os.path.join(base_dir, 'icons')
        # Img + Predictions
        self.reload_img_and_predictions()

        # Window + Frame
        self.window = Tk()
        self.window.protocol("WM_DELETE_WINDOW", self.q_key_press)
        self.frame = Frame(self.window, bd=5, relief=SUNKEN)
        self.frame.grid(row=0, column=0)
        self.main_canvas_frame = Frame(self.frame)
        self.main_canvas_frame.pack()
        # Hard-code choice of resolution for main canvas, and hard-set scroll region as maximum shape of images
        self.main_canvas = Canvas(
            self.main_canvas_frame,
            bg="#000000",
            width=1366,
            height=700,
            scrollregion=(0, 0, self.dataset.imgs.max_shape()[1], self.dataset.imgs.max_shape()[0]),
        )

        # Create palette and toolbar
        self.toolbar = Frame(self.frame)
        self.toolbar.pack(side=LEFT)
        self.palette = Frame(self.frame)
        self.palette.pack(side=LEFT)

        # Scrollbars
        hbar = Scrollbar(self.main_canvas_frame, orient=HORIZONTAL)
        hbar.pack(side=BOTTOM, fill=X)
        hbar.config(command=self.main_canvas.xview)
        vbar = Scrollbar(self.main_canvas_frame, orient=VERTICAL)
        vbar.pack(side=RIGHT, fill=Y)
        vbar.config(command=self.main_canvas.yview)
        self.main_canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set)
        buttonFrame = Frame(self.window, bd=5)
        finishButton = Button(buttonFrame, text="Continue", command=self.finish_button_press)
        quitButton = Button(buttonFrame, text="Quit", command=self.q_key_press)

        leftrightFrame = Frame(buttonFrame)
        self.leftButton = Button(leftrightFrame, text="◀", command=self.left_arrow_key_press)
        self.rightButton = Button(leftrightFrame, text="▶", command=self.right_arrow_key_press)
        self.updating_img = False

        buttonFrame.grid(row=1, column=0, sticky=W + E)
        quitButton.pack(side=LEFT)
        finishButton.pack(side=RIGHT)
        leftrightFrame.pack()
        # begin with the leftButton hidden, and only show the rightButton if there are multiple
        # images
        if len(self.dataset.imgs) > 1 and self.dataset.progress["prediction_grids_image"] > 0:
            self.leftButton.pack(side=LEFT)
        if len(self.dataset.imgs) > 1 and self.dataset.progress["prediction_grids_image"] < len(self.dataset.imgs) - 1:
            self.rightButton.pack(side=RIGHT)

        # Title
        self.window.title("{} - Image {}/{}".format(self.title, self.dataset.progress["prediction_grids_image"] + 1,
                                                    len(self.dataset.prediction_grids.before_editing)))

        # Img + Event listeners
        self.main_canvas.image = ImageTk.PhotoImage(
            Image.fromarray(self.img))  # Literally because tkinter can't handle references properly and needs this.
        self.main_canvas.config(scrollregion=(0, 0, self.main_canvas.image.width(), self.main_canvas.image.height()))
        self.main_canvas_image_config = self.main_canvas.create_image(0, 0, image=self.main_canvas.image,
                                                                      anchor="nw")  # So we can change the image later
        self.main_canvas.focus_set()
        self.main_canvas.bind_all("<Button-4>", self.mouse_scroll)  # Scrollwheel for entire editor
        self.main_canvas.bind_all("<Button-5>", self.mouse_scroll)  # Scrollwheel for entire editor
        self.main_canvas.bind("<Left>", self.left_arrow_key_press)
        self.main_canvas.bind("<Right>", self.right_arrow_key_press)
        self.main_canvas.bind("<Key>", self.key_press)
        self.main_canvas.pack(side=TOP)

        self.toolButtons = []
        self.iconImages = []
        icon_color_str = "#%02x%02x%02x" % (180, 180, 180)

        self.buttonFrame = Frame(self.frame)

        self.buttonFrame.pack(side=LEFT)

        self.undo_img = Image.open(os.path.join(icon_dir, "undo-solid.png"))
        self.undo_img = self.undo_img.resize((20, 20), Image.ANTIALIAS)
        self.undo_img = ImageTk.PhotoImage(self.undo_img)
        self.undoButton = Button(
            self.buttonFrame,
            relief=SUNKEN,
            state=DISABLED,
            command=self.undo,
            bg=icon_color_str,
            image=self.undo_img
        )
        self.undoButton.pack()
        self.undos = []

        self.clear_img = Image.open(os.path.join(icon_dir, "eye-slash-solid.png"))
        self.clear_img = self.clear_img.resize((20, 20), Image.ANTIALIAS)
        self.clear_img = ImageTk.PhotoImage(self.clear_img)
        self.clearButton = Button(
            self.buttonFrame,
            relief=FLAT,
            command=self.clear_predictions,
            bg=icon_color_str,
            image=self.clear_img
        )
        self.clearButton.pack()
        createTooltip(self.undoButton, 'Undo last edit')
        createTooltip(self.clearButton, 'Set all classifications to Healthy Tissue')

        def change_tool(index):
            return lambda: self.changeTool(index)

        for i, icon in enumerate(self.tool_icons):
            icon_path = os.path.join(icon_dir, icon)
            icon_img = Image.open(icon_path)
            icon_img = icon_img.resize((20, 20), Image.ANTIALIAS)
            icon_img = ImageTk.PhotoImage(icon_img)
            self.iconImages.append(icon_img)
            tool_cmd = change_tool(i)
            self.toolButtons.append(
                Button(self.toolbar, relief=FLAT, command=tool_cmd, bg=icon_color_str, image=self.iconImages[i])
            )
            if i == self.tool_index:
                self.toolButtons[i].config(relief=SUNKEN, state=DISABLED)
            self.toolButtons[i].pack()
            createTooltip(self.toolButtons[i], tool_tips[i])

        self.paletteButtons = []

        def change_color(index):
            return lambda: self.changeColor(index)

        # Side Canvas
        for i, (classification, color) in enumerate(zip(self.classification_key, self.color_key)):
            # Since our colors are in BGR, and tkinter only accepts hex, we have to create a hex string for them,
            # in RGB order.
            b, g, r = color
            hex_color_str = "#%02x%02x%02x" % (r, g, b)

            # We then check get the color's brightness using the relative luminance algorithm
            # https://en.wikipedia.org/wiki/Relative_luminance
            color_brightness = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255
            if color_brightness < 0.5:
                # Dark color, bright font.
                text_color = "white"
            else:
                # Bright color, dark font.
                text_color = "black"

            # Then we generate our colored label string to include the keyboard shortcut for this classification
            color_cmd = change_color(i)

            button_str = "{}: {}".format(i, classification)
            self.paletteButtons.append(
                Button(self.palette, text=button_str, bg=hex_color_str, fg=text_color, relief=FLAT,
                       command=color_cmd)
            )
            if i == self.color_index:
                self.paletteButtons[i].config(relief=SUNKEN, state=DISABLED)
            if i < 4:
                self.paletteButtons[i].grid(sticky=W + E, row=i, column=0)
            else:
                self.paletteButtons[i].grid(sticky=W + E, row=i - 4, column=1)

        # Add left mouse and right mouse

        # Keeping track of which mouse button is currently held down
        self.left_mouse = False

        # So that if the user tries to insert classifications before they've selected any we will not do anything
        self.prediction_rect_x1 = 0
        self.prediction_rect_y1 = 0
        self.prediction_rect_x2 = 0
        self.prediction_rect_y2 = 0

        # Predictions and start
        self.window.mainloop()
    def paint_bucket_click(self, event):
        self.add_undo()
        # Get coordinates on canvas for beginning of this selection, (x1, y1)
        self.selection_x1, self.selection_y1 = get_canvas_coordinates(event)
        outline_rect_x1, outline_rect_y1, outline_rect_x2, outline_rect_y2 = get_outline_rectangle_coordinates(
            self.selection_x1, self.selection_y1, self.selection_x1, self.selection_y1, self.sub_h, self.sub_w)

        self.prediction_rect_x1 = int(outline_rect_x1 / self.sub_w)
        self.prediction_rect_y1 = int(outline_rect_y1 / self.sub_h)
        self.prediction_rect_x2 = int(outline_rect_x2 / self.sub_w)
        self.prediction_rect_y2 = int(outline_rect_y2 / self.sub_h)
        if self.prediction_rect_x1 == self.prediction_rect_x2:
            self.prediction_rect_x2 += 1
        if self.prediction_rect_y1 == self.prediction_rect_y2:
            self.prediction_rect_y2 += 1
        i = self.color_index
        square_color_i = self.prediction_grid[self.prediction_rect_y1:self.prediction_rect_y2,
                         self.prediction_rect_x1:self.prediction_rect_x2][0][0]

        # Save updated predictions
        fill_bound_x1 = self.prediction_rect_x1
        fill_bound_x2 = self.prediction_rect_x2
        fill_bound_y1 = self.prediction_rect_y1
        fill_bound_y2 = self.prediction_rect_y2

        # take care of filling adjacent squares with an iterative implementation
        # of recursion, using a stack because Python is scared of normal recursion

        rect_stack = [(self.prediction_rect_x1, self.prediction_rect_x2,
                       self.prediction_rect_y1, self.prediction_rect_y2)]
        while len(rect_stack) > 0:
            rect_x1, rect_x2, rect_y1, rect_y2 = rect_stack.pop()
            new_i = self.color_index
            if new_i == square_color_i:
                continue
            if rect_x1 < 0 or rect_y1 < 0 or \
                    rect_x2 > self.prediction_grid.shape[1] or rect_y2 > self.prediction_grid.shape[0]:
                continue
            if fill_bound_x1 > rect_x1:
                fill_bound_x1 = rect_x1
            if fill_bound_x2 < rect_x2:
                fill_bound_x2 = rect_x2
            if fill_bound_y1 > rect_y1:
                fill_bound_y1 = rect_y1
            if fill_bound_y2 < rect_y2:
                fill_bound_y2 = rect_y2
            self.prediction_grid[rect_y1:rect_y2, rect_x1:rect_x2] = new_i
            if rect_x2 + 1 <= self.prediction_grid.shape[1] and \
                    self.prediction_grid[rect_y1:rect_y2, rect_x1 + 1:rect_x2 + 1][0][
                        0] == square_color_i:
                rect_stack.append((rect_x1 + 1, rect_x2 + 1, rect_y1, rect_y2))
            if rect_x1 - 1 >= 0 and \
                    self.prediction_grid[rect_y1:rect_y2, rect_x1 - 1:rect_x2 - 1][0][0].item() == square_color_i:
                rect_stack.append((rect_x1 - 1, rect_x2 - 1, rect_y1, rect_y2))
            if rect_y2 + 1 <= self.prediction_grid.shape[0] and \
                    self.prediction_grid[rect_y1 + 1:rect_y2 + 1, rect_x1:rect_x2][0][0].item() == square_color_i:
                rect_stack.append((rect_x1, rect_x2, rect_y1 + 1, rect_y2 + 1))
            if rect_y1 - 1 >= 0 and \
                    self.prediction_grid[rect_y1 - 1:rect_y2 - 1, rect_x1:rect_x2][0][0].item() == square_color_i:
                rect_stack.append((rect_x1, rect_x2, rect_y1 - 1, rect_y2 - 1))

        self.dataset.prediction_grids.after_editing[
            self.dataset.progress["prediction_grids_image"]] = self.prediction_grid
        img_section = self.resized_img[
                      fill_bound_y1 * self.sub_h:fill_bound_y2 * self.sub_h,
                      fill_bound_x1 * self.sub_w:fill_bound_x2 * self.sub_w
                      ]
        prediction_grid_section = self.prediction_grid[
                                  fill_bound_y1:fill_bound_y2,
                                  fill_bound_x1:fill_bound_x2
                                  ]
        prediction_overlay_section = np.zeros_like(img_section)
        for row_i, row in enumerate(prediction_grid_section):
            for col_i, col in enumerate(row):
                color = self.color_key[col]
                # draw rectangles of the resized sub_hxsub_w size on it
                cv2.rectangle(
                    prediction_overlay_section,
                    (col_i * self.sub_w, row_i * self.sub_h),
                    (col_i * self.sub_w + self.sub_w, row_i * self.sub_h + self.sub_h),
                    color,
                    -1
                )

        img_section = weighted_overlay(img_section, prediction_overlay_section,
                                       self.editor_transparency_factor)
        img_section = cv2.cvtColor(img_section,
                                   cv2.COLOR_BGR2RGB)
        self.img[fill_bound_y1 * self.sub_h:fill_bound_y2 * self.sub_h,
                 fill_bound_x1 * self.sub_w:fill_bound_x2 * self.sub_w] = img_section

        # And finally update the canvas
        self.main_canvas.image = ImageTk.PhotoImage(
            Image.fromarray(self.img))  # Literally because tkinter can't handle references properly and needs this.
        self.main_canvas.itemconfig(self.main_canvas_image_config, image=self.main_canvas.image)
Beispiel #16
0
 def to_tk_image(self, img):
     return ImageTk.PhotoImage(Image.fromarray(img))
Beispiel #17
0
 def convertCVToTk(self, cvImage):
     height, width, _ = cvImage.shape
     if height == 0 or width == 0:
         return 0, 0, None
     img = Image.fromarray(cv2.cvtColor(cvImage, cv2.COLOR_BGR2RGB))
     return height, width, ImageTk.PhotoImage(img)
Beispiel #18
0
def redeye():
    global panelB, image, gray
    if panelB is not None:
        panelB.grid_forget()
    face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
    img_original = image.copy()
    # gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    if not np.any(faces):
        print "empty"
        eyes = eye_cascade.detectMultiScale(gray)
        for (ex, ey, ew, eh) in eyes:
            roi_eye = image[ey:ey + eh, ex:ex + ew]
            # cv2.imshow('img2', roi_eye)
            # cv2.waitKey(0)
            b = roi_eye[:, :, 0]
            g = roi_eye[:, :, 1]
            r = roi_eye[:, :, 2]
            bg = cv2.add(b, g)
            mask = (r > 100) & (r > bg)
            mask = mask.astype(np.uint8) * 255
            mask = fillHoles(mask)
            mask = cv2.dilate(mask,
                              None,
                              anchor=(-1, -1),
                              iterations=1,
                              borderType=1,
                              borderValue=1)
            mean = bg / 2
            mask = mask.astype(np.bool)[:, :, np.newaxis]
            mean = mean[:, :, np.newaxis]
            eyeOut = roi_eye.copy()
            np.copyto(eyeOut, mean, where=mask)
            image[ey:ey + eh, ex:ex + ew] = eyeOut
            # cv2.rectangle(img,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

    else:
        for (x, y, w, h) in faces:
            # cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
            roi_gray = gray[y:y + h, x:x + w]
            roi_color = image[y:y + h, x:x + w]

            eyes = eye_cascade.detectMultiScale(roi_gray)
            for (ex, ey, ew, eh) in eyes:
                roi_eye = roi_color[ey:ey + eh, ex:ex + ew]
                # cv2.imshow('img2', roi_eye)
                # cv2.waitKey(0)
                b = roi_eye[:, :, 0]
                g = roi_eye[:, :, 1]
                r = roi_eye[:, :, 2]
                bg = cv2.add(b, g)
                mask = (r > 100) & (r > bg)
                mask = mask.astype(np.uint8) * 255
                mask = fillHoles(mask)
                mask = cv2.dilate(mask,
                                  None,
                                  anchor=(-1, -1),
                                  iterations=1,
                                  borderType=1,
                                  borderValue=1)
                mean = bg / 2
                mask = mask.astype(np.bool)[:, :, np.newaxis]
                mean = mean[:, :, np.newaxis]
                eyeOut = roi_eye.copy()
                np.copyto(eyeOut, mean, where=mask)
                roi_color[ey:ey + eh, ex:ex + ew] = eyeOut
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    edged = Image.fromarray(image)
    edged = ImageTk.PhotoImage(edged)
    if panelB is None:
        panelB = Label(image=edged)
        panelB.image = edged
        panelB.pack(side="right", padx=10, pady=10)
    else:
        panelB.pack_forget()
        panelB = Label(image=edged)
        panelB.image = edged
        panelB.pack(side="right", padx=10, pady=10)
def detectAndDisplay(image):
    start_time = time.time()
    (h, w) = image.shape[:2]

    imageBlob = cv2.dnn.blobFromImage(cv2.resize(image, OUTPUT_SIZE),
                                      1.0,
                                      OUTPUT_SIZE, (104.0, 177.0, 123.0),
                                      swapRB=False,
                                      crop=False)

    detector.setInput(imageBlob)
    detections = detector.forward()

    log_ScrolledText.delete(1.0, END)

    for i in range(0, detections.shape[2]):
        confidence = detections[0, 0, i, 2]

        if confidence > min_confidence:
            box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
            (startX, startY, endX, endY) = box.astype("int")

            face = image[startY:endY, startX:endX]
            (fH, fW) = face.shape[:2]

            face_blob = cv2.dnn.blobFromImage(
                face,
                1.0, (227, 227), (78.4263377603, 87.7689143744, 114.895847746),
                swapRB=False)

            age_detector.setInput(face_blob)
            age_predictions = age_detector.forward()
            age_index = age_predictions[0].argmax()
            age = age_list[age_index]
            age_confidence = age_predictions[0][age_index]

            gender_detector.setInput(face_blob)
            gender_predictions = gender_detector.forward()
            gender_index = gender_predictions[0].argmax()
            gender = gender_list[gender_index]
            gender_confidence = gender_predictions[0][gender_index]

            text = "{}: {}".format(gender, age)
            y = startY - 10 if startY - 10 > 10 else startY + 10
            cv2.rectangle(image, (startX, startY), (endX, endY), (0, 255, 0),
                          2)
            cv2.putText(image, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX,
                        0.45, (0, 255, 0), 2)

            log_ScrolledText.insert(
                END, "%10s %10s %10.2f %2s" %
                ('Gender : ', gender, gender_confidence * 100, '%') + '\n',
                'TITLE')
            log_ScrolledText.insert(
                END, "%10s %10s %10.2f %2s" %
                ('Age : ', age, age_confidence * 100, '%') + '\n\n', 'TITLE')
            log_ScrolledText.insert(
                END, "%15s %20s" % ('Age', 'Probability(%)') + '\n', 'HEADER')
            for i in range(len(age_list)):
                log_ScrolledText.insert(
                    END, "%10s %15.2f" %
                    (age_list[i], age_predictions[0][i] * 100) + '\n')
            log_ScrolledText.insert(
                END, "%12s %20s" % ('Gender', 'Probability(%)') + '\n',
                'HEADER')

            for i in range(len(gender_list)):
                log_ScrolledText.insert(
                    END, "%10s %15.2f" %
                    (gender_list[i], gender_predictions[0][i] * 100) + '\n')

    frame_time = time.time() - start_time
    global elapsed_time
    elapsed_time += frame_time
    print("Frame {} time {:.3f} seconds".format(frame_count, frame_time))

    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image = Image.fromarray(image)
    imgtk = ImageTk.PhotoImage(image=image)
    detection.config(image=imgtk)
    detection.image = imgtk
def user_input():
    global userIp
    global e1
    e1.focus_set()
    userip = userIp.get()
    e1.delete(0,END)
    print(userip)
    return userip
 
#Tkinter
window=tk.Tk()
userIp = tk.StringVar()
window.geometry("1300x800")
scrollbar = Scrollbar(window) 
window.configure(background='black')
img = PIL.Image.open('jarvis.png')
img = img.resize((400, 500), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)

lbl = Label(window, image = img , text = 'WELCOME TO JARVIS',highlightthickness = 0,bd=0)
lbl.pack()
btn_open = tk.Button(window, text="SPEAK", command=speaking, bg='black', fg='green', bd=10)
btn_open.place(x=50,y=300, height=100,width=100)

e1 = Entry(window, bd =10, bg= 'black', textvariable=userIp,fg='green')
e1.place(x= 350,y= 500, width= 600,height=50)
 
window.mainloop()
   

Beispiel #21
0
# l_name.grid(row=0, column=0, padx=20)
# but_save.grid(row=0, column=2, padx=20)

listbox_faces = Listbox(frame5, bg='white', height=33)
listbox_faces.config(selectmode=MULTIPLE)

#listbox_faces.grid(row=0, column=0,  padx=10, pady=10)

#     but_step1 = Button(frame5, text='<<', command=lambda i=-1: page_change(i)).grid(row=5, column=0, sticky=(N, W, E, S))
#     but_step2 = Button(frame5, text='>>', command=lambda i=1: page_change(i)).grid(row=6, column=0, sticky=(N, W, E, S))
#     but_cut = Button(frame5, text='Вырезать', command=onCut).grid(row=2, column=0, sticky=(N, W, E, S))
#     but_paste = Button(frame5, text='Вставить', command=onPaste).grid(row=1, column=0,
#                                                                                       sticky=(N, W, E, S))
# #but_del = Button(frame5, text='Удалить', command=lambda i=person: onDel(i)).grid(row=3, column=0, sticky=(N, W, E, S))

img = ImageTk.PhotoImage(Image.open('../face_recognition/img/present.png'))

panel = Label(frame6, image=img, width=980, height=675)
panel.pack(side="bottom", fill="both", expand="yes")

refresh_main_window()

listbox.grid(row=1, column=0, padx=10, pady=10)

m = Menu(root)  # создается объект Меню на главном окне
root.config(menu=m)  # окно конфигурируется с указанием меню для него

fm = Menu(m)  # создается пункт меню с размещением на основном меню (m)
m.add_cascade(label="Захват изображение",
              menu=fm)  # пункту располагается на основном меню (m)
fm.add_command(
from tkinter import Tk, Button, Label
import PIL as pillow
from PIL import ImageTk, Image

root = Tk()
root.title("Icon,Images & exit buttons")
# root.iconbitmap()

quit_button = Button(root, text="Exit Program", command=root.quit)
quit_button.pack()

my_img = ImageTk.PhotoImage(Image.open("mario_PNG57.png"))
my_label = Label(image=my_img)
my_label.pack()

root.mainloop()
Beispiel #23
0
    top.destroy()
    import ppal


def deb():
    top.destroy()
    import debit


top = Tk()
top.title("WELCOME")
top.config(background="white")
top.geometry("1005x580+150+30")
top.resizable(0, 0)
image = Image.open("sre.jpg")
pho = ImageTk.PhotoImage(image)
r = Label(top, image=pho)
r.pack()
Label(top,
      text="Select Payment Method",
      fg="black",
      bg="yellow",
      font=("timesnew roman", 24)).place(x=335, y=40)
photo = PhotoImage(file="c.png")
t = Label(top, image=photo)
t.place(x=40, y=170)
phot = PhotoImage(file="d.png")
s = Label(top, image=phot)
s.place(x=730, y=170)
ph = PhotoImage(file="gt.png")
e = Label(top, image=ph, height=250, width=250)
Beispiel #24
0
	def main(self, displayed, tabControl):
		self.Frame=Frame(tabControl, background="black")
		self.Frame.pack(fill=BOTH, expand=YES)
		newstab = ttk.Frame(tabControl)
		tabControl.add(self.Frame, text ="NEWS")
		tabControl.select(len(tabControl.tabs())-1)
		title=Label(self.Frame, font=("Helvetica", 60), fg="white", bg="black", text="NEWS",anchor="w")
		title.pack(padx=0, pady=25)
		n=0
		NewsList=[]
		News=Work_with_files.read_news_data()
		NewsList=News["articles"]
		w=350
		h=600
		self.NewsFrame=Frame(self.Frame, width=1920, height=1000, bg="black",padx=25,pady=50)
		self.NewsFrame.pack()
		self.NewsDir1=Canvas(self.NewsFrame, width=w, height=h, bg="black")
		self.NewsDir1.pack(side=LEFT, padx=10, pady=0) 
		self.NewsDir2=Canvas(self.NewsFrame, width=w, height=h, bg="black")
		self.NewsDir2.pack(side=LEFT, padx=10)
		self.NewsDir3=Canvas(self.NewsFrame, width=w, height=h, bg="black")
		self.NewsDir3.pack(side=LEFT, padx=10) 
		self.NewsDir4=Canvas(self.NewsFrame, width=w, height=h, bg="black")
		self.NewsDir4.pack(side=LEFT, padx=10)
		self.NewsDir5=Canvas(self.NewsFrame, width=w, height=h, bg="black")
		self.NewsDir5.pack(side=LEFT, padx=10)
		self.update()
		NewsD=1
		displayed=int(displayed)
		start= displayed-5
		end=displayed
		for i in NewsList:
			Nov = str(i["title"]).split("- ")
			news_source=i["source"]["name"]
			if (news_source.lower() in ("24ur.com", "rtvslo.si", "siol.net", "racunalniske-novice.com") and start<=n<end):
				news_title=str(i["title"]).split("-")
				image_url=str(i["urlToImage"])
				render=""
				try:
					if ("http" in image_url):
						image_byt = urlopen(image_url).read()
						load = PIL.Image.open(io.BytesIO(image_byt))
						image_final=load.resize((300,200), PIL.Image.BOX, reducing_gap=1)
						render = ImageTk.PhotoImage(image_final)
					elif ("//" in image_url):
						try:
							image_byt = urlopen("https:"+image_url).read()
							load = PIL.Image.open(io.BytesIO(image_byt))
							image_final=load.resize((300,200), PIL.Image.BOX, reducing_gap=1)
							render = ImageTk.PhotoImage(image_final)
						except:
							image_byt = urlopen("http:"+image_url).read()
							load = PIL.Image.open(io.BytesIO(image_byt))
							image_final=load.resize((300,200), PIL.Image.BOX, reducing_gap=1)
							render = ImageTk.PhotoImage(image_final)
					elif("dnevnik" in str(i["url"])):
						image_byt = urlopen("https://www.dnevnik.si"+image_url).read()
						load = PIL.Image.open(io.BytesIO(image_byt))
						image_final=load.resize((300,200), PIL.Image.ANTIALIAS)
						render = ImageTk.PhotoImage(image_final)
				except:
					load = PIL.Image.open("no_image.PNG")
					render = ImageTk.PhotoImage(load)
				
				if NewsD==1:
					self.NewsDir1.create_rectangle(1,1, w-1, h-1,fill="black")
					self.NewsDir1.create_text(20, 50, width=w-20, text=news_title[0],fill="white", font=("verdana", 12, "bold"), anchor="w")
					self.NewsDir1.create_text(20, 90, width=w-20, text=news_title[len(news_title) - 1],fill="white", font=("verdana", 12), anchor="w")
					img = Label(self.NewsDir1, image=render, width=310, height=200)
					img.image = render
					img.place(x=20, y=110)
					self.NewsDir1.create_text(30,400,width=w-30, text=str(i["description"]), fill="white", font=("verdana", 12), anchor="w")
					

				elif NewsD==2:
					self.NewsDir2.create_rectangle(3,3, w-1, h-1,fill="black")
					self.NewsDir2.create_text(20, 50, width=w-20, text=news_title[0],fill="white", font=("verdana", 12, "bold"), anchor="w")
					self.NewsDir2.create_text(20, 90, width=w-20, text=news_title[len(news_title) - 1],fill="white", font=("verdana", 12), anchor="w")
					img = Label(self.NewsDir2, image=render, width=310, height=200)
					img.image = render
					img.place(x=20, y=110)
					self.NewsDir2.create_text(30,400,width=w-30, text=str(i["description"]), fill="white", font=("verdana", 12), anchor="w")

				elif NewsD==3:
					self.NewsDir3.create_rectangle(3,3, w-1, h-1,fill="black")
					self.NewsDir3.create_text(20, 50, width=w-20, text=news_title[0],fill="white", font=("verdana", 12, "bold"), anchor="w")
					self.NewsDir3.create_text(20, 90, width=w-20, text=news_title[len(news_title) - 1],fill="white", font=("verdana", 12), anchor="w")
					img = Label(self.NewsDir3, image=render, width=310, height=200)
					img.image = render
					img.place(x=20, y=110)
					self.NewsDir3.create_text(30,400,width=w-30, text=str(i["description"]).replace(" - ", "\n"), fill="white", font=("verdana", 12), anchor="w")

				elif NewsD==4:
					self.NewsDir4.create_rectangle(3,3, w-1, h-1,fill="black")
					self.NewsDir4.create_text(20, 50, width=w-20, text=news_title[0],fill="white", font=("verdana", 12, "bold"), anchor="w")
					self.NewsDir4.create_text(20, 90, width=w-20, text=news_title[len(news_title) - 1],fill="white", font=("verdana", 12), anchor="w")
					img = Label(self.NewsDir4, image=render, width=310, height=200)
					img.image = render
					img.place(x=20, y=110)
					self.NewsDir4.create_text(30,400,width=w-30, text=str(i["description"]).replace(" - ", "\n"), fill="white", font=("verdana", 12), anchor="w")

				elif NewsD==5:
					self.NewsDir5.create_rectangle(3,3, w-1, h-1,fill="black")
					self.NewsDir5.create_text(20, 50, width=w-20, text=news_title[0],fill="white", font=("verdana", 12, "bold"), anchor="w")
					self.NewsDir5.create_text(20, 90, width=w-20, text=news_title[len(news_title) - 1],fill="white", font=("verdana", 12), anchor="w")
					img = Label(self.NewsDir5, image=render, width=310, height=200)
					img.image = render
					img.place(x=20, y=110)
					self.NewsDir5.create_text(30,400,width=w-30, text=str(i["content"]), fill="white", font=("verdana", 12), anchor="w")
				NewsD=NewsD+1
				n=n+1
			else:
				if (NewsD==1 and news_source.lower() in ("24ur.com", "rtvslo.si", "siol.net", "racunalniske-novice.com")):
					n=n+1
Beispiel #25
0
    return ret


def quotes():
    file = open("/home/pi/Desktop/ui_assistant/quotes.txt", "r")
    quotes = file.readlines()
    line = quotes[randint(0, len(quotes) - 1)]
    return wrap_by_word(line, 12)


global image
webscraper.get_pic()
i = Image.open("backgroundpic.jpg")
i.thumbnail((2000, 1000))

image = ImageTk.PhotoImage(i, master=root)
my_label = Label(root, image=image)
my_label.place(x=0, y=0, relheight=1, relwidth=1)

#canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
#canvas.pack()

GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.add_event_detect(10, GPIO.RISING, callback=button_pressed)

top = tk.Frame(root, bg=yellow)
top.place(relheight=0.2, relwidth=0.95, rely=0.025, relx=0.025)

quote = tk.Label(top, fg=gray, text=quotes(), bg=yellow, font=("Pacifico", 20))
quote.place(relheight=0.8, relwidth=0.9, relx=0.05, rely=0.1)
Beispiel #26
0
def exhelp():
    top=Toplevel()
    global my_img1
    global staus
    global button_backward
    global button_forward
    global my_lebel
    my_img1=ImageTk.PhotoImage(Image.open("./image/img1.jpeg"))
    my_img2=ImageTk.PhotoImage(Image.open("./image/img2.jpeg"))
    my_img3=ImageTk.PhotoImage(Image.open("./image/img3.jpeg"))
    my_img4=ImageTk.PhotoImage(Image.open("./image/img4.jpeg"))
    
    
    image_list=[my_img1,my_img2,my_img3,my_img4]


    def forward(image_number):
        global my_lebel
        global button_backward
        global button_forward
        global status
        my_lebel.grid_forget()
        my_lebel=Label(top,image=image_list[image_number-1])
        status=Label(top,text=f"Image {str(image_number+1)} of "+str(len(image_list)),relief=SUNKEN,anchor=E)
        button_backward=Button(top,text="<<",command=lambda:backward(image_number-1))
        button_forward=Button(top,text=">>",command=lambda:forward(image_number+1))
        if image_number==3:
            button_forward=Button(top,text=">>",state=DISABLED)
        my_lebel.grid(row=0,column=1)
        button_backward.grid(row=0,column=0)
        button_forward.grid(row=0,column=2)
        status.grid(row=1,column=0,columnspan=3,sticky=W+E)

    def backward(image_number):
        global my_lebel
        global button_backward
        global button_forward
        global status
        my_lebel.grid_forget()
        my_lebel=Label(top,image=image_list[image_number])
        status=Label(top,text=f"Image {str(image_number+1)} of "+str(len(image_list)),relief=SUNKEN,anchor=E)
        button_backward=Button(top,text="<<",command=lambda:backward(image_number-1))
        button_forward=Button(top,text=">>",command=lambda:forward(image_number+1))
        if image_number==0:
            button_backward=Button(top,text="<<",state=DISABLED)
        my_lebel.grid(row=0,column=1)
        button_backward.grid(row=0,column=0)
        button_forward.grid(row=0,column=2)
        status.grid(row=1,column=0,columnspan=3,sticky=W+E)


    my_lebel=Label(top,image=my_img1,borderwidth=5)
    status=Label(top,text="Image 1 of "+str(len(image_list)),relief=SUNKEN,anchor=E)
    button_forward=Button(top,text=">>",command=lambda:forward(0))
    button_backward=Button(top,text="<<",command=lambda:backward(0))


    button_backward.grid(row=0,column=0)
    button_forward.grid(row=0,column=2)
    my_lebel.grid(row=0,column=1)
    status.grid(row=1,column=0,columnspan=3,sticky=W+E)
Beispiel #27
0
 def popup_reporte_png(self, master, path):
     top = self.top = Toplevel(master)
     img = ImageTk.PhotoImage(Image.open(path))
     panel = Label(top, image=img)
     panel.image = img
     panel.pack(side="bottom", fill="both", expand="yes")
Beispiel #28
0
    def __init__(self, cv2image, ratio=0):
        ##Für Anzeige der CV2 Bilder in tkinter Canvas##
        cv2image, self.ratio = img_change_size(
            cv2image, ratio)  # enable/disable für anpassung der größe
        img = Image.fromarray(cv2image)  # Image in PIL
        self.imgtk = ImageTk.PhotoImage(image=img)  # Image in tkinter
        canvas.config(width=cv2image.shape[1],
                      height=cv2image.shape[0])  # Größe canvas anpassen
        canvas.create_image(0, 0, image=self.imgtk,
                            anchor=NW)  # Bild in Canvas schreiben
        self.cv2img2 = cv2image  # Bild für select_color kopieren
        status_bar.config(text='Bitte alle benötigten Größen eingeben')

        #self.color_RGB=[120,100,50] #Für Entwicklungszwecke Farbe festlegen
        #self.ratio=0.0236327 #Für Entwicklungszwecke skalierung festlegen
        cv2.imwrite('testbildTMP.png', cv2image)

        #Um ratio bei aufnahme von bildern fix zu halten
        self.fix_length = False
        if ratio != 0:
            self.fix_length = True

        def starten():
            BildMaskieren(cv2image, self.color_RGB, self.ratio,
                          self.tattoo_shape, self.birthmarks)

        def TriggerToolbar(trigger):
            if str(Farbe['state']) == str(self.Laenge['state']) == str(
                    Kontur['state']) == str(
                        Auslassen['state']
                    ) == 'normal':  #Bei aktivieren eines buttons
                Farbe.config(state='disabled')
                self.Laenge.config(state='disabled')
                Kontur.config(state='disabled')
                Auslassen.config(state='disabled')
                Start.config(state='disabled')
                menu.entryconfig("Datei",
                                 state="disabled")  #Datei menü deaktivieren
                canvas.config(cursor="hand1")  #Cursor zu Hand
                self.trigg_button = 'first'  #Bei aktivieren eines buttons
            else:  #Um restliche Buttons wieder zu aktivieren
                Farbe.config(state='normal')
                self.Laenge.config(state='normal')
                Kontur.config(state='normal')
                Auslassen.config(state='normal')
                menu.entryconfig("Datei",
                                 state="normal")  #Datei menü aktivieren
                canvas.config(cursor="arrow")  #Cursor zurück zu Pfeil
                self.trigg_button = 'second'  #Bei deaktivieren der Buttons
                canvas.unbind(
                    '<Button-1>')  #Löscht alle Bindungen von linker Maustaste
                try:
                    if self.ratio != 0 and self.color_RGB != [] and self.tattoo_shape != []:
                        Start.config(state='normal')
                        status_bar.config(text='Bereit')
                    else:
                        status_bar.config(
                            text='Bitte alle benötigten Größen eingeben')
                except:
                    pass

            if trigger == 'farbe':
                Farbe.config(state='normal')
                self.select_color()
            elif trigger == 'laenge':
                self.Laenge.config(state='normal')
                ratio = self.length()
            elif trigger == 'kontur':
                Kontur.config(state='normal')
                self.select_shape()
            elif trigger == 'auslassen':
                Auslassen.config(state='normal')
                self.exclude()
            elif trigger == 'start':
                pass

        self.birthmarks = []
        self.tattoo_shape = []
        self.TriggerToolbar = TriggerToolbar  #Um in length darauf zu zu greifen
        global toolbar
        toolbar.destroy()
        toolbar = Label(l)  # Erstellt leere Toolbar
        toolbar.pack(side=TOP, fill=X)
        Farbe = Button(toolbar,
                       text='Farbe auswählen',
                       command=lambda: TriggerToolbar('farbe'))
        Farbe.grid(row=0, column=1, padx=5, pady=1)
        self.Laenge = Button(toolbar,
                             text='Skalierung festlegen',
                             command=lambda: TriggerToolbar('laenge'))
        self.Laenge.grid(row=0, column=2, padx=5, pady=1)
        Kontur = Button(toolbar,
                        text='Tattoo markieren',
                        command=lambda: TriggerToolbar('kontur'))
        Kontur.grid(row=0, column=3, padx=5, pady=1)
        Auslassen = Button(toolbar,
                           text='Stellen auslassen?',
                           command=lambda: TriggerToolbar('auslassen'))
        Auslassen.grid(row=0, column=4, padx=5, pady=1)
        Start = Button(toolbar, text='Starten', command=starten)
        Start.grid(row=0, column=6, padx=5, pady=1)
        Start.config(state='disabled')
        self.cBOX = Label(toolbar, width=25)
        self.cBOX.grid(row=0, column=5, padx=5, pady=1)
Beispiel #29
0
    def __init__(self, master):
        self.master = master
        self.loc = self.dragged = 0
        tk.Frame.__init__(self, master)

        canv = tk.Canvas(root, width=512, height=512)



        squads = []
        side = 64
        tup = tuple((x, y) for y in (i * side for i in range(8))\
                    for x in (i * side for i in range(8)))

        count = 0

        for x1, y1 in tup:
            x2, y2 = x1 + side, y1 + side
            if count % 9 == 0:
                count += 1
            if count % 2 == 0:
                squads.append(canv.create_rectangle(x1, y1, x2, y2, width=3, fill="brown"))
            else:
                squads.append(canv.create_rectangle(x1, y1, x2, y2, width=3, fill="white"))
            count += 1
        path1 = 'C:/Users/User/PycharmProjects/chess/img/blackp.png'
        path2 = 'C:/Users/User/PycharmProjects/chess/img/whitep.png'
        path3 = 'C:/Users/User/PycharmProjects/chess/img/blackr.png'
        path4 = 'C:/Users/User/PycharmProjects/chess/img/whiter.png'
        path5 = 'C:/Users/User/PycharmProjects/chess/img/blackn.png'
        path6 = 'C:/Users/User/PycharmProjects/chess/img/whiten.png'
        path7 = 'C:/Users/User/PycharmProjects/chess/img/blackb.png'
        path8 = 'C:/Users/User/PycharmProjects/chess/img/whiteb.png'
        path9 = 'C:/Users/User/PycharmProjects/chess/img/blackq.png'
        path10 = 'C:/Users/User/PycharmProjects/chess/img/whiteq.png'
        path11 = 'C:/Users/User/PycharmProjects/chess/img/blackk.png'
        path12 = 'C:/Users/User/PycharmProjects/chess/img/whitek.png'

        coord = []
        figures = []
        white1 = []
        black1 = []
        self.imgb1 = ImageTk.PhotoImage(Image.open(path1))
        self.imgw1 = ImageTk.PhotoImage(Image.open(path2))
        y = 32.
        while y <= 480.:
            figures.append(canv.create_image(96., y, image=self.imgb1, tag="DnD"))
            figures.append(canv.create_image(480. - 64., y, image=self.imgw1, tag="DnD"))
            black1.append([96.,y])
            coord.append([96.,y])
            white1.append([480. - 64., y])
            coord.append([480.-64., y])
            y += 64.
        '''туры'''
        self.imgb2 = ImageTk.PhotoImage(Image.open(path3))
        self.imgw2 = ImageTk.PhotoImage(Image.open(path4))

        figuresx1 = 32.
        figuresx2 = 512. - 32.

        coord.append([32., figuresx1])
        coord.append([32., figuresx2])
        coord.append([512.-32., figuresx1])
        coord.append([512. - 32., figuresx2])

        black1.append([32., figuresx1])
        black1.append([32., figuresx2])
        white1.append([512.-32., figuresx1])
        white1.append([512. - 32., figuresx2])

        figures.append(canv.create_image(32., figuresx1, image=self.imgb2, tag="DnD"))
        figures.append(canv.create_image(32., figuresx2, image=self.imgb2, tag="DnD"))
        figures.append(canv.create_image(512. - 32., figuresx1, image=self.imgw2, tag="DnD"))
        figures.append(canv.create_image(512. - 32., figuresx2, image=self.imgw2, tag="DnD"))
        '''кони'''
        self.imgb3 = ImageTk.PhotoImage(Image.open(path5))
        self.imgw3 = ImageTk.PhotoImage(Image.open(path6))

        figuresx1 += 64.
        figuresx2 -= 64.

        coord.append([32., figuresx1])
        coord.append([32., figuresx2])
        coord.append([512. - 32., figuresx1])
        coord.append([512. - 32., figuresx2])

        black1.append([32., figuresx1])
        black1.append([32., figuresx2])
        white1.append([512.-32., figuresx1])
        white1.append([512. - 32., figuresx2])


        figures.append(canv.create_image(32., figuresx1, image=self.imgb3, tag="DnD"))
        figures.append(canv.create_image(32., figuresx2, image=self.imgb3, tag="DnD"))
        figures.append(canv.create_image(512. - 32., figuresx1, image=self.imgw3, tag="DnD"))
        figures.append(canv.create_image(512. - 32., figuresx2, image=self.imgw3, tag="DnD"))
        '''слоны'''
        self.imgb4 = ImageTk.PhotoImage(Image.open(path7))
        self.imgw4 = ImageTk.PhotoImage(Image.open(path8))

        figuresx1 += 64.
        figuresx2 -= 64.

        coord.append([32., figuresx1])
        coord.append([32., figuresx2])
        coord.append([512. - 32., figuresx1])
        coord.append([512. - 32., figuresx2])

        black1.append([32., figuresx1])
        black1.append([32., figuresx2])
        white1.append([512.-32., figuresx1])
        white1.append([512. - 32., figuresx2])

        figures.append(canv.create_image(32., figuresx1, image=self.imgb4, tag="DnD"))
        figures.append(canv.create_image(32., figuresx2, image=self.imgb4, tag="DnD"))
        figures.append(canv.create_image(512. - 32., figuresx1, image=self.imgw4, tag="DnD"))
        figures.append(canv.create_image(512. - 32., figuresx2, image=self.imgw4, tag="DnD"))
        '''ферзи'''
        self.imgb5 = ImageTk.PhotoImage(Image.open(path9))
        self.imgw5 = ImageTk.PhotoImage(Image.open(path10))
        '''короли'''
        self.imgb6 = ImageTk.PhotoImage(Image.open(path11))
        self.imgw6 = ImageTk.PhotoImage(Image.open(path12))

        figuresx1 += 64.
        figuresx2 -= 64.

        coord.append([32., figuresx1])
        coord.append([32., figuresx2])
        coord.append([512. - 32., figuresx1])
        coord.append([512. - 32., figuresx2])

        black1.append([32., figuresx1])
        black1.append([32., figuresx2])
        white1.append([512.-32., figuresx1])
        white1.append([512. - 32., figuresx2])

        figures.append(canv.create_image(32., figuresx1, image=self.imgb5, tag="DnD"))
        figures.append(canv.create_image(32., figuresx2, image=self.imgb6, tag="DnD"))
        figures.append(canv.create_image(512. - 32., figuresx1, image=self.imgw5, tag="DnD"))
        figures.append(canv.create_image(512. - 32., figuresx2, image=self.imgw6, tag="DnD"))
        self.kingbl = 29
        self.kingwh = 31
        canv.pack(expand=1, fill=tk.BOTH)

        canv.tag_bind("DnD", "<ButtonPress-1>", self.down)
        canv.tag_bind("DnD", "<ButtonRelease-1>", self.chkup)
        canv.tag_bind("DnD", "<Enter>", self.enter)
        canv.tag_bind("DnD", "<Leave>", self.leave)
        self.coord = coord

        self.white1 = white1
        self.black1 = black1

        self.figures = figures

        self.canv = canv
        data = s.recv(10000)

        print 'received0', len(data), 'bytes'

        dataa = data.split(' ')
        for i in range(0, len(dataa), 1):
            dataa[i] = dataa[i].split(',')
        del dataa[len(dataa) - 1]

        for i in range(0, len(dataa), 1):
            for j in range(0, len(dataa[i]), 1):
                dataa[i][j] = float(dataa[i][j])
        self.coord = dataa

        for i in range(len(self.coord)):
            self.canv.coords(self.figures[i], self.coord[i][0], self.coord[i][1])
Beispiel #30
0
    def __init__(self, *args, **kwargs):
        Tk.__init__(self, *args, **kwargs)
        #Pre-configuration of interface
        self.winfo_toplevel().title("SE4TeC - Shapelets Extraction")
        self._root().geometry('820x620')
        self.k_list = list(range(10))
        self.guiFunc = gui_function(self)
        '''start of menubar'''
        menubar = Menu(self)
        filemenu = Menu(menubar, tearoff=0)

        filemenu.add_command(label="New training file",
                             command=self.guiFunc.add_dataset)
        # add the tkinter.Label which indicate the file name
        filemenu.add_separator()
        filemenu.add_command(label="exit", command=self.hello)
        menubar.add_cascade(label="File", menu=filemenu)
        self._root().config(menu=menubar)
        '''end of menubar'''

        #Frame1
        self.frame1 = tkinter.Frame(self, bg="SkyBlue4")
        #self.frame1.pack(fill = BOTH, side=TOP)
        self.frame1.pack(fill=X)
        self.frame1.config(borderwidth=2, relief=GROOVE)

        #Frame 1_1
        self.frame1_1 = tkinter.Frame(self.frame1, bg="SkyBlue4")
        self.frame1_1.grid(row=0, column=0, sticky=W)
        l1 = tkinter.Label(self.frame1_1,
                           text="SE4TeC",
                           background="SkyBlue4",
                           font="Helvetica 28 bold",
                           foreground="White")
        l1.grid(row=0, column=0, sticky=W, rowspan=2)

        self.frame1_2 = tkinter.Frame(self.frame1, bg="SkyBlue4")
        self.frame1_2.grid(row=0, column=1, sticky=W)
        '''b1 = tkinter.Button(self.frame1_2, text="Import Dataset", command=self.guiFunc.add_dataset, highlightthickness=4,
                      #highlightcolor="SkyBlue4",
                      anchor="center",
                      highlightbackground="SkyBlue4",
                      borderwidth=4)'''
        b1 = tkinter.Button(
            self.frame1_2,
            text="Import Dataset",
            command=self.guiFunc.add_dataset,
            highlightthickness=4,
            # highlightcolor="SkyBlue4",
            anchor="center",
            highlightbackground="SkyBlue4",
            borderwidth=4)
        b1.grid(row=0, column=0, sticky=W, padx=15, pady=10)

        #Frame 2: the middle part of GUI
        self.frame2 = tkinter.Frame(self, bg="gray90")
        self.frame2.pack(fill=BOTH)
        self.frame2.config(borderwidth=2, relief=GROOVE)

        # Placement of a single SOURCE visualization
        self.frame2_1 = SMAPPage(self.frame2, self)

        #Frame 1_3
        self.frame1_3 = tkinter.Frame(self.frame1, bg="SkyBlue4")
        self.frame1_3.grid(row=0, column=2, sticky=E, columnspan=2, padx=80)
        self.img_open = Image.open('CombinedLogo_360_40.jpg')
        self.img = ImageTk.PhotoImage(self.img_open)
        self.label_img = tkinter.Label(self.frame1_3, image=self.img)
        self.label_img.pack()
        '''l_algo = tkinter.Label(self.frame1_3, text="Select the algorithm: ", background= "SkyBlue4", foreground = "White")
        radVar = StringVar()
        b_USE = tkinter.Radiobutton(self.frame1_3, text="USE", variable=radVar, value="USEPage", indicatoron=0, command=lambda x=radVar: self.show_frame(self.frame2, x.get()), border=4)
        b_SMAP = tkinter.Radiobutton(self.frame1_3, text="SMAP", variable=radVar, value="SMAPPage", indicatoron=0, command=lambda x=radVar: self.show_frame(self.frame2, x.get()), border=4)
        b_SMAP_LB = tkinter.Radiobutton(self.frame1_3, text="SMAP_LB", variable=radVar, value="SMAPLBPage", indicatoron=0, command=lambda x=radVar: self.show_frame(self.frame2, x.get()), border=4)
        l_algo.grid(row=0, column=0, sticky=E, padx=(15,5), pady=10)  # position "West"
        b_USE.grid(row=0, column=1, ipadx=15, ipady=10, padx=15, pady=10)
        b_SMAP.grid(row=0, column=2, ipadx=15, ipady=10, padx=15, pady=10)
        b_SMAP_LB.grid(row=0, column=3, ipadx=15, ipady=10, padx=15, pady=10)'''
        self.frame1_3.grid_columnconfigure(0, weight=1)

        ####################################################################################
        #############################Frame 2_2, plot of results#############################
        self.frame2_2 = tkinter.Frame(self.frame2)
        self.frame2_2.grid(row=0, column=1, sticky=N, columnspan=2)
        self.figure = plt.figure(figsize=(8, 6), dpi=60)
        self.ax1 = self.figure.add_subplot(311)
        self.ax2 = self.figure.add_subplot(312, sharex=self.ax1)
        self.ax3 = self.figure.add_subplot(313, sharex=self.ax1)
        self.ax1.axis("off")
        self.ax2.axis("off")
        self.ax3.axis("off")
        self.canvas = FigureCanvasTkAgg(self.figure, self.frame2_2)
        self.canvas.draw()
        #canvas.get_tk_widget().pack(fill=tkinter.BOTH, expand=True)
        self.canvas.get_tk_widget().grid(row=1, column=0, sticky=E)

        toolbar = NavigationToolbar2Tk(self.canvas, self.frame2_2)
        toolbar.update()
        self.canvas._tkcanvas.pack(side=tkinter.TOP,
                                   fill=tkinter.BOTH,
                                   expand=True)
        #############################Frame 2_2, plot of results#############################
        ####################################################################################

        ####################################################################################
        #########################Frame 2_3, Properties of Training Dataset##################
        self.frame2_3 = tkinter.Frame(self.frame2, bg="gray90")
        self.frame2_3.grid(row=1, column=0, sticky="wn")
        l_info = tkinter.Label(self.frame2_3,
                               text="Info. of Training Dataset: ",
                               background="SkyBlue4",
                               foreground="White")

        l_info.grid(row=0, column=0, sticky="ws",
                    columnspan=2)  # position "West"
        #self.frame2.rowconfigure(0, weight=3)
        #blue
        l_info1 = Label(self.frame2_3, text="TS length: ", foreground="blue")
        l_info2 = Label(self.frame2_3, text="TS number: ", foreground="blue")
        l_info3 = Label(self.frame2_3, text="Nbr class: ", foreground="blue")

        l_info4 = Label(self.frame2_3,
                        text="Source class: ",
                        foreground="blue")
        l_info5 = Label(self.frame2_3,
                        text="Target class: ",
                        foreground="blue")

        self.v_dsname = StringVar()
        self.v_tslength = IntVar()
        self.v_tsnbr = IntVar()
        self.v_classnbr = IntVar()
        self.v_sourceC = StringVar()
        self.v_targetC = StringVar()

        l_dataset = Label(self.frame2_3,
                          textvariable=self.v_dsname,
                          foreground="red")
        l_tslength = Label(self.frame2_3,
                           textvariable=self.v_tslength,
                           foreground="red")
        l_tsnbr = Label(self.frame2_3,
                        textvariable=self.v_tsnbr,
                        foreground="red")
        l_classnbr = Label(self.frame2_3,
                           textvariable=self.v_classnbr,
                           foreground="red")

        l_sourceC = Label(self.frame2_3,
                          textvariable=self.v_sourceC,
                          foreground="red")
        l_targetC = Label(self.frame2_3,
                          textvariable=self.v_targetC,
                          foreground="red")
        l_dataset.grid(row=1, column=0, sticky="ws",
                       columnspan=2)  # position "West"
        l_info1.grid(row=2, column=0, sticky="ws")  # position "West"
        l_info2.grid(row=3, column=0, sticky="ws")  # position "West"
        l_info3.grid(row=4, column=0, sticky="ws")  # position "West"
        l_tslength.grid(row=2, column=1, sticky="ws")  # position "West"
        l_tsnbr.grid(row=3, column=1, sticky="ws")  # position "West"
        l_classnbr.grid(row=4, column=1, sticky="ws")  # position "West"
        l_tsnbr.grid(row=3, column=1, sticky="ws")  # position "West"
        l_classnbr.grid(row=4, column=1, sticky="ws")  # position "West"

        l_info4.grid(row=2, column=2, sticky="ws")  # position "West"
        l_info5.grid(row=3, column=2, sticky="ws")  # position "West"
        l_sourceC.grid(row=2, column=3, sticky="ws")  # position "West"
        l_targetC.grid(row=3, column=3, sticky="ws")  # position "West"
        #########################Frame 2_3, Properties of Training Dataset##################
        ####################################################################################

        ####################################################################################
        #########################Frame 2_3, Properties of Testing Dataset###################
        self.frame2_4 = tkinter.Frame(self.frame2, bg="gray90")
        self.frame2_4.grid(row=1, column=1, sticky="wn")
        l_testinfo = tkinter.Label(self.frame2_4,
                                   text="Info. of Testing Dataset: ",
                                   background="SkyBlue4",
                                   foreground="White")

        l_testinfo.grid(row=0, column=0, sticky="ws",
                        columnspan=2)  # position "West"
        # self.frame2.rowconfigure(0, weight=3)
        # blue
        l_testinfo1 = Label(self.frame2_4,
                            text="TS length: ",
                            foreground="blue")
        l_testinfo2 = Label(self.frame2_4,
                            text="TS number: ",
                            foreground="blue")
        l_testinfo3 = Label(self.frame2_4,
                            text="Nbr class: ",
                            foreground="blue")

        self.v_testdsname = StringVar()
        self.v_testtslength = IntVar()
        self.v_testtsnbr = IntVar()
        self.v_testclassnbr = IntVar()

        l_testdataset = Label(self.frame2_4,
                              textvariable=self.v_testdsname,
                              foreground="red")
        l_testtslength = Label(self.frame2_4,
                               textvariable=self.v_testtslength,
                               foreground="red")
        l_testtsnbr = Label(self.frame2_4,
                            textvariable=self.v_testtsnbr,
                            foreground="red")
        l_testclassnbr = Label(self.frame2_4,
                               textvariable=self.v_testclassnbr,
                               foreground="red")

        l_testdataset.grid(row=1, column=0, sticky="ws",
                           columnspan=2)  # position "West"
        l_testinfo1.grid(row=2, column=0, sticky="ws")  # position "West"
        l_testinfo2.grid(row=3, column=0, sticky="ws")  # position "West"
        l_testinfo3.grid(row=4, column=0, sticky="ws")  # position "West"
        l_testtslength.grid(row=2, column=1, sticky="ws")  # position "West"
        l_testtsnbr.grid(row=3, column=1, sticky="ws")  # position "West"
        l_testclassnbr.grid(row=4, column=1, sticky="ws")  # position "West"
        #########################Frame 2_4, Properties of Testing Dataset###################
        ####################################################################################

        ####################################################################################
        #########################Frame 2_4_1, Properties of Testing Dataset###################
        self.frame2_4_1 = tkinter.Frame(self.frame2, bg="gray90")
        self.frame2_4_1.grid(row=1, column=2, sticky="wn")
        l_timeinfo = tkinter.Label(self.frame2_4_1,
                                   text="Running Time (s): ",
                                   background="SkyBlue4",
                                   foreground="White")
        l_timeinfo.grid(row=0, column=0, sticky="ws",
                        columnspan=2)  # position "West"
        l_timeinfo1 = Label(self.frame2_4_1, text="USE ", foreground="blue")
        l_timeinfo2 = Label(self.frame2_4_1, text="SMAP: ", foreground="blue")
        l_timeinfo3 = Label(self.frame2_4_1,
                            text="SMAP_LB: ",
                            foreground="blue")
        self.v_timeUSE = IntVar()
        self.v_timeSMAP = IntVar()
        self.v_timeSMAPLB = IntVar()
        l_timeUSE = Label(self.frame2_4_1,
                          textvariable=self.v_timeUSE,
                          foreground="red")
        l_timeSMAP = Label(self.frame2_4_1,
                           textvariable=self.v_timeSMAP,
                           foreground="red")
        l_timeSMAPLB = Label(self.frame2_4_1,
                             textvariable=self.v_timeSMAPLB,
                             foreground="red")
        l_timeinfo1.grid(row=1, column=0, sticky="ws")  # position "West"
        l_timeinfo2.grid(row=2, column=0, sticky="ws")  # position "West"
        l_timeinfo3.grid(row=3, column=0, sticky="ws")  # position "West"
        l_timeUSE.grid(row=1, column=1, sticky="ws")  # position "West"
        l_timeSMAP.grid(row=2, column=1, sticky="ws")  # position "West"
        l_timeSMAPLB.grid(row=3, column=1, sticky="ws")  # position "West"
        #########################Frame 2_4_1, Properties of Testing Dataset###################
        ####################################################################################

        # Frame 3, extract Shapelets, predict the test instance
        self.frame3 = tkinter.Frame(self, bg="gray90")
        self.frame3.pack(fill=X)
        self.frame3.config(borderwidth=2, relief=GROOVE)

        ######################################################################################
        #########################Frame3_1, Show raw TS & Shapelets############################
        self.frame3_1 = tkinter.Frame(self.frame3, bg="gray90")
        self.frame3_1.grid(row=0, column=0, sticky=W)

        self.v_class = StringVar()
        self.v_k = IntVar()
        l_class = tkinter.Label(self.frame3_1, text="Class", bg="gray90")
        combb_shap_class = Combobox(self.frame3_1,
                                    values=["1.0", "-1.0"],
                                    textvariable=self.v_class,
                                    state='readonly',
                                    width=6)
        b_show_ds = tkinter.Button(self.frame3_1,
                                   text="show TS set",
                                   command=self.guiFunc.showTSset,
                                   highlightthickness=4,
                                   anchor="center",
                                   highlightbackground="gray90",
                                   borderwidth=0)
        l_k = tkinter.Label(self.frame3_1, text="select k", bg="gray90")
        combb_k = Combobox(self.frame3_1,
                           values=self.k_list,
                           textvariable=self.v_k,
                           state='readonly',
                           width=5)
        b_shap_extract = tkinter.Button(
            self.frame3_1,
            text="Show Shapelets",
            command=self.guiFunc.extractShapeletCandidate,
            highlightthickness=4,
            anchor="center",
            highlightbackground="gray90",
            borderwidth=0)
        l_class.grid(row=0, column=0, sticky=W)
        combb_shap_class.grid(row=0, column=1, sticky=W)
        b_show_ds.grid(row=1, column=0, sticky=W, columnspan=2)

        l_k.grid(row=0, column=2, sticky=W)
        combb_k.grid(row=0, column=3, sticky=W)
        b_shap_extract.grid(row=1,
                            column=2,
                            sticky=W + E + N + S,
                            columnspan=2)
        #########################Frame3_1, Show raw TS & Shapelets############################
        ######################################################################################

        self.frame3_2 = tkinter.Frame(self.frame3, bg="gray90")
        self.frame3_2.grid(row=0, column=2, sticky=E, padx=(100, 0))
        self.v_testInstance = StringVar()
        self.v_testInstance.set("select")
        b_testfile = tkinter.Button(
            self.frame3_2,
            text="Import testing data",
            command=self.guiFunc.add_testing_file,
            highlightthickness=4,
            # highlightcolor="SkyBlue4",
            anchor="center",
            highlightbackground="gray90",
            borderwidth=0)
        self.combb_test = Combobox(self.frame3_2,
                                   values=self.guiFunc.testdataset.tsNbrList,
                                   textvariable=self.v_testInstance,
                                   postcommand=self.update_combbtest,
                                   state='readonly',
                                   width=10)
        self.combb_test.bind('<<ComboboxSelected>>', self.callback_test)
        b_predict = tkinter.Button(
            self.frame3_2,
            text="predict",
            command=lambda: self.guiFunc.predict(self),
            highlightthickness=4,
            #highlightcolor="SkyBlue4",
            anchor="center",
            highlightbackground="gray90",
            borderwidth=0)
        b_testfile.grid(row=0, column=0, sticky=W)
        self.combb_test.grid(row=0, column=1, sticky=W)
        b_predict.grid(row=1, column=0, sticky=W + E + N + S, columnspan=2)
Beispiel #31
0
def processFrame(width, height, pixels, agent, mission_count):
    # Attempt some fairly simple image processing in order to determine how many agents the current agent can "see".
    # We rely on the fact that the other agents jut above the horizon line, which is at the mid-point of the image.
    # With the time set to morning, and the weather set to clear, there should always be a good distinction between
    # background (sky) pixels, and foreground (agent) pixels. A bit of thresholding should suffice to provide a
    # fairly reliable way of counting the visible agents.
    global root, bitmaps, failed_frame_count
    channels = 3  # Following code assumes this to be true.

    # 1. Extract a narrow strip of the middle from the middle up:
    y1 = int(height * 0.45)
    y2 = int(height * 0.5)
    if y2 == y1:
        y1 -= 1
    num_rows = y2 - y1
    middle_strip = pixels[y1 * width * channels:y2 * width * channels]

    if SHOW_GUI:
        image_original = Image.frombytes('RGB', (width, num_rows),
                                         str(middle_strip))
        photo_original = ImageTk.PhotoImage(image_original)
        if bitmaps[agent][bmp_original][1] != None:
            canvas.delete(bitmaps[agent][bmp_original][0])
        handle = canvas.create_image(old_div(width, 2),
                                     ((4 * agent) + 0.5) * (num_rows + 5),
                                     image=photo_original)
        bitmaps[agent][bmp_original] = (handle, photo_original)

    # 2. Convert RGB to luminance. Build up a histogram as we go - this will be useful for finding a threshold point.
    hist = [0 for x in range(256)]
    for col in range(0, width * channels, channels):
        for row in range(0, num_rows):
            pix = col + row * width * channels
            lum = int(0.2126 * middle_strip[pix] +
                      0.7152 * middle_strip[pix + 1] +
                      0.0722 * middle_strip[pix + 2])
            hist[lum] += 1
            middle_strip[pix] = middle_strip[pix + 1] = middle_strip[
                pix + 2] = lum  # assuming channels == 3

    if SHOW_GUI:
        image_greyscale = Image.frombytes('RGB', (width, num_rows),
                                          str(middle_strip))
        photo_greyscale = ImageTk.PhotoImage(image_greyscale)
        if bitmaps[agent][bmp_luminance][1] != None:
            canvas.delete(bitmaps[agent][bmp_luminance][0])
        handle = canvas.create_image(old_div(width, 2),
                                     ((4 * agent + 1) + 0.5) * (num_rows + 5),
                                     image=photo_greyscale)
        bitmaps[agent][bmp_luminance] = (handle, photo_greyscale)

    # 3. Calculate a suitable threshold, using the Otsu method
    total_pixels = width * num_rows
    total_sum = 0.
    for t in range(256):
        total_sum += t * hist[t]
    sum_background = 0.
    weight_background = 0.
    weight_foreground = 0.
    max_variation = 0.
    threshold = 0
    for t in range(256):
        weight_background += hist[t]
        if weight_background == 0:
            continue
        weight_foreground = total_pixels - weight_background
        if weight_foreground == 0:
            break
        sum_background += t * hist[t]
        mean_background = old_div(sum_background, weight_background)
        mean_foreground = old_div((total_sum - sum_background),
                                  weight_foreground)
        # Between class variance:
        var = weight_background * weight_foreground * (
            mean_background - mean_foreground) * (mean_background -
                                                  mean_foreground)
        if var > max_variation:
            max_variation = var
            threshold = t

    # 4. Apply this threshold
    for pix in range(len(middle_strip)):
        if middle_strip[pix] <= threshold:
            middle_strip[pix] = 255
        else:
            middle_strip[pix] = 0

    # 5. OR together all the rows. This helps to de-noise the image.
    # At the same time, we count the number of changes (from foreground to background, or background to foreground)
    # that occur across the scanline. Assuming that there are no partial agents at the sides of the view - ie the scanline
    # starts and ends with background - this count should result in two changes per visible agent.
    pixelvalue = lambda col: sum(middle_strip[x] for x in range(
        col, len(middle_strip), width * channels))
    lastval = 255
    changes = 0
    for col in range(0, width * channels, channels):
        val = 0 if pixelvalue(col) > 0 else 255
        if lastval != val:
            changes += 1
        lastval = val
        if SHOW_GUI:
            # Update the bitmap so the user can see what we see.
            for row in range(num_rows):
                middle_strip[col + row * width * channels] = val
                middle_strip[1 + col + row * width * channels] = val
                middle_strip[
                    2 + col + row * width *
                    channels] = 0  # blue channel always 0 (will simplify recolouring later)

    # 6. Perform the actual test.
    agents_detected = old_div(changes, 2)
    test_passed = agents_detected == NUM_AGENTS - 1

    # 7. If we're displaying the gui, recolour the final image - turn the background red for error or green for success.
    # (At the moment all background pixels have both red and green values set to 255, so all we need to do is remove
    # the relevant channel.)
    if SHOW_GUI:
        channel_mask = 0 if test_passed else 1  # Remove red channel for success, remove green for failure
        for pixel in range(channel_mask, len(middle_strip), channels):
            middle_strip[pixel] = 0
        # And add this to the GUI:
        image_threshold = Image.frombytes('RGB', (width, num_rows),
                                          str(middle_strip))
        photo_threshold = ImageTk.PhotoImage(image_threshold)
        if bitmaps[agent][bmp_thresholded][1] != None:
            canvas.delete(bitmaps[agent][bmp_thresholded][0])
        handle = canvas.create_image(old_div(width, 2),
                                     ((4 * agent + 2) + 0.5) * (num_rows + 5),
                                     image=photo_threshold)
        bitmaps[agent][bmp_thresholded] = (handle, photo_threshold)
        # Update the canvas:
        root.update()

    if not test_passed:
        # The threshold is not entirely bullet-proof - sometimes there are drawing artifacts that can result in
        # false negatives.
        # So we save a copy of the failing frames for manual inspection:
        image_failed = Image.frombytes('RGB', (width, height), str(pixels))
        image_failed.save(FAILED_FRAME_DIR + "/failed_frame_agent_" +
                          str(agent) + "_mission_" + str(mission_count) + "_" +
                          str(failed_frame_count) + ".png")
        failed_frame_count += 1
    return test_passed
Beispiel #32
0
    def detectPartyImage(self, img, template):
        # panelA.grid_forget()
        img_0 = img.copy()
        # -------------------<Ballot paper>----------------------------

        # Grayscale
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        # Apply blur to reduce noise
        gray = cv2.GaussianBlur(gray, (5, 5), 0)

        # Detect edges
        cannyout = cv2.Canny(gray, 50, 100, 5)

        # Find contours
        im2, contours, hierarchy = cv2.findContours(cannyout.copy(),
                                                    cv2.RETR_EXTERNAL,
                                                    cv2.CHAIN_APPROX_SIMPLE)

        # Select the contours with convexity and four points
        contours = [
            contour for contour in contours
            if not cv2.isContourConvex(contour) and len(
                cv2.approxPolyDP(contour, 0.02 *
                                 cv2.arcLength(contour, True), True)) == 4
        ]

        # contours = sorted(contours, key=lambda x: (cv2.contourArea(x)), reverse=True)

        # ------------------</Ballot paper>----------------------------

        # ------------------<Party sign>-------------------------------

        # Read the image
        # template_ori = cv2.imread(path, 0)
        template_ori = template
        # template = cv2.bilateralFilter(template_ori,9,75,75)
        # template = cv2.medianBlur(template_ori,5)
        # template = cv2.fastNlMeansDenoising(template_ori,None,10,7,21)

        # Apply blur to reduce noise
        template = cv2.GaussianBlur(template_ori, (5, 5), 0)

        # thresh, template = cv2.threshold(template, 200, 255, cv2.THRESH_BINARY)

        # Detect edges
        template_edges = cv2.Canny(template, 100, 200, 10)

        # ------------------</Party sign>-------------------------------

        # ------------------<BRISK descriptors>---------------------------

        # Create the BRISK descriptor detector
        detector = cv2.BRISK_create(10, 1)

        # Compute descriptors and keypoints in image and template
        kp1, des1 = detector.detectAndCompute(gray, None)
        kp2, des2 = detector.detectAndCompute(template, None)

        # Create the matcher
        bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

        # Match the descriptors
        matches = bf.match(des1, des2)
        # Sort matches by distances
        matches = sorted(matches, key=lambda x: x.distance)
        # Compute the distances for matches
        distances = [match.distance for match in matches]

        # Min distance
        min_dist = min(distances)
        # Average distance
        avg_dist = sum(distances) / len(distances)

        # Define tolerance
        min_tolerance = 10

        # Compute the new min distance
        min_dist = min_dist or avg_dist * 1.0 / min_tolerance

        # Select the good matches based on the min distance
        good_matches = [
            match for match in matches
            if match.distance <= min_dist * min_tolerance
        ]

        # Get matched points in the image and the symbol
        ballot_matched_points = np.array(
            [kp1[match.queryIdx].pt for match in good_matches])
        party_matched_points = np.array(
            [kp2[match.trainIdx].pt for match in good_matches])

        # ------------------<Find homography>---------------------------
        # Find homography
        homography, h_mask = cv2.findHomography(party_matched_points,
                                                ballot_matched_points,
                                                cv2.RANSAC, 2.0)

        h, w = template_ori.shape[0:2]
        sh, sw = img.shape[0:2]

        pts = np.array([(0, 0), (w, 0), (w, h), (0, h)], dtype=np.float32)

        # Perspective transformation using homography
        dst = cv2.perspectiveTransform(pts.reshape(1, -1, 2),
                                       homography).reshape(-1, 2)
        # print(dst)
        # Draw lines in the image
        img_0 = cv2.polylines(img_0, [np.int32(dst)], True, (0, 255, 0), 3,
                              cv2.LINE_AA)

        # ------------------</Find homography>---------------------------

        # im3 = cv2.drawMatches(img, kp1, template, kp2, good_matches, None, flags=2)

        # ------------------</BRISK descriptors>---------------------------

        # Resize the image
        im3 = cv2.resize(img_0, (0, 0), fx=0.25, fy=0.25)

        # -------------------<Image display processing>-------------------
        # This is for Tkinter gui
        template_ori = Image.fromarray(template_ori)
        template_edges = Image.fromarray(template_edges)

        template_ori = ImageTk.PhotoImage(template_ori)
        template_edges = ImageTk.PhotoImage(template_edges)

        # -------------------</Image display processing>-------------------

        # Update panels
        if self.panelA is None or self.panelB is None:

            self.panelA = Label(self.topframe, image=template_ori)
            self.panelA.image = template_ori
            self.panelA.pack(side='left', padx=10, pady=10)
            self.panelA.grid(row=0, column=0, padx=10, pady=10)

            self.panelB = Label(self.topframe, image=template_edges)
            self.panelB.image = template_edges
            self.panelB.pack(side='left', padx=10, pady=10)
            self.panelB.grid(row=0, column=1, padx=10, pady=10)

        else:
            # panelA.grid_forget()
            # panelB.grid_forget()
            self.panelA.configure(image=template_ori)
            self.panelB.configure(image='')
            self.panelB.configure(image=template_edges)
            self.panelA.image = template_ori
            self.panelB.image = template_edges