【发布时间】:2021-05-24 10:40:23
【问题描述】:
enhance_image() 函数应该将编辑后的照片写入文件夹。但它什么也没做。它甚至不会在命令行中返回错误,所以我很难找到哪里出错了。
import tkinter as tk
from tkinter import *
from PIL import ImageTk, Image, ImageEnhance
import tkinter.filedialog
import os, os.path
import cv2
root = tk.Tk()
root.geometry("600x500")
frame = tkinter.Frame(root, bg='gray')
frame.place(relx=0.1, rely=0.1, relwidth=0.8, relheight=0.8)
# Prompt a user to select an image by opening file explorer
def select_image():
global myFiles, fileBrowse
root.fileBrowse = tkinter.filedialog.askopenfilename()
fileLabel = Label(frame, text=root.fileBrowse, bg='gray', fg='white').pack()
# Enhance image
def enhance_image():
imagein = cv2.imread(root.fileBrowse)
ImageEnhance.Color(Image.open(root.fileBrowse)).enhance(0.5)
imagein = Image.fromarray(imagein)
imagein = ImageTk.PhotoImage(imagein)
# Make a folder then save the enhanced image there
if not os.path.exists('cc_folder'):
os.makedirs('cc_folder')
path = 'cc_folder'
cv2.imwrite(os.path.join(path, imagein))
appTitle = Label(root, text="AutoCC", font=("Colombo", 20, 'bold')).pack()
browseBtn = Button(frame, text="Browse Files", command=select_image)
browseBtn.pack(padx=0.2, pady=0)
enhanceBtn = Button(frame, text="Start", command=enhance_image).pack()
root.mainloop()
【问题讨论】:
-
如果
cc_folder不存在,我在cv2.imwrite(os.path.join(path, imagein))线上得到TypeError: join() argument must be str, bytes, or os.PathLike object, not 'PhotoImage'。如果cc_folder存在,cv2.imwrite(...)将不会被执行。 -
或者你可以使用
tkinter.filedialog.asksaveasfilename来获取保存路径。您可能应该更改缩进级别。 -
@acw1668 'os.makedirs' 对你不起作用吗? Python 为我做了一个,所以我知道它至少应该写在那里。
-
是的,我知道
os.makedirs()有效。但是你明白我的意思吗?当cc_folder不存在时,将创建文件夹,执行cv2.imwrite(...)时出现错误。在创建cc_folder并再次执行enhance_image()后,cv2.imwrite(...)将不会被执行,因为if not os.path.exists('cc_folder')将被评估为 False。 -
好吧,
join()的问题可能是您正在尝试加入相对路径。尝试使用绝对路径。