实现多种颜色转换器选择的多重Elif导致“未来警告”

2024-06-17 11:12:04 发布

您现在位置:Python中文网/ 问答频道 /正文

各位。我有一个关于在Python中实现颜色转换器选择的多选列表的问题。 这是密码

选项列表

effectoption = ["Effect RGB",
                "Effect HSV",
                "Effect LAB",
                "Effect RGBA",
                "Effect HLS"]

否则

if effect == effectoption[0] :
    edited = cv2.cvtColor(edited, cv2.COLOR_BGR2RGB)
elif effect == effectoption[1] :
    edited = cv2.cvtColor(edited, cv2.COLOR_BGR2HSV)
elif effect == effectoption[2] :
    edited = cv2.cvtColor(edited, cv2.COLOR_BGR2LAB)
elif effect == effectoption[3] :
    edited = cv2.cvtColor(edited, cv2.COLOR_BGR2RGBA)
elif effect == effectoption[4] :
    edited = cv2.cvtColor(edited, cv2.COLOR_BGR2HLS)

当前代码为

#image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
on_change(image) #the code will print none and this code was supposed for get value of effect option for applying image

颜色转换器的设置在这里

opt = tk.OptionMenu(window, var1, *effectoption)
opt.config(width=90, font=('Helvetica', 12))
opt.pack(side="top")

这是完整的代码

import tkinter as tk
from PIL import Image as PILImage
from PIL import ImageTk
from tkinter import Label
from tkinter import filedialog
from tkinter import ttk
from tkinter import Menu
import cv2
#import matplotlib.pyplot as plt
import numpy as np
 
WINDOW_NAME = "CV2 Photo Editor"

"""
effectoption = ["Effect RGB",
                "Effect HSV",
                "Effect LAB",
                "Effect RGBA",
                "Effect HLS", "Effect GRAY"]
"""
effectoption = [("Effect RGB"),
                ("Effect HSV"),
                ("Effect LAB"),
                ("Effect RGBA"),
                ("Effect HLS"), ("Effect GRAY")]

 
effectoption2 = ["Original(RGB)",
                 "Original(HSV)",
                 "Effect3"]
 
def on_change(effect):
    if effect == effectoption[0]:
        edited = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        var1.set(effectoption[0])
        print(var1.get())
    if effect == effectoption[1]:
        edited = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
        var1.set(effectoption[1])
        print(var1.get())
    if effect == effectoption[2]:
        edited = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
        var1.set(effectoption[2])
        print(var1.get())
    if effect == effectoption[3]:
        edited = cv2.cvtColor(image, cv2.COLOR_BGR2RGBA)
        var1.set(effectoption[3])
        print(var1.get())
    if effect == effectoption[4]:
        edited = cv2.cvtColor(image, cv2.COLOR_BGR2HLS)
        var1.set(effectoption[4])
        print(var1.get())
    if effect == effectoption[5]:
        edited = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        var1.set(effectoption[5])
        print(var1.get())
    else :
        edited = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    print(effect)
    #print(edited)
