【问题标题】:cv2.imwrite function not running properlycv2.imwrite 函数运行不正常
【发布时间】: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() 的问题可能是您正在尝试加入相对路径。尝试使用绝对路径。

标签: python opencv tkinter


【解决方案1】:

问题是您在os.path.join(path, imagein) 中使用了imageinImageTk.PhotoImage() 的一个实例。

其实你根本不需要imagein,只需使用root.fileBrowse就足够了。您也可以使用PIL.Image 来读取和写入图像,而不是使用cv2 模块。

以下是修改后的enchance_image()

def enhance_image():
    ### make sure `root.fileBrowse` is set
    image = ImageEnhance.Color(Image.open(root.fileBrowse)).enhance(0.5)
    path = "cc_folder"
    if not os.path.exists(path):
        os.makedirs(path)
    fname = os.path.basename(root.fileBrowse)
    image.save(os.path.join(path, fname))

【讨论】:

    猜你喜欢
    • 2023-03-21
    • 2019-09-01
    • 2020-02-27
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多