[英]How to pass the file location from "askopenfilename" and use it for a second function
[英]How to parse 'askopenfilename' file pathway into another function?
我正在嘗試使用 Python 和 Tkinter 創建圖像分割應用程序。 我無法通過filedialog.askopenfilename
(用戶從文件上傳)獲取文件路徑,並通過單擊 Tkinter GUI 上的另一個按鈕通過圖像分割 function 解析圖像路徑。
因為我想要一個按鈕來收集文件路徑,所以我創建了一個 function 來綁定到按鈕,但是圖像分割 function 無法在文件路徑 ZC1C425268E68385D1AB4Z5074 中獲取路徑變量。 所以我創建了全局變量,但是,分段 function 無法讀取string
或NoneType
對象。 另外,我嘗試為所有這些創建一個class
但它沒有用。
這是兩個函數(分段函數需要decode_segmap
):
# Define the helper function
def decode_segmap(image, nc=21):
label_colors = np.array([(0, 0, 0), # 0=background
# 1=aeroplane, 2=bicycle, 3=bird, 4=boat, 5=bottle
(128, 0, 0), (0, 128, 0), (128, 128, 0), (0, 0, 128), (128, 0, 128),
# 6=bus, 7=car, 8=cat, 9=chair, 10=cow
(0, 128, 128), (128, 128, 128), (64, 0, 0), (192, 0, 0), (64, 128, 0),
# 11=dining table, 12=dog, 13=horse, 14=motorbike, 15=person
(192, 128, 0), (64, 0, 128), (192, 0, 128), (64, 128, 128), (192, 128, 128),
# 16=potted plant, 17=sheep, 18=sofa, 19=train, 20=tv/monitor
(0, 64, 0), (128, 64, 0), (0, 192, 0), (128, 192, 0), (0, 64, 128)])
r = np.zeros_like(image).astype(np.uint8)
g = np.zeros_like(image).astype(np.uint8)
b = np.zeros_like(image).astype(np.uint8)
for l in range(0, nc):
idx = image == l
r[idx] = label_colors[l, 0]
g[idx] = label_colors[l, 1]
b[idx] = label_colors[l, 2]
rgb = np.stack([r, g, b], axis=2)
return rgb
def segment(net, path):
img = Image.open(path)
plt.imshow(img); plt.axis('off'); plt.show()
# Comment the Resize and CenterCrop for better inference results
trf = T.Compose([T.Resize(256),
T.CenterCrop(224),
T.ToTensor(),
T.Normalize(mean = [0.485, 0.456, 0.406],
std = [0.229, 0.224, 0.225])])
inp = trf(img).unsqueeze(0)
out = net(inp)['out']
om = torch.argmax(out.squeeze(), dim=0).detach().cpu().numpy()
rgb = decode_segmap(om)
plt.imshow(rgb); plt.axis('off'); plt.show()
def open_img():
path = filedialog.askopenfilename(initialdir='/Downloads',title='Select Photo', filetypes=(('JPEG files', '*.jpg'),('PNG files', '*.png')))
img = Image.open(path)
plt.imshow(img); plt.axis('off'); plt.show()
Tkinter 代碼(兩幀,一幀用於按鈕,另一幀用於預覽圖像): 如您所見,段 function 有兩個參數, fcn
是神經網絡,是文件中的“全局”變量,但是路徑參數無法獲得,因為變量位於另一個 function 綁定到按鈕。
window = Tk()
window.geometry("500x300")
btn_frame = Frame(window, width=500, height=100)
btn_frame.pack(side="top", expand=True, fill="both")
bottom_frame = Frame(window, width=500, height=200)
bottom_frame.pack(side="bottom", expand=True, fill="both")
btn1 = Button(btn_frame, text="Open", width = 10, height = 1, cursor = "hand2", command=open_img)
btn1.pack(side="left")
btn2 = Button(btn_frame, text="Segment", width = 10, height = 1, cursor = "hand2", command=segment(net=fcn, path=path))
btn2.pack(side="left")
btn3 = Button(btn_frame, text="Save", width = 10, height = 1, cursor = "hand2")
btn3.pack(side="left")
window.mainloop()
任何幫助將不勝感激。
有3種方法可以解決這個問題,但首先:
command=function()
例如將 function 的返回值設置為“命令”,因為 function 將直接執行。 在您的示例中,它應該引發錯誤,因為路徑似乎尚未定義。
無論如何,這里有2個“解決方法”:
global path
放在open_img
的開頭,以便能夠全局設置路徑。 然后你就可以從你的segment
函數中刪除“路徑”參數,同時仍然讀取路徑變量的內容。self.path
或類似內容,以便您也可以在segment
中使用它。這是我的做法:
from tkinter import *
from PIL.ImageTk import Image, PhotoImage
import numpy as np
import matplotlib.pyplot as plt
#from ? import T
class App(Tk):
def __init__(self)
Tk.__init__(self)
self.geometry("500x300")
self.path = ''
btn_frame = Frame(self, width=500, height=100)
btn_frame.pack(side=TOP, expand=True, fill=BOTH)
btn_frame.pack_propagate(False) #otherwise your width and height options would be useless
bottom_frame = Frame(self, width=500, height=200)
bottom_frame.pack(side=BOTTOM, expand=True, fill=BOTH)
btn1 = Button(btn_frame, text="Open", width = 10, height = 1, cursor = "hand2", command=self.open_img)
btn1.pack(side=LEFT)
btn2 = Button(btn_frame, text="Segment", width = 10, height = 1, cursor = "hand2", command=self.segment)
#command=segment(net=fcn, path=path) would instantly execute the command but there is no path variable
btn2.pack(side=LEFT)
btn3 = Button(btn_frame, text="Save", width = 10, height = 1, cursor = "hand2")
btn3.pack(side=LEFT)
self.image_label = Label(bottom_frame)
self.image_label.pack(fill=BOTH, expand=True)
self.mainloop()
def decode_segmap(image, nc=21):
label_colors = np.array([(0, 0, 0), # 0=background
# 1=aeroplane, 2=bicycle, 3=bird, 4=boat, 5=bottle
(128, 0, 0), (0, 128, 0), (128, 128, 0), (0, 0, 128), (128, 0, 128),
# 6=bus, 7=car, 8=cat, 9=chair, 10=cow
(0, 128, 128), (128, 128, 128), (64, 0, 0), (192, 0, 0), (64, 128, 0),
# 11=dining table, 12=dog, 13=horse, 14=motorbike, 15=person
(192, 128, 0), (64, 0, 128), (192, 0, 128), (64, 128, 128), (192, 128, 128),
# 16=potted plant, 17=sheep, 18=sofa, 19=train, 20=tv/monitor
(0, 64, 0), (128, 64, 0), (0, 192, 0), (128, 192, 0), (0, 64, 128)])
r = np.zeros_like(image).astype(np.uint8)
g = np.zeros_like(image).astype(np.uint8)
b = np.zeros_like(image).astype(np.uint8)
for l in range(0, nc):
idx = image == l
r[idx] = label_colors[l, 0]
g[idx] = label_colors[l, 1]
b[idx] = label_colors[l, 2]
rgb = np.stack([r, g, b], axis=2)
return rgb
def segment(self, net):
#if an image is chosen path will be any other than ''
if path: img = Image.open(self.path)
else: return
plt.imshow(img); plt.axis('off'); plt.show()
# Comment the Resize and CenterCrop for better inference results
trf = T.Compose([T.Resize(256),
T.CenterCrop(224),
T.ToTensor(),
T.Normalize(mean = [0.485, 0.456, 0.406],
std = [0.229, 0.224, 0.225])])
inp = trf(img).unsqueeze(0)
out = net(inp)['out']
om = torch.argmax(out.squeeze(), dim=0).detach().cpu().numpy()
rgb = decode_segmap(om)
plt.imshow(rgb); plt.axis('off'); plt.show()
def open_img(self):
path = filedialog.askopenfilename(initialdir='/Downloads',title='Select Photo', filetypes=(('JPEG files', '*.jpg'),('PNG files', '*.png')))
if path:
self.path = path
img = PhotoImage(Image.open(path))
#img = tkinter.PhotoImage(file=path) should work too but then you'll need to remove the import of PILs PhotoImage
self.image_label.img = img #keep a reference to the image object
self.image_label.config(image=img)
#plt.imshow(img); plt.axis('off'); plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.