【问题标题】:Image won't clear when saved from Tkinter canvas从 Tkinter 画布保存时图像不会清除
【发布时间】:2020-08-21 00:07:27
【问题描述】:

我正在使用我制作的模型使用 Tkinter 制作手写数字解释器。我保存画布图像,然后通过我的模型读回它以获得预测。我用 cv.delete("all") 清除画布,然后绘制另一个数字进行预测,得到一个不稳定的预测。

初步结果:(3 是 3 :)!!!)

然后我清除它并写另一个数字:

然后我转到保存图像的文件夹,图片如下所示:

这是我的代码,用于定义我的画布和我要绘制的图像。

# define the canvas and image to save
lastx, lasty = None, None

cv = Canvas(root, width=420, height=420, bg='black')
image1 = PIL.Image.new("L",(420,420),"black")
draw = ImageDraw.Draw(image1)

cv.bind('<1>', activate_paint)
cv.pack(expand=YES, fill=BOTH)

这是我用来绘制的代码:

 def activate_paint(e):
    global lastx, lasty
    cv.bind('<B1-Motion>', paint)
    lastx, lasty = e.x, e.y

def paint(e):
    global lastx, lasty
    x, y = e.x, e.y
    cv.create_line((lastx, lasty, x, y), fill = 'white',width=30)
    #  --- PIL
    draw.line((lastx, lasty, x, y), fill='white', width=30)
    lastx, lasty = x, y

这是我点击预测按钮时用来保存它的代码:

filename = f'img_to_predict.png'
image1.save(filename)

我只需要清除按钮来使图像真正空白,这样它就不会保存在以前的图像上。谁能把我推向正确的方向?

谢谢!

杰克逊

【问题讨论】:

  • 您还需要通过调用draw.rectangle((0, 0, 420, 420), fill="black")来清除图像。

标签: python image canvas tkinter save


【解决方案1】:

更新:这似乎根本不重要,所以请忽略它

假设您复制粘贴了cv.delete("all") 行,问题可能是使用“all”作为字符串。您可能需要cv.delete(ALL) 来清除它?

【讨论】:

  • 其实ALL等于tkinter中的'all'
  • 感谢您的回复!这没有解决问题...我现在将尝试您的其他解决方案。
【解决方案2】:

您还需要通过调用清除图像

draw.rectangle((0, 0, 420, 420), fill="black")

但是,我建议删除图像上的绘图。只需在画布上绘图,然后使用ImageGrab.grab()(也来自Pillow 模块)在画布上拍摄快照,并在需要进行预测时将快照保存到文件中:

# get the canvas bounding box on screen
x, y = cv.winfo_rootx(), cv.winfo_rooty()
w, h = cv.winfo_width(), cv.winfo_height()
# take a snapshot on the canvas and save the image to file
ImageGrab.grab((x, y, x+w, y+h)).save('img_to_predict.png')

【讨论】:

  • 您的第一段代码就成功了。谢谢!我的代码在画布上绘制而不是在图像上绘制有何不同?
猜你喜欢
  • 2012-07-26
  • 1970-01-01
  • 1970-01-01
  • 2015-07-17
  • 2016-08-22
  • 1970-01-01
  • 2013-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多