在Tkinter中加载大图像会导致MemoryError

时间:2018-12-17 22:46:12

标签: python image-processing tkinter out-of-memory tkinter-canvas

我的背景是我是一名微生物学家,在编程方面自学成才。如果有更简便的方法或清理代码的方法,我总是乐于接受建设性的批评和改进的方法。我正在尝试使用以下代码使用python的tkinter创建GUI:

import sys
import cv2

from tkinter import *
from PIL import ImageTk, Image
import cv2

class TypeOneDetectionEditor(object):
    def __init__(self):

        image_file = "6wk_Control_B_01.png"  # Update the file as needed

        self.image_cv = cv2.imread(image_file)
        self.resize_factor = 0.1
        self.height, self.width, self.channel = self.image_cv.shape

        self.window = Tk()
        self.frame = Frame(self.window, bd=5, relief = SUNKEN)

        # Hard-code choice of resolution for canvas and scroll region as
        # maximum shape of images*resize_factor
        self.canvas = Canvas(self.frame, bg="#000000", width=1366, height=768,
                             scrollregion=(0, 0, self.width*self.resize_factor,
                                           self.height*self.resize_factor))

        # Scrollbars
        hbar=Scrollbar(self.frame,orient=HORIZONTAL)
        hbar.pack(side=BOTTOM,fill=X)
        hbar.config(command=self.canvas.xview)
        vbar=Scrollbar(self.frame,orient=VERTICAL)
        vbar.pack(side=RIGHT,fill=Y)
        vbar.config(command=self.canvas.yview)
        self.canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set)

        # Img + Event listeners
        # Literally because tkinter can't handle references properly and needs this.
        self.canvas.image = ImageTk.PhotoImage(Image.fromarray(self.image_cv))
        # So we can change the image later
        self.canvas_image_config = self.canvas.create_image(0, 0,
                                                            image=self.canvas.image,
                                                            anchor="nw")
        # Sets the focus to our program besides putting it in the background
        self.canvas.focus_set()
        # Put future functions here
        self.canvas.pack(side=LEFT)
        self.window.mainloop()

TypeOneDetectionEditor()

我收到的错误指出:

Traceback (most recent call last):
  File "Bacterial Counter GUI.py", line 45, in <module>
    TypeOneDetectionEditor()
  File "Bacterial Counter GUI.py", line 35, in __init__
    self.canvas.image = ImageTk.PhotoImage(Image.fromarray(self.image_cv))#Literally because tkinter can't handle references properly and needs this.
  File "C:\Users\basay3\AppData\Local\Continuum\anaconda3\lib\site-packages\PIL\ImageTk.py", line 120, in __init__
    self.paste(image)
  File "C:\Users\basay3\AppData\Local\Continuum\anaconda3\lib\site-packages\PIL\ImageTk.py", line 175, in paste
    block = image.new_block(self.__mode, im.size)
MemoryError

我已经更新了我的tkinter库和枕头库,但是仍然不能解决问题。我尝试使用的图像为604 MB(太大,无法上传到这篇文章),并且我的计算机上有16 GB的内存。我不知所措,所以在这一点上任何建议都将是有帮助的。

0 个答案:

没有答案