def insertbutton_cb():
    #global orima, editima
    global image, edited
 
    picpath = filedialog.askopenfilename(
        title="Select An Image",
        filetypes=(("JPG Files", "*.jpg"), ("GIF Files", "*.gif*"), ("PNG files", "*.png"), ("JPEG Files", "*.jpeg"))
    )
 
    if len(picpath) > 0:
        
        bright = 255
        contrast = 100
        saturation = 50
        
 
        image = cv2.imread(picpath)
        edited = cv2.imread(picpath)
 
        edited = np.array(edited)
        #edited = PILImage.fromarray(edited.astype('uint8'))
 
        print(picpath)
        print('Original Dimensions : ',image.shape)
        print(image)
        print(edited)
 
        scale_percent = 50 # percent of original size
        width = int(image.shape[1] * scale_percent / 100)
        height = int(image.shape[0] * scale_percent / 100)
        width2 = int(edited.shape[1] * scale_percent / 100)
        height2 = int(edited.shape[0] * scale_percent / 100)
        dim = (width, height)
        dim2 = (width2, height2)
 
        image = cv2.resize(image, dim, interpolation = cv2.INTER_AREA)
        edited = cv2.resize(edited, dim2, interpolation = cv2.INTER_AREA)
 
        #if effectoption[0] :
            #edited = cv2.cvtColor(edited, cv2.COLOR_BGR2RGB)
        #elif effectoption[1] :
            #edited = cv2.cvtColor(edited, cv2.COLOR_BGR2HSV)
        #elif effectoption[2] :
            #edited = cv2.cvtColor(edited, cv2.COLOR_BGR2LAB)
        #elif effectoption[3] :
            #edited = cv2.cvtColor(edited, cv2.COLOR_BGR2RGBA)
        #elif effectoption[4] :
            #edited = cv2.cvtColor(edited, cv2.COLOR_BGR2HLS)
 
        #image = cv2.cvtColor(image, cv2.COLOR_BGR2RGBA)
        #on_change(image)
        print(on_change(image))
        #edited = cv2.cvtColor(edited, cv2.COLOR_BGR2RGB)
 
        image =  PILImage.fromarray(image)
        edited = PILImage.fromarray(edited)
 
        #xa, ya, za = np.shape(image)
        #xb, yb, zb = np.shape(edited)
 
        #image = np.ones((xa, ya, za), np.uint8)
        #edited = np.ones((xb, yb, zb), np.uint8)
 
        image = np.uint8(image)
        edited = np.uint8(edited)
 
        #hueSlider = tk.Scale(Frm2, label="Hue",from_=0, to=100, orient=tk.HORIZONTAL, length=sw, resolution=1, command=huecb)
        #hueSlider.pack(anchor=tk.N)
 
        #saturationSlider = tk.Scale(Frm2, label="Saturation",from_=0, to=100, orient=tk.HORIZONTAL, length=sw, resolution=1, command=satcb)
        #saturationSlider.pack(anchor=tk.N)
 
        #brightSlider = tk.Scale(Frm2, label="Brightness",from_=0, to=100, orient=tk.HORIZONTAL, length=sw, resolution=1, command=brightcb)
        #brightSlider.pack(anchor=tk.N)
 
        #contrastSlider = tk.Scale(Frm2, label="Contrast",from_=0, to=100, orient=tk.HORIZONTAL, length=sw, resolution=1, command=contrastcb)
        #contrastSlider.pack(anchor=tk.N)

        #create trackbars for high,low H,S,V 
 
        cv2.namedWindow(WINDOW_NAME)
        cv2.createTrackbar('Bright', WINDOW_NAME, 255, 2 * 255, bccb)
        cv2.createTrackbar('Contrast', WINDOW_NAME, 255, 2 * 127, bccb)
        cv2.createTrackbar('Saturation', WINDOW_NAME, 255, 2 * 255, bccb)
        #functionbcs(edited, 0, 0, 0)
        bccb(0, 0, 0)
        teste = controller(image, bright, contrast, saturation)
        cv2.imshow(WINDOW_NAME, teste)
 
        #cv2.waitKey(0)
    """
    if orima is None or editima is None:
        orima = Label(image=image)
        orima.image = image
        orima.pack(side="left", padx= 0, pady=0)
 
        editima = Label(image=edited)
        editima.image = edited
        editima.pack(side="right", padx= 0, pady=0)
    else:
        orima.configure(image=image)
        editima.configure(image=edited)
        orima.image = image
        editima.image = edited
    """
 
def resetbutton_cb():
    """
    orima = None
    editima = None
    """
    pass
 
def savebutton_cb():
    pass
 
"""
def functionbcs(edited, bright=0, contrast=0, saturation=0):
 
    #edited = cv2.cvtColor(edited, cv2.COLOR_BGR2RGB)
    bright = cv2.getTrackbarPos('Bright','CV2 Photo Editor')
    contrast = cv2.getTrackbarPos('Contrast','CV2 Photo Editor')
    saturation = cv2.getTrackbarPos('Saturation','CV2 Photo Editor')
    edited = controller(edited, bright, contrast, saturation)
    #print("Edited : " + edited)
    print(edited)
    cv2.imshow("Edited", edited)
 
def satcb(satpos = 0):
    print(satpos)
"""
 
def bccb(bright = 0, contrast=0, saturation=0):
    bright = cv2.getTrackbarPos('Bright', WINDOW_NAME)
    print("B : " + str(bright))
    contrast = cv2.getTrackbarPos('Contrast', WINDOW_NAME)
    print("C : " + str(contrast))
    saturation = cv2.getTrackbarPos('Saturation', WINDOW_NAME)
    print("S : " + str(saturation))
 
    edited = controller(image, bright, contrast, saturation)
    cv2.imshow(WINDOW_NAME, edited)
 
