我尝试使用“ tkinter”按钮使“另存为”按钮将图像保存到某个位置目录中,但是出现问题
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from PIL import ImageTk, Image, ImageDraw
import cv2
import numpy as np
img = cv2.imread('face_person1.jpg')
# convert the images to PIL format...
edged = Image.fromarray(img)
edged = ImageTk.PhotoImage(edged)
def savefile():
hsl = Image.open(edged)
hsl = filedialog.asksaveasfile(mode='w', defaultextension=".jpg")
if hsl is None:
return
sv = edged.save()
sv.close()
button = Button(text="save as", command=savefile)
button.pack()
错误消息是:
Exception in Tkinter callback fp = io.BytesIO(fp.read())
AttributeError: 'numpy.ndarray' object has no attribute 'read'
答案 0 :(得分:1)
要保存图像,您必须使用PIL.Image
,所以不要将PhotoImage
分配给用于保留PIL.Image
的变量
edge = Image.fromarray(img)
tk_edge = ImageTk.PhotoImage(edge)
并且您必须使用文件名进行保存
edge.save(filename)
完整的示例
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from PIL import ImageTk, Image, ImageDraw
import cv2
import numpy as np
# --- functions ---
def savefile():
filename = filedialog.asksaveasfile(mode='w', defaultextension=".jpg")
if not filename:
return
edge.save(filename)
# --- main ---
root = tk.Tk()
img = cv2.imread('face_person1.jpg')
edge = Image.fromarray(img)
tk_edge = ImageTk.PhotoImage(edge)
label = tk.Label(root, image=tk_edge)
label.pack()
button = tk.Button(root, text="save as", command=savefile)
button.pack()
root.mainloop()