所以问题是我不久前开始使用python而且我正在尝试使用一些代码。基本上我正在尝试创建一个包含图像的窗口,当按下某些按钮时,图像会发生变化(大小,模糊等等)。我遇到的一些问题是模糊只会生效一次,调整大小效果在较大/较小的一个上方创建另一个图像,而后一个图像不被删除。有没有办法让这一切发挥作用?先感谢您。我可能使用了太多的代码行,我完全清楚它,因为我仍然没有足够的知识:)。
import tkinter
import cv2
import PIL.Image, PIL.ImageTk
def blur_image():
print("Blur")
global photo_blur
global cv_img_blur
cv_img_blur = cv2.blur(cv_img, (3, 3))
photo_blur = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(cv_img_blur))
canvas.create_image(0, 0, image=photo_blur, anchor=tkinter.NW)
def reduce_image():
print("Reduced")
global photo_reduce
global cv_img_reduce
cv_img_reduce = cv2.resize(cv_img, (0,0), fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
photo_reduce = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(cv_img_reduce))
canvas.create_image(0, 0, image=photo_reduce, anchor=tkinter.NW)
window = tkinter.Tk()
window.title("Project")
cv_img = cv2.cvtColor(cv2.imread("hqdefault.jpg"), cv2.COLOR_BGR2RGB)
height, width, no_channels = cv_img.shape
canvas = tkinter.Canvas(window, width = width, height = height)
canvas.pack()
photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(cv_img))
canvas.create_image(0, 0, image=photo, anchor=tkinter.NW)
btn_blur=tkinter.Button(window, text="Blur", width=50, command=blur_image)
btn_blur.pack(anchor=tkinter.CENTER, expand=True)
btn_reduce=tkinter.Button(window, text="Reduce", width=50, command=reduce_image)
btn_reduce.pack(anchor=tkinter.CENTER, expand=True)
window.mainloop()
尝试这样的事情
import tkinter
import cv2
import PIL.Image, PIL.ImageTk
blur_status = (3, 3)
def blur_image():
print("Blur")
global photo_blur, cv_img_blur, image, blur_status
cv_img_blur = cv2.blur(cv_img, blur_status)
photo_blur = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(cv_img_blur))
canvas.delete(image)
image = canvas.create_image(0, 0, image=photo_blur, anchor=tkinter.NW)
n1, n2 = blur_status
blur_status = (n1 + 1, n2 + 2)
def reduce_image():
print("Reduced")
global photo_reduce, cv_img_reduce, image
cv_img_reduce = cv2.resize(cv_img, (0,0), fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
photo_reduce = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(cv_img_reduce))
canvas.delete(image)
image = canvas.create_image(0, 0, image=photo_reduce, anchor=tkinter.NW)
window = tkinter.Tk()
window.title("Project")
cv_img = cv2.cvtColor(cv2.imread("home.png"), cv2.COLOR_BGR2RGB)
height, width, no_channels = cv_img.shape
canvas = tkinter.Canvas(window, width = width, height = height)
canvas.pack()
photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(cv_img))
image = canvas.create_image(0, 0, image=photo, anchor=tkinter.NW)
btn_blur = tkinter.Button(window, text="Blur", width=50, command=blur_image)
btn_blur.pack(anchor=tkinter.CENTER, expand=True)
btn_reduce = tkinter.Button(window, text="Reduce", width=50, command=reduce_image)
btn_reduce.pack(anchor=tkinter.CENTER, expand=True)
window.mainloop()
实际上,您调用的函数会叠加图像,因为它们始终创建新图像而不修改先前创建的图像,因此在创建新图像之前,您必须删除旧图像。模糊似乎只是第一次起作用,因为值总是设置为(3,3),因为它们总是设置为(3,3),如果你想“多次工作”,你必须在每次调用函数时增加值