计算绿色像素的百分比 - 错误

时间:2021-02-21 11:29:05

标签: python tkinter

我需要计算图像中绿色像素的百分比。为此,我使用 open() 函数打开并显示图像,使用 calc_green() 函数计算绿色像素的百分比。我创建了一个按钮来调用 calc_green() 函数。当我运行代码并单击按钮时,我收到错误消息:“TypeError:calc_green() 缺少 1 个必需的位置参数:'my_image'”。我该如何解决这个问题?

from tkinter import *
from tkinter import filedialog
from PIL import ImageTk, Image
import numpy as np

root = Tk()
root.title("Photo Analysis")
root.geometry('1360x765')
root.iconbitmap(r'icon.ico')

main_frame = Frame(root)
main_frame.pack(fill="both", expand=True)

def open():

    for widget in img_display_canvas.winfo_children():
        widget.destroy()

    global my_image
    filename = filedialog.askopenfilename(initialdir="/", title="Select A File", filetypes=(("all files", "*.*"), ("jpg files", "*.jpg"), ("png files", "*.png")))
    my_image = ImageTk.PhotoImage(Image.open(filename))
    my_image_label = Label(img_display_canvas, image=my_image).pack()
    return my_image

open_btn = Button(main_frame, text="Open File", padx=5, pady=2, font=('arial', 10, 'bold'), command=open)
open_btn.pack(pady=10)

img_display_canvas = Canvas(main_frame, width=800, height=450, bg='#d8d8d8')
img_display_canvas.pack()

def calc_green(my_image):
    img = Image.open(my_image)
    pixels = img.load()
    width, height = img.size
    total_green = 0
    for x in range(width):
        for y in range(height):
            rgb = pixels[x, y]
            if rgb[1] > rgb[0] and rgb[1] > rgb[2]:
                total_green = total_green + 1
    percent = (total_green / (width * height)) * 100
    print(str(percent) + " %")

calc_green_btn = Button(main_frame, text="Calc Green %", padx=5, pady=2, font=('arial', 10, 'bold'), bg='#009900', activebackground='#009900', command = calc_green)
calc_green_btn.pack()

0 个答案:

没有答案
相关问题