在Tkinter中单击按钮,在Opencv中显示图像

时间:2015-12-09 14:27:49

标签: python-2.7 opencv tkinter raspberry-pi2

我一直致力于Tkinter GUI和新手。现在我想在单独的窗口中单击按钮时使用Opencv显示图像,所以首先使用askopenfilename()获取图像路径,然后将该值传递给cv2.imread() 下面是代码。

openpath = filedialog.askopenfilename()
if openpath:
   image = cv2.imread(openpath)
   cv2.imshow("slot", image)
   cv2.waitKey(0)
   cv2.destroyWindow("slot")

图像显示在新窗口中,但当我尝试关闭它时,Tkinter应用程序也会关闭。我需要在图像上执行一些任务,然后在按键上关闭它而不影响我的Tkinter应用程序。可以使用线程完成。如果是,那我该怎么办呢?请指导 谢谢

1 个答案:

答案 0 :(得分:0)

此代码段是一种解决方法。它在画布TKinter中打开图像。

def __init__(self, parent):
    self.parent = parent
    self.create_frame()

def create_frame(self):
    global image

    cv_frame = Frame(self.parent)
    cv_frame.pack()
    imagepath = load_image()
    image = Image.open(imagepath)
    image = image.resize((1072, 650), Image.ANTIALIAS)
    tkpi = ImageTk.PhotoImage(image)
    canvas = Canvas(cv_frame, width=tkpi.width(), height=tkpi.height())
    canvas.pack(side="top", fill="both", expand=True)
    canvas.create_image(0, 0, anchor="nw", image=tkpi)
    canvas.bind("<Button-1>", self.pressdown)                      ##binding for left button when its pressed
    canvas.bind("<ButtonRelease-1>", self.pressup)                 ##binding for left button when its released
    canvas.bind("<Double-Button-3>", self.reset)                   ##binding for right button double click will reset the drawn lines 
    canvas.image = tkpi
    canvas.pack()

    frame = Frame(cv_frame)
    frame.pack()
    crop = Button(frame, text="Crop", width=6, command=self.crop)
    crop.pack(side=LEFT)
    save = Button(frame, text="Save", width=6, command=self.save)
    save.pack(side=LEFT)

def pressdown(self, event):                       ##event handler for left button when button is pressed
    coords.append(event.x)
    coords.append(event.y)
    allpoints.append((event.x, event.y))

def pressup(self, event):                       ##event handler for left button when released
    cord.append(event.x)
    cord.append(event.y)
    allpoints.append((event.x, event.y))
    event.widget.create_line(coords[0], coords[1], cord[0], cord[1], fill="green", width=4, dash=(4, 4), tag="line")