首页 > 解决方案 > 如何将在 tkinter 中上传的图像放入函数中?

问题描述

我正在尝试创建一个 Python tkinter 应用程序,用户可以在其中从文件上传图像,并且图像通过图像分割函数输出 matplotlib 图。

我有图像分割功能,它需要两个参数:神经网络,图像文件路径。

from torchvision import models
from PIL import Image
import matplotlib.pyplot as plt
import torch
import torchvision.transforms as T
import numpy as np


fcn = models.segmentation.fcn_resnet101(pretrained=True).eval()


# 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()

我没有制作 Tkinter GUI,因为我不确定如何获取从文件上传的图像并将其转换为文件路径(字符串)并将其放入函数中。目前只有一个神经网络,即fcn

标签: pythonnumpytkinterpytorch

解决方案


首先导入filedialogPIL

from tkinter import filedialog
from PIL import Image

现在使用变量路径(或任何东西)来定义当您在 GUI 内选择时返回的路径。

path = filedialog.askopenfilename(initialdir='/Downloads', title='Select Photo', filetypes=(('JPEG files', '*.jpg'), ('PNG files', '*.png')))

您可以通过在带有标题和“*.extension”的参数中指定它来使用您想要的任何文件类型。请注意,它是区分大小写的。现在您的变量path具有图像的路径,您所要做的就是使用 PIL 打开它

img = Image.open(path)

就像您在代码中所做的那样


推荐阅读