我已经创建了tkinter和cv2组合的程序,用于将彩色图像转换为黑白图像,但我不知道如何添加保存黑白图像的按钮。怎么做
# importing the Packages
import cv2 # importing cv2 package for converting the colored imaged to gray or vice versa
import tkinter as tk # importing tkinter package for creating Gui and its instance io created is tk
from tkinter import filedialog as fd # importing the filedialog package from tkinter to open the file default file explorer
from PIL import Image, ImageTk # Python imaginary library for performing operation on images
root = tk.Tk()
root.title("Color to blackNwhite Convertor")
root.config(bg='#FFFAFA')
def selectimage():
global panelA,panelB #used two global variables to create two panels
location = fd.askopenfilename()
if len(location) > 0:
image = cv2.imread(location)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# convert the images to PIL format...
image = Image.fromarray(image)
gray = Image.fromarray(gray)
# ...and then to ImageTk format
image = ImageTk.PhotoImage(image)
gray = ImageTk.PhotoImage(gray)
if panelA is None or panelB is None:
panelA = tk.Label(image=image)
panelA.image = image
panelA.pack(side="left", padx=10, pady=10)
panelB = tk.Label(image=gray)
panelB.image = gray
panelB.pack(side="right", padx=10, pady=10)
else:
panelA.configure(image=image)
panelB.configure(image=gray)
panelA.image = image
panelB.image = gray
panelA = None
panelB = None
btn = tk.Button(root, text="Select an image",font=('arial',10,'bold'),bg="cyan", command=selectimage)
btn.config(height=5,width=15)
btn.pack(side="bottom", fill="both", expand="yes", padx="10", pady="10")
# kick off the GUI
root.mainloop()
您应该保留由
Image.fromarray(gray)
返回的图像的引用,然后创建一个按钮来触发回调以使用灰色图像上的save()
保存灰色图像:您可能需要创建postscript文件:
然后使用Pillow将postscript文件保存为png:
相关问题 更多 >
编程相关推荐