def controller(effect, bright=1, contrast=1, saturation=1):
    bright = int((bright - 0) * (255 - (-255)) / (510 - 0) + (-255))
 
    contrast = int((contrast - 0) * (127 - (-127)) / (254 - 0) + (-127))
 
    saturation = int((saturation - 0) * (100 - (-100)) / (200 - 0) + (-100))
 
    if bright != 0:
        if bright > 0:
            shadow = bright
            max = 255
        else:
            shadow = 0
            max = 255 + bright
        alf = (max - shadow) / 255
        gam = shadow
 
        cal = cv2.addWeighted(effect, alf,
                              effect, 0, gam) # changed edited to effect, alfa to alf
    else:
        cal = effect
 
    if contrast != 0:
        Alf2 = float(131 * (contrast + 127)) / (127 * (131 - contrast))
        Gam2 = 127 * (1 - Alf2)
 
        # The function addWeighted calculates
        # the weighted sum of two arrays
        cal = cv2.addWeighted(cal, Alf2,
                              cal, 0, Gam2)
    #cv2.imshow('CV2 Photo Editor', effect)
 
    return cal
 
 
def exitbutton_cb():
    window.destroy()
    cv2.destroyAllWindows()
 
 
window = tk.Tk()
window.title('Simple Photo Editing')
mb = Menu(window)
#file manager
fm = Menu(mb, tearoff=0)
fm.add_command(label="Open", command=insertbutton_cb)
fm.add_command(label="Save", command=savebutton_cb)
fm.add_separator()
#fm.add_command(label="Cancel Edit", command=pass)
fm.add_command(label="Exit", command=exitbutton_cb)
mb.add_cascade(label="File", menu=fm)
 
var1 = tk.StringVar(window)
var1.set(effectoption[0])
var1.get()
 
cr = ttk.Frame(window)
canvas = tk.Canvas(cr)
scrolling = ttk.Scrollbar(cr, orient="vertical", command=canvas.yview)
 
sw = window.winfo_screenwidth()
sh = window.winfo_screenheight()
 
Frm = tk.Frame(window, height=50, width=300)
Frm.pack(anchor=tk.N)
 
Frm2 = tk.Frame(window, height=25, width=100)
Frm2.pack(anchor=tk.NW)
 
#Frm3 = tk.Frame(window, height=50, width=500)
#Frm3.pack(anchor=tk.N)
 
#showWin = tk.Label(window, width=100, height=100)
#showWin.pack(side='left')
 
#showWin2 = tk.Label(window, width=100, height=100)
#showWin2.pack(side='left')
 
label = ttk.Label(
    window, text="Simple Image Photo Editing"
)
 
resetbutton = tk.Button(Frm, text="Reset", padx=0, pady=0, command=resetbutton_cb)
resetbutton.grid(row=0, column=1)
 
savebutton = tk.Button(Frm, text="Save", padx=0, pady=0, command=savebutton_cb)
savebutton.grid(row=0, column=2)
 
orima = None
editima = None
 
opt = tk.OptionMenu(window, var1, *effectoption, command=on_change)
opt.config(width=90, font=('Helvetica', 12))
opt.pack(side="top")
 
print(opt)
print(var1)
print(var1.get())
 
window.config(menu=mb)
cv2.waitKey(0)
tk.mainloop()

问题是如何正确实现选择一个选项替换“if elif”(多个if elif导致“elementwise比较失败;返回标量,但将来将执行elementwise比较)


Tags: imageifwindowcv2commandtkcolorprint
1条回答
网友
1楼 · 发布于 2024-06-17 11:12:04

这几乎不是最小的可重复的例子。执行effect == effectoption[0]时,右侧是字符串,因此左侧也必须是字符串。如果effect是一个包含字符串的列表,那么需要获取字符串元素。另外,您的on_change函数可能会简化很多,例如

def on_change(effect):
    effect_choice = getattr(cv2, "COLOR_BGR2"+effect.split()[1])
    edited = cv2.cvtColor(image, effect_choice)
    var1.set(effect)
    print(var1.get())
    print(effect)
一般来说,如果你发现自己使用^ {CD4>},你应该考虑是否有一种更简单的方法来做它。

相关问题 更多 >